1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| from openai import OpenAI import json
client = OpenAI()
tools = [ { "type": "function", "function": { "name": "search_knowledge_base", "description": "搜索公司知识库,查找相关文档", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "搜索关键词", }, "category": { "type": "string", "enum": ["hr", "tech", "product", "finance"], "description": "知识库分类", }, }, "required": ["query"], }, }, }, { "type": "function", "function": { "name": "get_current_weather", "description": "获取指定城市的当前天气", "parameters": { "type": "object", "properties": { "city": {"type": "string", "description": "城市名称"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["city"], }, }, }, ]
messages = [{"role": "user", "content": "北京今天天气怎么样?"}]
response = client.chat.completions.create( model="gpt-4", messages=messages, tools=tools, tool_choice="auto", )
if response.choices[0].message.tool_calls: tool_call = response.choices[0].message.tool_calls[0] function_name = tool_call.function.name arguments = json.loads(tool_call.function.arguments) print(f"模型决定调用: {function_name}") print(f"参数: {arguments}") weather_result = get_current_weather(**arguments) messages.append(response.choices[0].message) messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(weather_result, ensure_ascii=False), }) final_response = client.chat.completions.create( model="gpt-4", messages=messages, ) print(final_response.choices[0].message.content)
|