维基百科帮助的写作助手
#调用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())
输出样例:
