# Responses API

OpenAI Responses 协议，适合使用新版 OpenAI SDK、内置工具（联网、文件检索、代码执行等）以及需要服务端保存上下文的应用。

**接口地址**：`POST https://YOUR_API_BASE_URL/v1/responses`

- 鉴权：Bearer Token
- Content-Type：application/json

input 为必填输入；stream 为 true 时返回 SSE 事件流。

## 请求头

| 请求头 | 必填 | 值 |
| --- | --- | --- |
| `Authorization` | 是 | `Bearer sk-xxxxxxxx` |
| `Content-Type` | 是 | `application/json` |

## 请求体参数

| 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `model` | string | 是 | 支持 Responses 协议的模型 ID |
| `input` | string \| array | 是 | 输入文本或输入项数组 |
| `instructions` | string | 否 | 系统级指令，相当于 system prompt |
| `max_output_tokens` | integer | 否 | 输出 token 上限，部分模型包含推理 token |
| `temperature` | number | 否 | 采样温度 |
| `top_p` | number | 否 | 核采样 |
| `stream` | boolean | 否 | 是否流式返回，默认 `false` |
| `store` | boolean | 否 | 是否保存响应以便后续引用，默认值由服务配置决定 |
| `previous_response_id` | string | 否 | 引用上一轮响应，实现多轮对话 |
| `tools` | array | 否 | 工具列表，支持函数与内置工具 |
| `tool_choice` | string \| object | 否 | `none`、`auto`、`required` 或指定工具 |
| `parallel_tool_calls` | boolean | 否 | 是否允许并行工具调用 |
| `reasoning` | object | 否 | 推理配置，如 `{"effort":"medium","summary":"auto"}` |
| `text` | object | 否 | 输出格式配置，如 JSON Schema |
| `truncation` | string | 否 | `auto` 或 `disabled` |
| `background` | boolean | 否 | 后台模式，适合长任务（模型相关） |
| `metadata` | object | 否 | 自定义元数据 |
| `include` | string[] | 否 | 要求返回额外的输出项 |
| `service_tier` | string | 否 | 服务等级 |
| `user` | string | 否 | 终端用户标识 |

**注意**

Chat Completions 的 `messages` **不能**直接作为 Responses 的顶层字段；请使用 `input`。同理，`max_tokens` 应改为 `max_output_tokens`。

## input 的两种写法

### 字符串

```json
{
  "model": "YOUR_MODEL",
  "input": "用一句话解释什么是 API。"
}
```

### 输入项数组

```json
{
  "model": "YOUR_MODEL",
  "input": [
    {
      "type": "message",
      "role": "user",
      "content": [
        { "type": "input_text", "text": "请描述这张图片。" },
        {
          "type": "input_image",
          "image_url": "https://media.example.com/reference.jpg",
          "detail": "auto"
        }
      ]
    }
  ]
}
```

常用输入项：

| type | 结构 | 说明 |
| --- | --- | --- |
| `message` | `{type, role, content}` | 对话消息；`role` 为 `user` / `assistant` / `system` / `developer` |
| `input_text` | `{type:"input_text", text}` | 消息中的文本块 |
| `input_image` | `{type:"input_image", image_url, detail}` | 图片块，`image_url` 是字符串 |
| `input_file` | `{type:"input_file", file_id}` 或 `file_url` | 文件输入 |
| `function_call_output` | `{type:"function_call_output", call_id, output}` | 工具执行结果 |
| `item_reference` | `{type:"item_reference", id}` | 引用之前的输出项 |

## 基础调用

**cURL**

```bash
curl "https://YOUR_API_BASE_URL/v1/responses" \
  -H "Authorization: Bearer sk-xxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_MODEL",
    "instructions": "你是一个简洁的技术助手。",
    "input": "用一句话解释什么是向量检索。",
    "stream": false
  }'
```

**Python**

