欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 【在线大模型调用】tool use 实战

【在线大模型调用】tool use 实战

2025/9/15 7:04:39 来源:https://blog.csdn.net/qq_60245590/article/details/145370265  浏览:    关键词:【在线大模型调用】tool use 实战

维基百科帮助的写作助手

#调用API助手
import openai 
from openai import OpenAI
import json
client = OpenAI(api_key="sk-K2leZhvtujNSsf87JJCYKjuHnK9muUP",base_url="https://api.chatanywhere.tech/v1") 

1.定义工具箱函数(Json架构的注释) 

#1.定义工具箱函数(Json架构的注释)
article_search_tool = [{"type": "function","function":{"name": "get_article","description": "A tool to retrieve an up to date Wikipedia article.","parameters": {"type": "object","properties": {"search_term": {"type": "string","description": "The search term to find a wikipedia article by title"},},"required": ["search_term"]}}
}]

2.向GPT发送API请求,携带工具与问题(API调用) 

#2.向GPT发送API请求,携带工具与问题(API调用)
messages = [{"role": "user", "content": "2024年的奥运会在哪里举行,有什么特别之处"}]
response = client.chat.completions.create(model="gpt-4o-mini",messages=messages,tools=article_search_tool,tool_choice= {"type": "function","function": {"name": "get_article"}}
)  # 可选值:"auto","required", "none", {"type": "function","function": {"name": "function_name"}}

3.GPT决策并返回:工具名与入参 

#3.GPT决策并返回:工具名与入参
if response.choices[0].message.tool_calls:tool_call = response.choices[0].message.tool_calls[0].functionprint("工具函数的名字:",tool_call.name)print("工具函数的输入:",tool_call.arguments) 

4.本地执行工具函数,得到结果,同时记得要添加两次消息到历史对话中

#4.本地执行工具函数,得到结果,同时记得要添加两次消息到历史对话中
import wikipediadef get_article(search_term):results = wikipedia.search(search_term)first_result = results[0] #通常,第一个结果是与搜索词最相关的页面。page = wikipedia.page(first_result, auto_suggest=False) #获取与该标题对应的页面对象,然后通过 page.content 获取该页面的内容。return page.contentarticle = get_article("西游记")
print(article[:500]) 
if tool_call.name == "get_article":arguments = json.loads(tool_call.arguments)search_term = arguments.get("search_term")wiki_result = get_article(search_term)print(f"搜索到了 {search_term}")print("维基百科的原文:")print(wiki_result[:500])
function_call_result_message = {"role": "tool","content": json.dumps({"article": wiki_result,}),"tool_call_id": response.choices[0].message.tool_calls[0].id
}
messages.append(response.choices[0].message)
messages.append(function_call_result_message)

5.向GPT提供本地执行的工具结果, GPT处理结果与上下文,加工出最终回答 

#5.向GPT提供本地执行的工具结果, GPT处理结果与上下文,加工出最终回答
response = client.chat.completions.create(model="gpt-4o-mini",messages=messages,tools=article_search_tool,tool_choice= "auto"
)  # 可选值:"auto","required", "none", {"type": "function","function": {"name": "function_name"}}
print(response.choices[0].message.content.strip())

输出样例: 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词