> ## 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 调用，实现纯文本对话：

```bash 基础对话请求 icon="terminal" theme={null}
curl -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
  }'
```

<Note>
  **重要**：必须显式设置 `stream: false` 以获得非流式响应，否则 API 默认返回流式输出。
</Note>

## 多轮对话

通过传递完整的对话历史实现上下文连贯的多轮对话：

```javascript 多轮对话示例 lines icon="comments" theme={null}
const messages = [
  { role: "user", content: "1+1等于几？" },
  { role: "assistant", content: "1+1等于2" },
  { role: "user", content: "那再加3呢？" },
];

const response = await fetch("https://huajune.duliday.com/api/v1/chat", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "anthropic/claude-3-7-sonnet-20250219",
    messages: messages,
    stream: false,
  }),
});
```

<Tip>
  AI 会根据完整的对话历史理解上下文，生成连贯的回复（"等于5"）。
</Tip>

## 自定义系统提示词

通过 `systemPrompt` 自定义 AI 的角色和行为：

```json 系统提示词配置 lines icon="message-bot" theme={null}
{
  "model": "anthropic/claude-3-7-sonnet-20250219",
  "systemPrompt": "你是一个专业的Python编程导师，擅长用简单易懂的语言解释复杂的编程概念。回复时请使用中文，并提供代码示例。",
  "messages": [
    {
      "role": "user",
      "content": "什么是装饰器？"
    }
  ],
  "stream": false
}
```

<Card title="查看更多系统提示词配置" icon="book" href="/concepts/system-prompts">
  了解如何使用预定义的系统提示词类型和自定义配置
</Card>

## 流式 vs 非流式

<Warning>
  **默认行为**：如果省略 `stream` 参数，API 默认使用**流式输出**（`stream: true`）。如需非流式响应，必须显式设置 `stream: false`。
</Warning>

### 非流式输出

一次性返回完整响应，适合后台处理场景：

```json 非流式配置 icon="ban" theme={null}
{
  "stream": false  // 必须显式设置为 false
}
```

响应格式：

```json 非流式响应 lines icon="check" theme={null}
{
  "success": true,
  "data": {
    "messages": [
      {
        "id": "msg_abc123",
        "role": "assistant",
        "parts": [
          {
            "type": "text",
            "text": "完整的回复内容...",
            "state": "done"
          }
        ]
      }
    ],
    "usage": {
      "inputTokens": 15,
      "outputTokens": 45,
      "totalTokens": 60,
      "reasoningTokens": 0,         // 可选：推理 token 数（某些模型支持）
      "cachedInputTokens": 0        // 可选：缓存的输入 token 数
    },
    "tools": {
      "used": [],                   // 已使用的工具列表
      "skipped": []                 // 跳过的工具列表
    }
  }
}
```

<Accordion title="响应字段说明" icon="info-circle">
  **usage 字段**：

  * `inputTokens`: 输入 token 数量
  * `outputTokens`: 输出 token 数量
  * `totalTokens`: 总 token 数量
  * `reasoningTokens`（可选）: 推理 token 数量（仅某些模型支持，如 o1 系列）
  * `cachedInputTokens`（可选）: 缓存的输入 token 数量（某些提供商支持缓存优化）

  **tools 字段**：

  * `used`: 本次对话中实际使用的工具列表
  * `skipped`: 因配置问题被跳过的工具列表（见[上下文策略](/concepts/tools#上下文策略)）
</Accordion>

### 流式输出

实时返回生成的内容，提供更好的用户体验：

```json 流式配置 icon="stream" theme={null}
{
  "stream": true  // API 默认值，可省略
}
```

<Card title="查看完整流式输出指南" icon="forward" href="/features/streaming">
  了解如何处理流式响应、SSE 事件格式和最佳实践
</Card>

## 完整示例

<CodeGroup>
  ```javascript JavaScript 完整示例 lines icon="js" theme={null}
  async function chat(message) {
    const response = await fetch("https://huajune.duliday.com/api/v1/chat", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.HUAJUNE_API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        model: "anthropic/claude-3-7-sonnet-20250219",
        systemPrompt: "你是一个友好的AI助手",
        messages: [{ role: "user", content: message }],
        stream: false,  // 显式设置非流式输出
      }),
    });

    const data = await response.json();

    // 提取回复文本
    return data.data.messages[0].parts[0].text;
  }

  // 使用示例
  const reply = await chat("你好！");
  console.log(reply);
  ```

  ```python Python 完整示例 lines icon="python" theme={null}
  import os
  import requests

  def chat(message):
      url = "https://huajune.duliday.com/api/v1/chat"
      headers = {
          "Authorization": f"Bearer {os.getenv('HUAJUNE_API_KEY')}",
          "Content-Type": "application/json"
      }
      payload = {
          "model": "anthropic/claude-3-7-sonnet-20250219",
          "systemPrompt": "你是一个友好的AI助手",
          "messages": [
              {"role": "user", "content": message}
          ],
          "stream": False  # 显式设置非流式输出
      }

      response = requests.post(url, json=payload, headers=headers)
      data = response.json()

      # 提取回复文本
      return data['data']['messages'][0]['parts'][0]['text']

  # 使用示例
  reply = chat('你好！')
  print(reply)
  ```
</CodeGroup>

<Tip>
  **最佳实践**：在生产环境中添加错误处理，检查 `response.ok` 和 `data.success`，并处理可能的异常情况。
</Tip>

## 下一步

<CardGroup cols={2}>
  <Card title="流式输出" icon="stream" href="/features/streaming">
    实现打字机效果的实时对话
  </Card>

  <Card title="工具调用" icon="wrench" href="/features/tool-calling">
    让 AI 调用工具完成复杂任务
  </Card>
</CardGroup>
