Function Calling
- Python
- JavaScript
- curl
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}")
import OpenAI from "openai";
const client = new OpenAI({ apiKey: "your-api-key", baseURL: "https://www.cheapertoken.work/v1" });
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "获取指定城市的天气",
parameters: {
type: "object",
properties: { city: { type: "string", description: "城市名称" } },
required: ["city"],
},
},
},
];
const response = await client.chat.completions.create({
model: "gemini-2.5-flash",
messages: [{ role: "user", content: "上海今天天气怎么样?" }],
tools,
tool_choice: "auto",
});
const toolCall = response.choices[0].message.tool_calls[0];
const args = JSON.parse(toolCall.function.arguments);
console.log(`调用函数: ${toolCall.function.name}, 参数:`, args);
curl https://www.cheapertoken.work/v1/chat/completions \
-H "Authorization: Bearer your-api-key" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-2.5-flash",
"messages": [{"role": "user", "content": "上海今天天气怎么样?"}],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string", "description": "城市名称"}},
"required": ["city"]
}
}
}],
"tool_choice": "auto"
}'