> ## 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.

# 快速开始

> 5 分钟完成首次 API 调用，快速体验花卷智能体

## 开始之前

在开始之前，请确保你已经：

<Check>拥有一个 Wolian AI 账户</Check>
<Check>获取了已激活的 API Key（可在 [Wolian AI 平台](https://wolian.cc/platform/clients-management) 获取）</Check>

## 第一步：获取 API Key

<Steps>
  <Step title="访问平台">
    前往 [Wolian AI 客户端管理](https://wolian.cc/platform/clients-management) 页面
  </Step>

  <Step title="登录账户">
    使用你的账户登录（与 `huajune.duliday.com` 使用相同的账户系统）
  </Step>

  <Step title="创建并激活密钥">
    点击 **"+ 创建"** 按钮创建新密钥，确保密钥状态为 **"已激活"**
  </Step>

  <Step title="复制密钥">
    点击复制按钮复制完整的 API Key 并妥善保存
  </Step>
</Steps>

<Warning>
  **安全提示**：请勿将 API Key
  提交到版本控制系统或公开分享。建议使用环境变量来存储密钥。
</Warning>

## 第二步：发起第一个请求

选择你熟悉的编程语言，发起第一个 API 请求：

<CodeGroup>
  ```bash cURL theme={null}
  curl -N -X POST https://huajune.duliday.com/api/v1/chat \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "anthropic/claude-3-7-sonnet-20250219",
      "messages": [
        {
          "role": "user",
          "content": "你好，请介绍一下你自己"
        }
      ],
      "stream": false
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch("https://huajune.duliday.com/api/v1/chat", {
    method: "POST",
    headers: {
      Authorization: "Bearer YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "anthropic/claude-3-7-sonnet-20250219",
      messages: [
        {
          role: "user",
          content: "你好，请介绍一下你自己",
        },
      ],
      stream: false,
    }),
  });

  const data = await response.json();
  console.log(data.data.messages[0].parts[0].text);
  ```

  ```python Python theme={null}
  import requests

  url = "https://huajune.duliday.com/api/v1/chat"
  headers = {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
  }
  payload = {
      "model": "anthropic/claude-3-7-sonnet-20250219",
      "messages": [
          {
              "role": "user",
              "content": "你好，请介绍一下你自己"
          }
      ],
      "stream": False
  }

  response = requests.post(url, json=payload, headers=headers)
  data = response.json()
  print(data['data']['messages'][0]['parts'][0]['text'])
  ```
</CodeGroup>

<Note>记得将 `YOUR_API_KEY` 替换为你在第一步中获取的实际 API Key。</Note>

## 第三步：理解响应

成功的请求会返回以下格式的 JSON 响应：

```json theme={null}
{
  "success": true,
  "data": {
    "messages": [
      {
        "id": "msg_abc123",
        "role": "assistant",
        "parts": [
          {
            "type": "text",
            "text": "你好！我是花卷智能体..."
          }
        ]
      }
    ],
    "usage": {
      "inputTokens": 15,
      "outputTokens": 45,
      "totalTokens": 60
    },
    "tools": {
      "used": [],
      "skipped": []
    }
  }
}
```

<AccordionGroup>
  <Accordion title="响应字段说明">
    * `messages`: 包含 AI 助手的回复消息 - `usage`: Token 使用量统计 -
      `inputTokens`: 输入的 token 数量 - `outputTokens`: 输出的 token 数量 -
      `totalTokens`: 总 token 数量 - `tools`: 工具使用情况 - `used`:
      本次使用的工具列表 - `skipped`: 跳过的工具列表
  </Accordion>
</AccordionGroup>

## 第四步：尝试流式输出

现在让我们尝试更流畅的流式输出，实现类似 ChatGPT 的打字机效果。

<Tip>
  流式输出使用 Server-Sent Events (SSE) 协议，可以实时接收 AI 生成的内容，非常适合需要即时反馈的聊天场景。
</Tip>

<CodeGroup>
  ```javascript JavaScript (Stream) theme={null}
  const response = await fetch("https://huajune.duliday.com/api/v1/chat", {
    method: "POST",
    headers: {
      Authorization: "Bearer YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "anthropic/claude-3-7-sonnet-20250219",
      messages: [
        {
          role: "user",
          content: "作为餐饮招聘助手，介绍一下服务员岗位",
        },
      ],
      stream: true, // 启用流式输出
    }),
  });

  // 处理 SSE 流式响应
  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  let accumulatedText = "";

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value);
    const lines = chunk.split('\n').filter(line => line.trim());

    for (const line of lines) {
      if (line.startsWith('data: ')) {
        const data = line.slice(6); // 去掉 "data: " 前缀

        // 检查流结束标记
        if (data === '[DONE]') {
          console.log('\n流式响应完成');
          break;
        }

        try {
          const event = JSON.parse(data);

          // 处理文本增量事件
          if (event.type === 'text.delta') {
            accumulatedText += event.delta;
            process.stdout.write(event.delta); // 实时打印
          }

          // 处理消息完成事件
          if (event.type === 'finish') {
            console.log('\n消息生成完成');
          }
        } catch (e) {
          // 忽略无法解析的行
        }
      }
    }
  }

  console.log('\n完整回复:', accumulatedText);
  ```

  ```python Python (Stream) theme={null}
  import requests
  import json

  url = "https://huajune.duliday.com/api/v1/chat"
  headers = {
      "Authorization": "Bearer YOUR_API_KEY",
      "Content-Type": "application/json"
  }
  payload = {
      "model": "anthropic/claude-3-7-sonnet-20250219",
      "messages": [
          {
              "role": "user",
              "content": "作为餐饮招聘助手，介绍一下服务员岗位"
          }
      ],
      "stream": True  # 启用流式输出
  }

  accumulated_text = ""

  with requests.post(url, json=payload, headers=headers, stream=True) as response:
      for line in response.iter_lines():
          if line:
              line_str = line.decode('utf-8')

              if line_str.startswith('data: '):
                  data = line_str[6:]  # 去掉 "data: " 前缀

                  # 检查流结束标记
                  if data == '[DONE]':
                      print('\n流式响应完成')
                      break

                  try:
                      event = json.loads(data)

                      # 处理文本增量事件
                      if event.get('type') == 'text.delta':
                          text_delta = event.get('delta', '')
                          accumulated_text += text_delta
                          print(text_delta, end='', flush=True)

                      # 处理消息完成事件
                      if event.get('type') == 'finish':
                          print('\n消息生成完成')
                  except json.JSONDecodeError:
                      pass  # 忽略无法解析的行

  print('\n完整回复:', accumulated_text)
  ```
</CodeGroup>

<Warning>
  **流式响应注意事项**：

  * 流式响应使用 SSE 格式，每行以 `data: ` 开头
  * 流结束时会收到 `data: [DONE]` 标记（字面量，非 JSON）
  * 消息完成时会收到 `{"type":"finish"}` 事件
  * 需要逐行解析 JSON 事件，主要关注 `text.delta` 类型
  * 某些代理服务器可能会缓冲 SSE 响应，建议在生产环境配置 `X-Accel-Buffering: no`
</Warning>

## 第五步：查看响应头信息

API 会在响应头中返回一些有用的信息，帮助你监控和优化调用：

<CodeGroup>
  ```javascript JavaScript theme={null}
  const response = await fetch('https://huajune.duliday.com/api/v1/chat', {
    // ... 请求配置
  });

  // 查看响应头
  console.log('Correlation ID:', response.headers.get('X-Correlation-Id'));
  console.log('消息已剪裁:', response.headers.get('X-Message-Pruned'));
  console.log('跳过的工具:', response.headers.get('X-Tools-Skipped'));

  const data = await response.json();
  ```

  ```python Python theme={null}
  response = requests.post(url, json=payload, headers=headers)

  # 查看响应头
  print('Correlation ID:', response.headers.get('X-Correlation-Id'))
  print('消息已剪裁:', response.headers.get('X-Message-Pruned'))
  print('跳过的工具:', response.headers.get('X-Tools-Skipped'))

  data = response.json()
  ```
</CodeGroup>

**重要响应头说明：**

<ResponseField name="X-Correlation-Id" type="string">
  请求关联 ID，用于追踪和调试问题，报告 Bug 时请提供此 ID
</ResponseField>

<ResponseField name="X-Message-Pruned" type="boolean">
  是否进行了消息剪裁（值为 "true" 或不存在）
</ResponseField>

<ResponseField name="X-Tools-Skipped" type="string">
  被跳过的工具列表（逗号分隔），仅在使用 `contextStrategy: "skip"` 时出现
</ResponseField>

## 常见问题

<AccordionGroup>
  <Accordion title="401 Unauthorized 错误">
    请检查：

    * API Key 是否正确
    * Authorization 头格式是否为 `Bearer YOUR_API_KEY`
    * API Key 是否已激活（在 Wolian AI 平台查看状态）
    * API Key 是否已过期或被撤销
  </Accordion>

  <Accordion title="403 Forbidden 错误">
    可能原因：

    * 使用的模型不在你的许可列表中
    * 账户权限不足

    解决方法：使用 `GET /api/v1/models` 查看可用模型列表

    ```bash theme={null}
    curl -X GET https://huajune.duliday.com/api/v1/models \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```
  </Accordion>

  <Accordion title="如何知道 AI 使用了哪些工具？">
    查看响应中的 `tools` 字段：

    ```json theme={null}
    {
      "success": true,
      "data": {
        "messages": [...],
        "tools": {
          "used": ["zhipin_reply_generator"],  // 本次使用的工具
          "skipped": []  // 跳过的工具（如有）
        }
      }
    }
    ```

    **注意**：花卷会根据对话内容自动选择合适的工具，无需手动指定
  </Accordion>

  <Accordion title="响应速度较慢怎么办？">
    可以尝试以下优化：

    1. **使用流式输出** (`stream: true`)，让用户立即看到内容开始生成
    2. **启用消息剪裁** (`prune: true`)，减少输入 token 数量
    3. **选择更快的模型**（如 `qwen/qwen-plus-latest`），牺牲少量质量换取速度

    查看 [性能优化文档](/best-practices/performance) 了解更多技巧
  </Accordion>
</AccordionGroup>

## 下一步

恭喜！你已经成功完成了第一次 API 调用。接下来你可以：

<CardGroup cols={2}>
  <Card title="探索工具调用" icon="wrench" href="/features/tool-calling">
    让 AI 使用工具完成更复杂的任务
  </Card>

  {" "}

  <Card title="了解核心概念" icon="book" href="/concepts/models">
    深入理解模型、消息、上下文等概念
  </Card>

  {" "}

  <Card title="查看 API 参考" icon="code" href="/api-reference/introduction">
    完整的 API 端点文档和参数说明
  </Card>

  <Card title="最佳实践" icon="star" href="/best-practices/performance">
    学习性能优化和调试技巧
  </Card>
</CardGroup>
