> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wolian.cc/llms.txt
> Use this file to discover all available pages before exploring further.

# 请求与响应

> API 请求和响应格式详解

## 请求格式

### HTTP 方法

| 方法   | 用途           |
| ---- | ------------ |
| POST | 发起对话 (/chat) |
| GET  | 查询资源（模型、工具等） |

### 请求头

所有请求必须包含以下头部:

```http theme={null}
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
```

### 请求体示例

<CodeGroup>
  ```json 基础对话 theme={null}
  {
    "model": "anthropic/claude-3-7-sonnet-20250219",
    "messages": [
      {
        "role": "user",
        "content": "你好"
      }
    ],
    "stream": false
  }
  ```

  ```json 完整参数 theme={null}
  {
    "model": "anthropic/claude-3-7-sonnet-20250219",
    "systemPrompt": "你是一个专业的编程助手",
    "messages": [
      {
        "role": "user",
        "content": "解释一下异步编程"
      }
    ],
    "allowedTools": ["bash"],
    "context": {
      "configData": { ... }
    },
    "prune": true,
    "pruneOptions": {
      "maxOutputTokens": 100000,
      "targetTokens": 80000,
      "preserveRecentMessages": 3
    },
    "stream": true
  }
  ```
</CodeGroup>

## 响应格式

### 成功响应（非流式）

```json theme={null}
{
  "success": true,
  "data": {
    "messages": [
      {
        "id": "msg_abc123",
        "role": "assistant",
        "parts": [
          {
            "type": "text",
            "text": "你好！我是一个AI助手..."
          }
        ]
      }
    ],
    "usage": {
      "inputTokens": 15,
      "outputTokens": 45,
      "totalTokens": 60
    },
    "tools": {
      "used": [],
      "skipped": []
    }
  }
}
```

### 成功响应（流式）

流式响应使用 Server-Sent Events (SSE) 格式,所有事件以 `data:` 开头:

```
data: {"type":"start"}

data: {"type":"start-step"}

data: {"type":"text-start","id":"0"}

data: {"type":"text-delta","id":"0","delta":"你好"}

data: {"type":"text-delta","id":"0","delta":"！"}

data: {"type":"text-end","id":"0"}

data: {"type":"finish-step"}

data: {"type":"finish"}

data: [DONE]
```

<Note>
  **关键点**：

  * 所有事件都以 `data:` 开头,后跟 JSON 对象
  * 事件类型在 JSON 的 `type` 字段中标识
  * `[DONE]` 是字面量文本,不是 JSON
  * 详见[流式输出文档](/features/streaming)
</Note>

### 响应头

响应会包含以下有用的头部信息:

| 头部               | 说明                                                        |
| ---------------- | --------------------------------------------------------- |
| X-Correlation-Id | 请求关联 ID（所有响应都包含，401 错误除外）                                 |
| X-Message-Pruned | 值为 `"true"`，仅在实际发生消息剪裁时存在                                 |
| X-Tools-Skipped  | 跳过的工具名称列表（逗号分隔），仅在使用 `contextStrategy: "skip"` 且有工具被跳过时出现 |

<Note>
  **correlationId 获取方式**：

  * 成功响应（200 OK）：只能从响应头 `X-Correlation-Id` 获取，响应体中不包含
  * 错误响应（400, 403, 500等）：响应体和响应头中都包含
  * 401 认证错误：响应体和响应头都不包含
</Note>

<Warning>
  **速率限制未实现**：当前 API 未实现速率限制功能，不会返回 `X-RateLimit-*` 响应头。
</Warning>

## 消息格式

### 简单格式（推荐）

最直接的消息格式:

```json theme={null}
{
  "messages": [
    {
      "role": "user",
      "content": "你好"
    },
    {
      "role": "assistant",
      "content": "你好！有什么我可以帮助你的吗？"
    },
    {
      "role": "user",
      "content": "介绍一下 Python"
    }
  ]
}
```