```python
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ["API_KEY"],
    base_url=os.environ["API_BASE"] + "/v1",
)

resp = client.responses.create(
    model="YOUR_MODEL",
    instructions="你是一个简洁的技术助手。",
    input="用一句话解释什么是向量检索。",
)
print(resp.output_text)
```

**Node.js**

```javascript
import OpenAI from 'openai'

const client = new OpenAI({
  apiKey: process.env.API_KEY,
  baseURL: process.env.API_BASE + '/v1'
})

const resp = await client.responses.create({
  model: 'YOUR_MODEL',
  instructions: '你是一个简洁的技术助手。',
  input: '用一句话解释什么是向量检索。'
})
console.log(resp.output_text)
```

## 成功响应

HTTP `200`：

```json
{
  "id": "resp_example",
  "object": "response",
  "created_at": 1788566400,
  "status": "completed",
  "model": "YOUR_MODEL",
  "output": [
    {
      "id": "msg_example",
      "type": "message",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "向量检索是把文本转换为向量后，按相似度查找相关内容的方法。",
          "annotations": []
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "tool_choice": "auto",
  "tools": [],
  "usage": {
    "input_tokens": 22,
    "output_tokens": 28,
    "total_tokens": 50
  },
  "previous_response_id": null,
  "store": true,
  "truncation": "disabled",
  "metadata": {}
}
```

| 字段 | 说明 |
| --- | --- |
| `id` | 响应 ID，可用于 `previous_response_id` |
| `object` | 固定为 `response` |
| `status` | `completed`、`in_progress`、`failed`、`incomplete` 等 |
| `output` | 输出项数组，可能包含推理、消息、工具调用等 |
| `output[].type` | `message`、`reasoning`、`function_call`、`web_search_call` 等 |
| `output[].content[]` | 消息内容块；文本为 `type: "output_text"` |
| `usage` | token 用量，字段为 `input_tokens` / `output_tokens` |
| `error` | 失败时的错误信息 |

**提示**

读取文本时要遍历 `output`，找到 `type: "message"` 的项，再提取 `content` 中 `type: "output_text"` 的 `text`。不要假设第一个输出项一定是消息，推理模型可能先返回 `reasoning` 项。

## 多轮对话

使用 `store: true` 保存响应，下一轮只传新增输入和 `previous_response_id`：

```json
{
  "model": "YOUR_MODEL",
  "input": "再举一个生活中的例子。",
  "previous_response_id": "resp_example",
  "store": true
}
```

也可以不使用服务端状态，把历史消息完整放进 `input` 数组。两种方式不要混用，避免上下文重复。

## 工具调用

Responses 的函数工具结构是**扁平**的，与 Chat Completions 的嵌套 `function` 不同：

```json
{
  "model": "YOUR_MODEL",
  "input": "北京今天天气怎么样？",
  "tools": [
    {
      "type": "function",
      "name": "get_weather",
      "description": "查询指定城市的天气",
      "parameters": {
        "type": "object",
        "properties": {
          "city": { "type": "string" }
        },
        "required": ["city"]
      },
      "strict": true
    }
  ],
  "tool_choice": "auto"
}
```

模型返回 `function_call` 输出项后，执行函数并把结果作为 `function_call_output` 输入继续：

```json
{
  "model": "YOUR_MODEL",
  "previous_response_id": "resp_example",
  "input": [
    {
      "type": "function_call_output",
      "call_id": "call_example",
      "output": "{\"temperature\":26,\"weather\":\"晴\"}"
    }
  ],
  "tools": [ ... ]
}
```

### 内置工具

| type | 用途 |
| --- | --- |
| `web_search` | 联网搜索 |
| `file_search` | 在向量库中检索文件 |
| `code_interpreter` | 运行代码 |
| `image_generation` | 生成图片 |
| `mcp` | 调用 MCP 服务 |
| `computer_use_preview` | 计算机操作（预览） |

