跳到主要内容

Function Calling

Chat Completions API(流式)

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"]
}
}
}
]

stream = client.chat.completions.create(
model="gpt-5.4",
messages=[{"role": "user", "content": "北京今天天气怎么样?"}],
tools=tools,
tool_choice="auto",
stream=True,
)

tool_call_args = ""
tool_call_name = ""
for chunk in stream:
delta = chunk.choices[0].delta
if delta.tool_calls:
for tc in delta.tool_calls:
if tc.function.name:
tool_call_name = tc.function.name
if tc.function.arguments:
tool_call_args += tc.function.arguments
if chunk.choices[0].finish_reason == "tool_calls":
args = json.loads(tool_call_args)
print(f"调用函数: {tool_call_name}, 参数: {args}")

Responses API

from openai import OpenAI

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

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

response = client.responses.create(
model="gpt-5.4",
input="上海今天天气怎么样?",
tools=tools,
)

for output in response.output:
if output.type == "function_call":
print(f"调用函数: {output.name}, 参数: {output.arguments}")