### AI SDK 格式

兼容 Vercel AI SDK 的消息格式:

```json theme={null}
{
  "messages": [
    {
      "id": "msg_1",
      "role": "user",
      "parts": [
        {
          "type": "text",
          "text": "你好"
        }
      ]
    },
    {
      "id": "msg_2",
      "role": "assistant",
      "parts": [
        {
          "type": "text",
          "text": "你好！"
        }
      ]
    }
  ]
}
```

### 工具调用消息

花卷智能体 API 使用**服务端自动执行**模式,工具调用和结果包含在同一个 `dynamic-tool` part 中:

```json theme={null}
{
  "messages": [
    {
      "role": "user",
      "content": "候选人问：你们公司地址在哪？"
    },
    {
      "id": "msg_001",
      "role": "assistant",
      "parts": [
        {
          "type": "dynamic-tool",
          "toolName": "zhipin_reply_generator",
          "toolCallId": "call_abc123",
          "state": "output-available",
          "input": {
            "candidate_message": "你们公司地址在哪？",
            "brand": "蜀地源冒菜"
          },
          "output": {
            "reply": "您好！我们蜀地源冒菜位于上海市浦东新区..."
          }
        }
      ]
    },
    {
      "id": "msg_002",
      "role": "assistant",
      "parts": [
        {
          "type": "text",
          "text": "已为您生成专业的回复",
          "state": "done"
        }
      ]
    }
  ]
}
```

<Note>
  **重要**：花卷智能体 API 在服务端自动执行工具,单次请求即可完成工具调用和结果处理。详见[工具调用文档](/features/tool-calling)。
</Note>

## 常用参数

### model (必需)

AI 模型标识符,格式为 `provider/model`:

```json theme={null}
{
  "model": "anthropic/claude-3-7-sonnet-20250219"
}
```

### systemPrompt (可选)

自定义系统提示词:

```json theme={null}
{
  "systemPrompt": "你是一个专业的 Python 开发导师"
}
```

### stream (可选)

是否启用流式输出,默认 `true`:

```json theme={null}
{
  "stream": false  // 禁用流式输出,返回完整 JSON 响应
}
```

### allowedTools (可选)

允许 AI 使用的工具列表:

```json theme={null}
{
  "allowedTools": ["bash", "zhipin_reply_generator"]
}
```

### prune (可选)

是否启用消息剪裁,默认 `false`:

```json theme={null}
{
  "prune": true,
  "pruneOptions": {
    "maxOutputTokens": 100000,
    "targetTokens": 80000,
    "preserveRecentMessages": 3
  }
}
```

<Note>
  **默认值**：如果不指定 `pruneOptions`,系统使用默认配置（targetTokens: 80000, maxOutputTokens: 100000, preserveRecentMessages: 3）。只有在需要更激进的剪裁时才需要自定义这些参数。
</Note>

### context (可选)

为工具提供上下文数据:

```json theme={null}
{
  "context": {
    "configData": { ... },
    "replyPrompts": { ... }
  }
}
```

### validateOnly (可选)

仅验证参数,不执行实际请求:

```json theme={null}
{
  "validateOnly": true
}
```

## Token 使用统计

响应中的 `usage` 字段包含 Token 使用情况:

```json theme={null}
{
  "usage": {
    "inputTokens": 150,    // 输入 Token 数
    "outputTokens": 450,   // 输出 Token 数
    "totalTokens": 600     // 总 Token 数
  }
}
```

<Tip>
  使用 `prune: true` 可以显著减少 `inputTokens`,降低 API 调用成本。
</Tip>

## 下一步

<CardGroup cols={2}>
  <Card title="错误码参考" icon="triangle-exclamation" href="/api-reference/error-codes">
    了解所有可能的错误类型
  </Card>

  <Card title="Chat API" icon="message" href="/api-reference/endpoint/chat">
    查看 /chat 端点详细文档
  </Card>
</CardGroup>
