Responses API
OpenAI 兼容的 Responses API。支持推理、工具调用、网络搜索和结构化输出。
POST /v1/responses
请求示例
- Curl
- Python
- TypeScript
- Java
- Go
- PHP
- Ruby
- C#
curl https://gw.opentoken.io/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPEN_TOKEN_KEY" \
-d '{
"model": "gpt-4o",
"input": "人工智能的未来发展趋势是什么?",
"instructions": "你是 AI 领域的专家,请给出专业深入的分析。",
"reasoning": {"effort": "high"}
}'
import os
import requests
response = requests.post(
"https://gw.opentoken.io/v1/responses",
headers={
"Authorization": f"Bearer {os.environ['OPEN_TOKEN_KEY']}",
"Content-Type": "application/json",
},
json={
"model": "gpt-4o",
"input": "人工智能的未来发展趋势是什么?",
"instructions": "你是 AI 领域的专家,请给出专业深入的分析。",
"reasoning": {"effort": "high"},
},
)
response.raise_for_status()
print(response.json())
const apiKey = process.env.OPEN_TOKEN_KEY;
if (!apiKey) {
throw new Error("OPEN_TOKEN_KEY is not set");
}
const response = await fetch("https://gw.opentoken.io/v1/responses", {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-4o",
input: "人工智能的未来发展趋势是什么?",
instructions: "你是 AI 领域的专家,请给出专业深入的分析。",
reasoning: { effort: "high" },
}),
});
if (!response.ok) {
throw new Error(`Request failed: ${response.status} ${response.statusText}`);
}
console.log(await response.json());
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ResponsesApi {
public static void main(String[] args) throws Exception {
String apiKey = System.getenv("OPEN_TOKEN_KEY");
if (apiKey == null || apiKey.isBlank()) {
throw new IllegalStateException("OPEN_TOKEN_KEY is not set");
}
String json = "{"
+ "\"model\":\"gpt-4o\","
+ "\"input\":\"人工智能的未来发展趋势是什么?\","
+ "\"instructions\":\"你是 AI 领域的专家,请给出专业深入的分析。\","
+ "\"reasoning\":{\"effort\":\"high\"}"
+ "}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://gw.opentoken.io/v1/responses"))
.header("Authorization", "Bearer " + apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new IllegalStateException("Request failed: " + response.statusCode() + " " + response.body());
}
System.out.println(response.body());
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
apiKey := os.Getenv("OPEN_TOKEN_KEY")
if apiKey == "" {
panic("OPEN_TOKEN_KEY is not set")
}
payload := map[string]interface{}{
"model": "gpt-4o",
"input": "人工智能的未来发展趋势是什么?",
"instructions": "你是 AI 领域的专家,请给出专业深入的分析。",
"reasoning": map[string]string{"effort": "high"},
}
body, err := json.Marshal(payload)
if err != nil {
panic(err)
}
request, err := http.NewRequest(
http.MethodPost,
"https://gw.opentoken.io/v1/responses",
bytes.NewReader(body),
)
if err != nil {
panic(err)
}
request.Header.Set("Authorization", "Bearer "+apiKey)
request.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
responseBody, _ := io.ReadAll(response.Body)
if response.StatusCode < 200 || response.StatusCode >= 300 {
panic(fmt.Sprintf("request failed: %s: %s", response.Status, responseBody))
}
fmt.Println(string(responseBody))
}
<?php
$apiKey = getenv('OPEN_TOKEN_KEY');
if (!$apiKey) {
throw new RuntimeException('OPEN_TOKEN_KEY is not set');
}
$ch = curl_init('https://gw.opentoken.io/v1/responses');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'model' => 'gpt-4o',
'input' => '人工智能的未来发展趋势是什么?',
'instructions' => '你是 AI 领域的专家,请给出专业深入的分析。',
'reasoning' => ['effort' => 'high'],
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
]);
$body = curl_exec($ch);
if ($body === false) {
throw new RuntimeException(curl_error($ch));
}
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode < 200 || $statusCode >= 300) {
throw new RuntimeException("Request failed: $statusCode $body");
}
echo $body, PHP_EOL;
require 'json'
require 'net/http'
require 'uri'
api_key = ENV.fetch('OPEN_TOKEN_KEY')
uri = URI('https://gw.opentoken.io/v1/responses')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request['Authorization'] = "Bearer #{api_key}"
request['Content-Type'] = 'application/json'
request.body = {
model: 'gpt-4o',
input: '人工智能的未来发展趋势是什么?',
instructions: '你是 AI 领域的专家,请给出专业深入的分析。',
reasoning: { effort: 'high' },
}.to_json
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "Request failed: #{response.code} #{response.body}"
end
puts response.body
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
var apiKey = Environment.GetEnvironmentVariable("OPEN_TOKEN_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
throw new InvalidOperationException("OPEN_TOKEN_KEY is not set");
}
using var client = new HttpClient();
using var request = new HttpRequestMessage(
HttpMethod.Post,
"https://gw.opentoken.io/v1/responses");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
request.Content = new StringContent(JsonSerializer.Serialize(new
{
model = "gpt-4o",
input = "人工智能的未来发展趋势是什么?",
instructions = "你是 AI 领域的专家,请给出专业深入的分析。",
reasoning = new { effort = "high" },
}), Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
Console.WriteLine(body);
请求参数
| 参数 | 类型 | 必填 | 默认值 | 描述 |
|---|---|---|---|---|
| model | string | 是 | - | 模型 ID,例如 gpt-4o |
| input | string / array | 是 | - | 用户输入文本或消息数组 |
| instructions | string | 否 | - | 系统指令,定义模型行为 |
| max_output_tokens | integer | 否 | - | 限制本次响应可生成的最大输出 token 数;实际输出长度可能因停止条件、上下文长度或模型限制而更短。 |
| temperature | number | 否 | 1.0 | 采样温度,用于控制生成过程中的随机性。较低的值通常会使输出更稳定、可预测;较高的值通常会增加输出的多样性。 |
| top_p | number | 否 | 1.0 | 核采样参数,用于将每一步采样限制在累计概率达到 top_p 的候选集合内。 |
| tools | array | 否 | - | 工具定义:function、web_search_preview、file_search |
| tool_choice | string / object | 否 | auto | 工具选择策略 |
| text | object | 否 | - | 文本输出配置,可通过 format 设置结构化输出 |
| reasoning | object | 否 | - | 推理配置:{"effort":"high"} |
| previous_response_id | string | 否 | - | 继续之前的对话响应 |
| truncation | string | 否 | disabled | 截断策略:auto / disabled |
| metadata | object | 否 | - | 自定义元数据 |
| stream | boolean | 否 | false | 启用流式输出 |
JSON Schema 结构化输出
{
"input": "分析这段文本的情感",
"text": {
"format": {
"type": "json_schema",
"name": "sentiment",
"schema": {
"type": "object",
"properties": {
"sentiment": {"type": "string", "enum": ["positive", "negative", "neutral"]},
"score": {"type": "number"}
},
"required": ["sentiment", "score"]
},
"strict": true
}
}
}
Tool Calling
{
"input": "帮我查一下旧金山今天的天气",
"tools": [
{"type": "web_search_preview"},
{
"type": "function",
"name": "get_weather",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
}
}
}
]
}
响应结构
| 字段 | 类型 | 描述 |
|---|---|---|
| id | string | 响应 ID |
| object | string | 固定为 response |
| status | string | 完成状态:completed、failed、in_progress |
| output | array | 输出内容数组,每条含 type 和 content |
| usage | object | Token 用量统计 |