跳到主要内容

Function Calling

from openai import OpenAI
import json

client = OpenAI(api_key="your-api-key", base_url="https://www.cheapertoken.work/v1")

tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"],
},
},
}
]

response = client.chat.completions.create(
model="gemini-2.5-flash",
messages=[{"role": "user", "content": "上海今天天气怎么样?"}],
tools=tools,
tool_choice="auto",
)

tool_call = response.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
print(f"调用函数: {tool_call.function.name}, 参数: {args}")