从程序员到ai Expert
- 1 定义参数和函数
- 2 第一轮chatgpt
- 3 第一轮结果和function定义全部加入prompt再喂给chatgpt
- 4 大结局
- 7 参考资料
上一篇解决了调用一个函数的问题。这一篇扩展为调用3个。n个自行脑补。
1 定义参数和函数
#1.设定目标
import json
import openai
#1.定义parameters for text completion
ai_prompt = [
{
"role": "user",
"content": f"汇总3个function的aiXpert的结果"
}
]
#2.定义self-function,3个
def search_baidu(keyword):
return f"{keyword}是一个技术博主"
def search_google(keyword):
return f"{keyword}很牛"
def search_bing(keyword):
return f"{keyword}喜欢水鱼"
#3.设置参数
ai_function = [
{
"type": "function",
"function": {
"name": "search_baidu",
"parameters": {
"type": "object",
"properties": {
"keyword": {
"type": "string",
}
},
"required": ["keyword"],
},
}
},
{
"type": "function",
"function": {
"name": "search_google",
"parameters": {
"type": "object",
"properties": {
"keyword": {
"type": "string",
}
},
"required": ["keyword"],
},
}
},
{
"type": "function",
"function": {
"name": "search_bing",
"parameters": {
"type": "object",
"properties": {
"keyword": {
"type": "string",
}
},
"required": ["keyword"],
},
}
}
]
available_functions = { "search_baidu": search_baidu, "search_google": search_google, "search_bing": search_bing }
#4.define function to call ChatGPT
def chat_completions(parameter_message):
response = openai.chat.completions.create(
model ="gpt-3.5-turbo-1106",
messages=parameter_message,
tools =ai_function,
tool_choice="auto",
)
return response.choices[0].message
2 第一轮chatgpt
#5.发起首次请求,告诉gpt要做什么,已经有哪些函数可以调动
first_response = chat_completions(ai_prompt)
tool_calls = first_response.tool_calls
3 第一轮结果和function定义全部加入prompt再喂给chatgpt
# 第一轮chat completions的结果加入prompt,再把function参数加入prompt,然后一起喂给chatgpt
if tool_calls:
ai_prompt.append(first_response) # 第一轮chat completions的结果加入prompt,
# 将所有函数调用的结果拼接到消息列表里
for tool_call in tool_calls:
function_name = tool_call.function.name
function_to_call = available_functions[function_name]
function_args = json.loads(tool_call.function.arguments)
function_response = function_to_call(**function_args)
ai_prompt.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
}
)
print(chat_completions(ai_prompt))
4 大结局
ChatCompletionMessage(
content='根据三个搜索引擎的结果,
"AIxPert" 是一个技术博主,非常牛,也喜欢水鱼。',
role='assistant',
function_call=None,
tool_calls=None)
7 参考资料
- OpenAI的多函数调用(Multiple Function Calling)简介
- OpenAI API