OpenAI ChatGPT-4开发笔记2024-04:Chat之Tool之2:multiple functions
2024-01-08 08:36:56
从程序员到ai Expert
上一篇解决了调用一个函数的问题。这一篇扩展为调用3个。n个自行脑补。
1 设定目标
#1.设定目标
what_i_want_to_know = [{"role": "user", "content": f"汇总3个function的aiXpert的结果"}]
2 自定义function,3个
#2.自定义function,3个
def search_baidu(keyword):
return f"{keyword}是一个技术博主"
def search_google(keyword):
return f"{keyword}是一个后端工程师"
def search_bing(keyword):
return f"{keyword}是一个Python爱好者"
3 接口。自定义function—>ChatGPT
采用Tool的标准写法:
tools = [
{
"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 run_chat(messages):
response = openai.chat.completions.create(
model ="gpt-3.5-turbo-1106",
messages=messages,
tools =tools,
tool_choice="auto",
)
return response.choices[0].message
5 发起首次请求,告诉gpt要做什么,已经有哪些函数可以调动
first_response = run_chat(what_i_want_to_know)
tool_calls = first_response.tool_calls
6 大结局
# 检查是否需要调用函数
if tool_calls:
# 解析所有需要调用的函数及参数
what_i_want_to_know.append(first_response) # 注意这里要将openai的回复也拼接到消息列表里
# 将所有函数调用的结果拼接到消息列表里
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)
what_i_want_to_know.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
}
)
print(run_chat(what_i_want_to_know))
7 参考资料
文章来源:https://blog.csdn.net/longwo888/article/details/108245629
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!