Logo
Section 1 / 3

结构化输出与工具兼容性

使用 response_format 参数在模型响应上强制执行严格的 JSON Schema,并实现构成代理型 AI 应用基础的三步工具调用流程。本课还介绍了 OpenRouter 插件(网络搜索、响应修复和 PDF 处理),这些插件可扩展任何支持的提供者上的模型能力。

导入

结构化输出与工具兼容性

使用 response_format 参数在模型响应上强制执行严格的 JSON Schema,并实现构成代理型 AI 应用基础的三步工具调用流程。本课还介绍了 OpenRouter 插件(网络搜索、响应修复和 PDF 处理),这些插件可扩展任何支持的提供者上的模型能力。

使用 response_format 的示例请求

1{ 2 "model": "openai/gpt-5.4", 3 "messages": [ 4 { "role": "user", "content": "Extract info: John Doe is 32 years old." } 5 ], 6 "response_format": { 7 "type": "json_schema", 8 "json_schema": { 9 "name": "user_extraction", 10 "strict": true, 11 "schema": { 12 "type": "object", 13 "properties": { 14 "name": { "type": "string" }, 15 "age": { "type": "integer" } 16 }, 17 "required": ["name", "age"], 18 "additionalProperties": false 19 } 20 } 21 } 22}
1import os 2import json 3import requests 4 5api_key = os.getenv("OPENROUTER_API_KEY") 6 7response = requests.post( 8 url="https://openrouter.ai/api/v1/chat/completions", 9 headers={ 10 "Authorization": f"Bearer {api_key}", 11 "Content-Type": "application/json", 12 }, 13 json={ 14 "model": "openai/gpt-5.4", 15 "messages": [ 16 {"role": "user", "content": "Extract info: John Doe is 32 years old."} 17 ], 18 "response_format": { 19 "type": "json_schema", 20 "json_schema": { 21 "name": "user_extraction", 22 "strict": True, 23 "schema": { 24 "type": "object", 25 "properties": { 26 "name": {"type": "string"}, 27 "age": {"type": "integer"} 28 }, 29 "required": ["name", "age"], 30 "additionalProperties": False 31 } 32 } 33 } 34 } 35) 36 37content = response.json()["choices"][0]["message"]["content"] 38user = json.loads(content) 39print(f"Name: {user['name']}, Age: {user['age']}")
1import os 2import json 3import requests 4 5api_key = os.getenv("OPENROUTER_API_KEY") 6 7# Define the tool the model is allowed to call 8tools = [ 9 { 10 "type": "function", 11 "function": { 12 "name": "get_weather", 13 "description": "Returns the current weather for a given city.", 14 "parameters": { 15 "type": "object", 16 "properties": { 17 "location": { 18 "type": "string", 19 "description": "The city name, e.g. 'London'" 20 } 21 }, 22 "required": ["location"], 23 "additionalProperties": False 24 } 25 } 26 } 27] 28 29messages = [ 30 {"role": "user", "content": "What's the weather like in Paris right now?"} 31] 32 33# Step 1: Send the request with tool definitions 34response = requests.post( 35 url="https://openrouter.ai/api/v1/chat/completions", 36 headers={ 37 "Authorization": f"Bearer {api_key}", 38 "Content-Type": "application/json", 39 }, 40 json={ 41 "model": "openai/gpt-5.4", 42 "messages": messages, 43 "tools": tools, 44 "tool_choice": "auto" 45 } 46) 47 48assistant_message = response.json()["choices"][0]["message"] 49tool_calls = assistant_message.get("tool_calls", []) 50 51if tool_calls: 52 tool_call = tool_calls[0] 53 arguments = json.loads(tool_call["function"]["arguments"]) 54 print(f"Model requested tool: get_weather({arguments['location']})") 55 56 # Step 2: Execute the tool 57 # In a real application, this would call a live weather API. 58 tool_result = "Partly cloudy, 18°C" 59 60 # Step 3: Append the tool result and send a second request 61 messages.append(assistant_message) 62 messages.append({ 63 "role": "tool", 64 "tool_call_id": tool_call["id"], 65 "content": tool_result 66 }) 67 68 final_response = requests.post( 69 url="https://openrouter.ai/api/v1/chat/completions", 70 headers={ 71 "Authorization": f"Bearer {api_key}", 72 "Content-Type": "application/json", 73 }, 74 json={ 75 "model": "openai/gpt-5.4", 76 "messages": messages, 77 "tools": tools 78 } 79 ) 80 81 print(final_response.json()["choices"][0]["message"]["content"]) 82 # Output: The weather in Paris is currently partly cloudy at 18°C.
1import os 2import requests 3 4api_key = os.getenv("OPENROUTER_API_KEY") 5 6response = requests.post( 7 url="https://openrouter.ai/api/v1/chat/completions", 8 headers={ 9 "Authorization": f"Bearer {api_key}", 10 "Content-Type": "application/json", 11 }, 12 json={ 13 "model": "openai/gpt-5.4", 14 "messages": [ 15 {"role": "user", "content": "What are the top AI model releases from the last 7 days?"} 16 ], 17 "plugins": [ 18 {"id": "web", "max_results": 5} 19 ] 20 } 21) 22 23print(response.json()["choices"][0]["message"]["content"])

成本、性能与优化

构建多模型生产工作流