ModelRiver 通过 tools、tool_choice 和 parallel_tool_calls 在所有供应商上支持 OpenAI 兼容的函数调用。工具定义、工具调用和工具结果始终使用 OpenAI 格式发送;对于有自己格式的供应商(Anthropic、Google Gemini、Amazon Bedrock、Cohere),ModelRiver 会自动转换,并以 OpenAI 格式返回工具调用。由于格式处处一致,包含工具调用的对话也可以从一个供应商故障转移到另一个供应商。
不想自己运行这个循环? 使用托管工具,你可以把函数注册为工作流上的 HTTPS 端点,由 ModelRiver 运行循环:调用这些端点、把结果交还给模型,并交付最终答案。开启了托管工具的工作流不接受请求中的
tools(400 tools_conflict);本页内容适用于未开启托管工具的工作流。
函数调用的工作方式
- 定义工具:描述你的应用可以执行哪些函数
- 发送请求:在消息中附带工具定义
- 接收
tool_calls:模型返回结构化函数调用,而不是纯文本 - 执行函数:由你的应用实际运行这些函数
- 回传结果:把函数结果再发回模型,继续对话
基础示例
Python
1from openai import OpenAI2 3client = OpenAI(4 base_url="https://api.modelriver.com/v1",5 api_key="mr_live_YOUR_API_KEY"6)7 8response = client.chat.completions.create(9 model="my_workflow",10 messages=[{"role": "user", "content": "What's the weather in Paris?"}],11 tools=[{12 "type": "function",13 "function": {14 "name": "get_weather",15 "description": "Get the current weather for a location",16 "parameters": {17 "type": "object",18 "properties": {19 "location": {20 "type": "string",21 "description": "City name"22 },23 "unit": {24 "type": "string",25 "enum": ["celsius", "fahrenheit"],26 "description": "Temperature unit"27 }28 },29 "required": ["location"]30 }31 }32 }],33 tool_choice="auto"34)35 36# Check if the model wants to call a function37message = response.choices[0].message38if message.tool_calls:39 for tool_call in message.tool_calls:40 print(f"Function: {tool_call.function.name}")41 print(f"Arguments: {tool_call.function.arguments}")42else:43 print(message.content)Node.js
1import OpenAI from "openai";2 3const client = new OpenAI({4 baseURL: "https://api.modelriver.com/v1",5 apiKey: "mr_live_YOUR_API_KEY",6});7 8const response = await client.chat.completions.create({9 model: "my_workflow",10 messages: [{ role: "user", content: "What's the weather in Paris?" }],11 tools: [{12 type: "function",13 function: {14 name: "get_weather",15 description: "Get the current weather for a location",16 parameters: {17 type: "object",18 properties: {19 location: { type: "string", description: "City name" },20 unit: { type: "string", enum: ["celsius", "fahrenheit"] },21 },22 required: ["location"],23 },24 },25 }],26 tool_choice: "auto",27});28 29const message = response.choices[0].message;30if (message.tool_calls) {31 for (const toolCall of message.tool_calls) {32 console.log(`Function: ${toolCall.function.name}`);33 console.log(`Arguments: ${toolCall.function.arguments}`);34 }35} else {36 console.log(message.content);37}带有 tool_calls 的响应
当模型决定调用函数时,响应中会包含 tool_calls 数组:
1{2 "choices": [{3 "index": 0,4 "message": {5 "role": "assistant",6 "content": null,7 "tool_calls": [{8 "id": "call_abc123",9 "type": "function",10 "function": {11 "name": "get_weather",12 "arguments": "{\"location\": \"Paris\", \"unit\": \"celsius\"}"13 }14 }]15 },16 "finish_reason": "tool_calls"17 }]18}响应字段说明
| 字段 | 说明 |
|---|---|
tool_calls[].id | 本次工具调用的唯一标识 |
tool_calls[].type | 恒为 "function" |
tool_calls[].function.name | 需要执行的函数名称 |
tool_calls[].function.arguments | 函数参数的 JSON 字符串 |
tool_calls[].extra_content | 仅当供应商需要随调用回传数据时出现,例如 Gemini 的 thought signature。请原样回传 |
finish_reason | 当模型要调用函数时,值为 "tool_calls" |
content | 有 tool_calls 时通常为 null |
多轮工具对话
在执行完模型请求的函数后,把结果回传给模型,就可以继续对话:
1import json2 3# Step 1: Initial request with tools4messages = [{"role": "user", "content": "What's the weather in Paris?"}]5 6response = client.chat.completions.create(7 model="my_workflow",8 messages=messages,9 tools=tools10)11 12message = response.choices[0].message13 14# Step 2: Execute the function15if message.tool_calls:16 # Add the assistant's message exactly as received (with tool_calls and17 # any extra_content on them)18 messages.append(message.model_dump(exclude_none=True))19 20 for tool_call in message.tool_calls:21 # Execute your function22 if tool_call.function.name == "get_weather":23 args = json.loads(tool_call.function.arguments)24 result = get_weather(args["location"]) # Your function25 26 # Add the function result27 messages.append({28 "role": "tool",29 "tool_call_id": tool_call.id,30 "content": json.dumps(result)31 })32 33 # Step 3: Get the final response34 final_response = client.chat.completions.create(35 model="my_workflow",36 messages=messages,37 tools=tools38 )39 40 print(final_response.choices[0].message.content)41 # Output: "The weather in Paris is currently 18°C and partly cloudy."每个工具结果都是一条 tool 消息,带有它所回应的调用的 tool_call_id。content 通常是字符串,也可以是文本内容块列表。如果模型一次发起了多个调用,请在助手消息之后按调用顺序为每个调用发送一条 tool 消息。
流式工具调用
使用 stream: true 时,工具调用以增量形式出现在 choices[0].delta.tool_calls 中。某个调用的第一个增量包含 index、id 和 function.name;之后同一 index 的增量会追加 function.arguments 的片段。最后一个数据块的 finish_reason 为 "tool_calls"。
1stream = client.chat.completions.create(2 model="my_workflow",3 messages=messages,4 tools=tools,5 stream=True,6)7 8calls = {}9for chunk in stream:10 if not chunk.choices:11 continue12 for delta in chunk.choices[0].delta.tool_calls or []:13 call = calls.setdefault(delta.index, {"id": None, "name": "", "arguments": ""})14 if delta.id:15 call["id"] = delta.id16 if delta.function and delta.function.name:17 call["name"] = delta.function.name18 if delta.function and delta.function.arguments:19 call["arguments"] += delta.function.argumentsModelRiver 暂不支持从 Amazon Bedrock 流式输出,因此 Bedrock 工作流会一次性返回完整回复(包括工具调用)。
工具选择选项
通过 tool_choice 参数控制模型如何使用工具:
| 值 | 行为 |
|---|---|
"auto" | 由模型决定是否调用函数(默认) |
"none" | 模型不会调用任何函数 |
"required" | 模型必须至少调用一个函数 |
{"type": "function", "function": {"name": "get_weather"}} | 强制调用指定函数 |
设置 parallel_tool_calls: false 可要求每次回复最多只调用一个工具。
1# Force the model to call a specific function2response = client.chat.completions.create(3 model="my_workflow",4 messages=messages,5 tools=tools,6 tool_choice={7 "type": "function",8 "function": {"name": "get_weather"}9 }10)多个工具
定义多个工具,让模型自行选择调用哪一个:
1tools = [2 {3 "type": "function",4 "function": {5 "name": "get_weather",6 "description": "Get weather for a location",7 "parameters": {8 "type": "object",9 "properties": {10 "location": {"type": "string"}11 },12 "required": ["location"]13 }14 }15 },16 {17 "type": "function",18 "function": {19 "name": "search_restaurants",20 "description": "Search for restaurants near a location",21 "parameters": {22 "type": "object",23 "properties": {24 "location": {"type": "string"},25 "cuisine": {"type": "string"},26 "max_results": {"type": "integer", "default": 5}27 },28 "required": ["location"]29 }30 }31 },32 {33 "type": "function",34 "function": {35 "name": "book_reservation",36 "description": "Book a table at a restaurant",37 "parameters": {38 "type": "object",39 "properties": {40 "restaurant_id": {"type": "string"},41 "date": {"type": "string", "format": "date"},42 "party_size": {"type": "integer"},43 "time": {"type": "string"}44 },45 "required": ["restaurant_id", "date", "party_size"]46 }47 }48 }49]模型可能在一次响应中调用多个工具。请逐个处理每个工具调用,并回传所有结果。
原生 API(/v1/ai)
POST /v1/ai 接受相同的 tools、tool_choice 和 parallel_tool_calls 字段以及相同的 tool 消息。非流式请求中,data 是 OpenAI 格式的供应商响应,工具调用位于 data.choices[0].message.tool_calls。使用 stream: true 时,会流式返回与上文相同的数据块。
供应商支持
所有供应商都支持工具调用。工作流所用的模型必须支持工具使用(即供应商页面上标有 Tools 的模型),否则供应商会返回错误。目录中的所有对话模型都支持,以下除外:OpenAI 和 Azure OpenAI 上的 GPT-6 Astra 与 GPT-6.1 Sol/Terra(它们的工具调用需要 Responses API,而 ModelRiver 使用 Chat Completions)、Amazon Bedrock 上的 GPT-6.1 Sol/Terra,以及 Cohere Command A Vision。使用托管工具时,ModelRiver 会自行检查:拒绝保存这类模型,并在运行时跳过它。
| 供应商 | 工具的发送方式 | 说明 |
|---|---|---|
| OpenAI、Azure OpenAI、xAI、DeepSeek、Qwen、Groq、Kimi、MiniMax、Custom | 以 OpenAI 格式原样转发 | |
| Mistral | 以 OpenAI 格式原样转发 | Mistral 只接受 9 个字符的工具调用 id,因此来自其他供应商的 id 会被映射为这种 id |
| Anthropic | 转换为 tool_use 和 tool_result 块 | 支持所有 tool_choice 取值和 parallel_tool_calls。Claude Opus 5.5、Sonnet 5.5、Fable 5.1 及更高版本、Mythos 5.1 及更高版本不接受 required 或指定函数的 tool_choice(它们总是先思考),因此对这些模型 ModelRiver 会发送 "auto",模型可能不调用工具而直接回答。这些模型在 Amazon Bedrock 上同样如此 |
| Google Gemini | 转换为 functionDeclarations、functionCall 和 functionResponse | 忽略 parallel_tool_calls。工具 schema 中的 additionalProperties 会被移除。Gemini 2.x 模型无法同时使用工具和结构化输出,因此发送工具时会去掉 schema。Gemini 3 模型会在 extra_content 中返回 thought signature,请原样回传助手消息 |
| Amazon Bedrock | 转换为 Converse 的 toolConfig、toolUse 和 toolResult | tool_choice: "none" 时不发送工具;一旦对话中已有工具调用,Bedrock 必须带上工具,模型仍可能调用。忽略 parallel_tool_calls。回复不会流式输出 |
| Cohere | 以 Cohere 的 tools 格式发送 | 指定函数的 tool_choice 只会发送该工具并要求调用它。忽略 parallel_tool_calls |
最佳实践
- 写清楚描述:函数描述直接影响模型是否调用它
- 使用
required字段:标明必填参数,避免调用不完整 - 校验参数:执行函数前始终校验解析后的参数,不要完全信任模型输出
- 处理未调用的情况:即使提供了工具,模型也可能直接回复文本
- 控制工具数量:工具太多会让模型混淆,保持列表精简
- 用
enum约束取值:减少函数参数出错 - 为函数执行设置超时:不要让工具执行无限期阻塞