内置工具需要模型支持；不支持时返回 `400`。字段细节以模型能力为准。

## 结构化输出

```json
{
  "model": "YOUR_MODEL",
  "input": "张三，32 岁，住在杭州。请抽取人物信息。",
  "text": {
    "format": {
      "type": "json_schema",
      "name": "person",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "name": { "type": "string" },
          "age": { "type": "integer" },
          "city": { "type": "string" }
        },
        "required": ["name", "age", "city"],
        "additionalProperties": false
      }
    }
  }
}
```

## 流式响应

设置 `"stream": true` 后返回 SSE，每个事件都是 JSON：

```text
event: response.created
data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_example","status":"in_progress"}}

event: response.output_text.delta
data: {"type":"response.output_text.delta","sequence_number":1,"item_id":"msg_example","output_index":0,"content_index":0,"delta":"向量"}

event: response.output_text.delta
data: {"type":"response.output_text.delta","sequence_number":2,"item_id":"msg_example","output_index":0,"content_index":0,"delta":"检索"}

event: response.completed
data: {"type":"response.completed","sequence_number":3,"response":{"id":"resp_example","status":"completed"}}
```

常见事件：

| 事件 | 说明 |
| --- | --- |
| `response.created` | 响应开始 |
| `response.in_progress` | 正在生成 |
| `response.output_item.added` | 新增输出项 |
| `response.content_part.added` | 新增内容块 |
| `response.output_text.delta` | 文本增量 |
| `response.output_text.done` | 文本结束 |
| `response.output_item.done` | 输出项结束 |
| `response.completed` | 全部完成 |
| `response.failed` | 失败 |
| `error` | 流内错误 |

SDK 通常提供 `client.responses.stream(...)` 或事件迭代器，按 `event.type` 处理即可。原始 HTTP 客户端需要先解析 `event:` 与 `data:` 两行。

## 查询与后台模式

部分模型支持：

```http
GET /v1/responses/{response_id}
```

用于查询后台模式（`background: true`）或已保存响应的状态。是否可用取决于模型与服务配置；不支持时返回 `404`。

## 上下文压缩

**接口地址**：`POST https://YOUR_API_BASE_URL/v1/responses/compact`

- 鉴权：Bearer Token
- Content-Type：application/json

把较长的对话历史压缩为更短的上下文，适合持续多轮的 Agent。

请求字段：

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `model` | string | 模型 ID |
| `input` | string \| array | 需要压缩的输入 |
| `instructions` | string | 指令 |
| `previous_response_id` | string | 关联的上一轮响应 |
| `tools` | array | 工具定义 |
| `parallel_tool_calls` | boolean | 并行工具开关 |
| `reasoning` | object | 推理配置 |
| `text` | object | 输出格式 |
| `service_tier` | string | 服务等级 |

响应：

```json
{
  "id": "resp_compact_example",
  "object": "response.compaction",
  "created_at": 1788566400,
  "output": [],
  "usage": {
    "input_tokens": 1200,
    "output_tokens": 300,
    "total_tokens": 1500
  }
}
```

`output` 的内容由模型决定，通常是一组可再次作为 `input` 传入的压缩项。

## 错误

| 状态码 | 常见原因 |
| --- | --- |
| `400` | `input` 格式错误、工具结构错误、参数不支持 |
| `401` | Key 无效 |
| `403` | 模型未开放或额度不足 |
| `404` | 模型或 `previous_response_id` 不存在 |
| `429` | 频率或额度超限 |

错误结构见[错误与重试](https://docs.myaigf.cfd/guide/errors)。

## 相关阅读

- [Chat Completions](https://docs.myaigf.cfd/api/chat)：传统 Chat 协议。
- [通用约定](https://docs.myaigf.cfd/guide/conventions#流式输出)：SSE 解析。
- [模型列表](https://docs.myaigf.cfd/api/models)：确认模型支持 `openai-response`。
