import OpenAI from "openai";
const API_KEY = "你的密钥";
const client = new OpenAI({
apiKey: API_KEY,
baseURL: "https://moxus.cloud/v1",
});
function getWeather(city) {
// 实际项目中在这里调用天气 API。
return { temp: "25℃", condition: "晴", city };
}
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "查询指定城市的当前天气",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "城市名称" },
},
required: ["city"],
},
},
},
];
const messages = [{ role: "user", content: "北京今天天气怎么样?" }];
const response = await client.chat.completions.create({
model: "gpt-5.4-mini",
messages,
tools,
tool_choice: "auto",
});
const message = response.choices[0].message;
if (message.tool_calls?.length) {
messages.push(message);
for (const call of message.tool_calls) {
if (call.function.name !== "get_weather") {
throw new Error(`未允许调用工具:${call.function.name}`);
}
const args = JSON.parse(call.function.arguments);
const result = getWeather(args.city);
messages.push({
role: "tool",
tool_call_id: call.id,
content: JSON.stringify(result),
});
}
const final = await client.chat.completions.create({
model: "gpt-5.4-mini",
messages,
tools,
});
console.log(final.choices[0].message.content);
} else {
console.log(message.content);
}