核心场景
让星链4sapi调用外部工具(天气查询、接口请求、数据库查询等),实现“AI思考+工具执行”,比如用户问“今天北京天气”,AI自动调用天气接口返回结果,无需人工介入。
关键代码(Python 实操)
from openai import OpenAI
client = OpenAI(base_url="https://4sapi.ai/v1", api_key="你的API_KEY")
# 1. 定义工具(以天气查询为例)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定城市的实时天气",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称,如北京、上海"}
},
"required": ["city"]
}
}
}
]
# 2. 发起调用,让AI判断是否需要调用工具
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "查询今天北京的天气"}],
tools=tools,
tool_choice="auto" # 自动判断是否调用工具
)
# 3. 解析响应,执行工具(此处简化,实际需对接真实天气接口)
if response.choices[0].message.tool_calls:
tool_call = response.choices[0].message.tool_calls[0]
if tool_call.function.name == "get_weather":
city = eval(tool_call.function.arguments)["city"]
# 模拟调用天气接口,返回结果
weather_result = f"北京今日天气:晴,20-28℃,微风"
# 把工具结果回传给AI,生成最终回答
final_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "查询今天北京的天气"},
response.choices[0].message,
{"role": "tool", "tool_call_id": tool_call.id, "content": weather_result}
]
)
print(final_response.choices[0].message.content)
总结
核心是定义工具参数、开启tool_choice="auto",AI会自动判断是否需要调用工具,适配所有外部接口,实现AI与业务工具的联动。