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

# 对话补全

> 与AI模型进行对话交流的核心接口

## 接口简介

Chat Completions 是老张API最核心的接口，用于与AI模型进行对话交流。支持200+AI模型，包括OpenAI、Claude、Gemini、DeepSeek等所有主流大模型。

## 接口信息

**接口地址**：`POST https://api2.laozhang.ai/v1/chat/completions`

**兼容性**：完全兼容OpenAI官方API格式

## 请求参数

### 必需参数

| 参数         | 类型     | 说明                                       |
| ---------- | ------ | ---------------------------------------- |
| `model`    | string | 要使用的模型名称，参考[模型列表](/api-reference/models) |
| `messages` | array  | 对话消息数组，包含角色和内容                           |

### 可选参数

| 参数                  | 类型           | 默认值   | 说明                |
| ------------------- | ------------ | ----- | ----------------- |
| `temperature`       | number       | 1.0   | 控制输出随机性 (0.0-2.0) |
| `max_tokens`        | integer      | 无限制   | 最大输出token数        |
| `top_p`             | number       | 1.0   | 核采样参数 (0.0-1.0)   |
| `frequency_penalty` | number       | 0.0   | 频率惩罚 (-2.0-2.0)   |
| `presence_penalty`  | number       | 0.0   | 存在惩罚 (-2.0-2.0)   |
| `stop`              | string/array | null  | 停止生成的标识符          |
| `stream`            | boolean      | false | 是否流式输出            |
| `n`                 | integer      | 1     | 生成的选择数量           |
| `user`              | string       | null  | 用户标识符             |

## 消息格式

### 基础消息格式

```json theme={null}
{
  "role": "user",
  "content": "你好，请介绍一下你自己"
}
```

### 支持的角色类型

* **`system`**：系统消息，用于设置AI的行为和角色
* **`user`**：用户消息，用户的输入内容
* **`assistant`**：助手消息，AI的回复内容
* **`function`**：函数消息（OpenAI模型支持）
* **`tool`**：工具消息（部分模型支持）

### 多模态消息格式

对于支持图片理解的模型（如GPT-4o、Gemini Pro Vision），可以发送包含图片的消息：

```json theme={null}
{
  "role": "user",
  "content": [
    {
      "type": "text",
      "text": "这张图片里有什么？"
    },
    {
      "type": "image_url",
      "image_url": {
        "url": "https://example.com/image.jpg"
      }
    }
  ]
}
```

## 请求示例

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api2.laozhang.ai/v1/chat/completions \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -d '{
      "model": "gpt-4o-mini",
      "messages": [
        {
          "role": "system",
          "content": "你是一个专业的AI助手，请用中文回答问题。"
        },
        {
          "role": "user",
          "content": "请介绍一下老张API平台的特色功能"
        }
      ],
      "temperature": 0.7,
      "max_tokens": 500
    }'
  ```

  ```javascript Node.js theme={null}
  import OpenAI from 'openai';

  const openai = new OpenAI({
    apiKey: 'YOUR_API_KEY',
    baseURL: 'https://api2.laozhang.ai/v1'
  });

  async function chatCompletion() {
    const completion = await openai.chat.completions.create({
      model: 'gpt-4o-mini',
      messages: [
        {
          role: 'system',
          content: '你是一个专业的AI助手，请用中文回答问题。'
        },
        {
          role: 'user',
          content: '请介绍一下老张API平台的特色功能'
        }
      ],
      temperature: 0.7,
      max_tokens: 500
    });

    console.log(completion.choices[0].message.content);
  }

  chatCompletion();
  ```

  ```python Python theme={null}
  from openai import OpenAI

  client = OpenAI(
      api_key="YOUR_API_KEY",
      base_url="https://api2.laozhang.ai/v1"
  )

  completion = client.chat.completions.create(
      model="gpt-4o-mini",
      messages=[
          {
              "role": "system",
              "content": "你是一个专业的AI助手，请用中文回答问题。"
          },
          {
              "role": "user",
              "content": "请介绍一下老张API平台的特色功能"
          }
      ],
      temperature=0.7,
      max_tokens=500
  )

  print(completion.choices[0].message.content)
  ```

  ```go Go theme={null}
  package main

  import (
      "context"
      "fmt"
      "github.com/sashabaranov/go-openai"
  )

  func main() {
      config := openai.DefaultConfig("YOUR_API_KEY")
      config.BaseURL = "https://api2.laozhang.ai/v1"
      
      client := openai.NewClientWithConfig(config)
      
      resp, err := client.CreateChatCompletion(
          context.Background(),
          openai.ChatCompletionRequest{
              Model: openai.GPT4oMini,
              Messages: []openai.ChatCompletionMessage{
                  {
                      Role:    openai.ChatMessageRoleSystem,
                      Content: "你是一个专业的AI助手，请用中文回答问题。",
                  },
                  {
                      Role:    openai.ChatMessageRoleUser,
                      Content: "请介绍一下老张API平台的特色功能",
                  },
              },
              Temperature: 0.7,
              MaxTokens:   500,
          },
      )
      
      if err != nil {
          fmt.Printf("Error: %v\n", err)
          return
      }
      
      fmt.Println(resp.Choices[0].Message.Content)
  }
  ```
</CodeGroup>

## 响应格式

### 标准响应

```json theme={null}
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1702855400,
  "model": "gpt-4o-mini",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "老张API是一个企业级 AI 技术 API 接入服务平台..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 25,
    "completion_tokens": 150,
    "total_tokens": 175
  }
}
```

### 响应字段说明

| 字段        | 类型      | 说明                        |
| --------- | ------- | ------------------------- |
| `id`      | string  | 请求的唯一标识符                  |
| `object`  | string  | 对象类型，固定为`chat.completion` |
| `created` | integer | 创建时间戳                     |
| `model`   | string  | 使用的模型名称                   |
| `choices` | array   | 生成的选择数组                   |
| `usage`   | object  | token使用情况统计               |

### finish\_reason 取值

* **`stop`**：自然结束
* **`length`**：达到max\_tokens限制
* **`content_filter`**：触发内容过滤
* **`function_call`**：调用函数（OpenAI模型）
* **`tool_calls`**：调用工具（部分模型）

## 流式响应

设置 `"stream": true` 可以启用流式响应，实时获取生成内容：

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api2.laozhang.ai/v1/chat/completions \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -d '{
      "model": "gpt-4o-mini",
      "messages": [
        {"role": "user", "content": "写一首关于AI的诗"}
      ],
      "stream": true
    }'
  ```

  ```javascript Node.js theme={null}
  const stream = await openai.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [
      { role: 'user', content: '写一首关于AI的诗' }
    ],
    stream: true,
  });

  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content || '');
  }
  ```

  ```python Python theme={null}
  stream = client.chat.completions.create(
      model="gpt-4o-mini",
      messages=[
          {"role": "user", "content": "写一首关于AI的诗"}
      ],
      stream=True
  )

  for chunk in stream:
      if chunk.choices[0].delta.content is not None:
          print(chunk.choices[0].delta.content, end="")
  ```
</CodeGroup>

### 流式响应格式

```json theme={null}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1702855400,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"role":"assistant","content":"在"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","created":1702855400,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"content":"数字"},"finish_reason":null}]}

data: [DONE]
```

## 不同模型的特殊用法

### GPT-4o Vision (图像理解)

```json theme={null}
{
  "model": "gpt-4o",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "描述这张图片的内容"
        },
        {
          "type": "image_url",
          "image_url": {
            "url": "https://example.com/image.jpg",
            "detail": "high"
          }
        }
      ]
    }
  ]
}
```

### Claude 原生格式

Claude模型同时支持OpenAI格式和原生格式。使用原生格式时，需要调用 `/v1/messages` 端点：

```bash theme={null}
curl https://api2.laozhang.ai/v1/messages \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-3-5-sonnet-20241022",
    "max_tokens": 1000,
    "messages": [
      {"role": "user", "content": "Hello, Claude!"}
    ]
  }'
```

### O1 系列推理模型

O1系列模型专为复杂推理任务设计，不支持部分参数：

```json theme={null}
{
  "model": "o1-preview",
  "messages": [
    {
      "role": "user",
      "content": "解决这个数学问题：如果一个数的平方等于64，这个数是多少？"
    }
  ]
}
```

<Warning>
  O1系列模型不支持 `temperature`、`top_p`、`frequency_penalty` 等参数，也不支持 `system` 角色消息。
</Warning>

## 使用技巧

### 1. 选择合适的模型

<AccordionGroup>
  <Accordion icon="lightbulb" title="日常对话">
    * **推荐**：GPT-4o Mini、Claude 3.5 Haiku
    * **特点**：响应快、成本低、质量好
  </Accordion>

  <Accordion icon="code" title="代码生成">
    * **推荐**：GPT-4o、Claude 3.5 Sonnet、DeepSeek Coder
    * **特点**：代码理解能力强、生成质量高
  </Accordion>

  <Accordion icon="brain" title="复杂推理">
    * **推荐**：O1 Preview、Claude 3 Opus
    * **特点**：逻辑推理能力强、适合数学问题
  </Accordion>

  <Accordion icon="languages" title="中文处理">
    * **推荐**：通义千问、GLM-4、文心一言
    * **特点**：中文理解和生成能力优秀
  </Accordion>
</AccordionGroup>

### 2. 优化提示词

```json theme={null}
{
  "model": "gpt-4o-mini",
  "messages": [
    {
      "role": "system",
      "content": "你是一个专业的技术文档写作助手。请用清晰、准确的语言回答问题，如果涉及代码，请提供完整的示例。"
    },
    {
      "role": "user",
      "content": "请解释什么是RESTful API，并给出一个Python示例"
    }
  ],
  "temperature": 0.3
}
```

### 3. 控制输出长度

```json theme={null}
{
  "model": "gpt-4o-mini",
  "messages": [
    {
      "role": "user",
      "content": "用100字以内总结人工智能的发展历程"
    }
  ],
  "max_tokens": 150
}
```

### 4. 使用停止词

```json theme={null}
{
  "model": "gpt-4o-mini",
  "messages": [
    {
      "role": "user",
      "content": "列出前5个最大的城市："
    }
  ],
  "stop": ["6."]
}
```

## 计费说明

老张API采用按Token计费模式，不同模型价格不同：

| 模型类型              | 输入价格             | 输出价格            | 特点     |
| ----------------- | ---------------- | --------------- | ------ |
| GPT-4o Mini       | \$0.15/1M tokens | \$0.6/1M tokens | 成本可控选择 |
| GPT-4o            | \$5/1M tokens    | \$15/1M tokens  | 多模态能力  |
| Claude 3.5 Sonnet | \$3/1M tokens    | \$15/1M tokens  | 推理能力强  |
| 通义千问 Turbo        | \$0.3/1M tokens  | \$0.6/1M tokens | 中文优化   |

<Note>
  实际费用以控制台显示为准。使用前请确保账户余额充足。
</Note>

## 错误处理

### 常见错误码

| 错误码 | 说明        | 解决方案           |
| --- | --------- | -------------- |
| 400 | 请求参数错误    | 检查参数格式和必需字段    |
| 401 | API Key无效 | 检查API Key是否正确  |
| 403 | 权限不足      | 确认API Key有足够权限 |
| 429 | 请求过于频繁    | 降低请求频率         |
| 500 | 服务器错误     | 稍后重试或联系支持      |

### 错误响应示例

```json theme={null}
{
  "error": {
    "message": "The model 'gpt-4o-invalid' does not exist",
    "type": "invalid_request_error",
    "param": "model",
    "code": "model_not_found"
  }
}
```

## 最佳实践

1. **使用合适的温度值**：创意任务使用0.7-1.0，精确任务使用0.1-0.3
2. **设置合理的max\_tokens**：避免无限制输出导致费用过高
3. **善用system消息**：设置清晰的角色和任务说明
4. **启用流式响应**：提升用户体验，实时显示生成内容
5. **错误重试机制**：实现指数退避重试策略
6. **监控使用情况**：定期检查控制台的使用统计

***

<Card title="查看更多API文档" icon="book" href="/api-manual">
  返回 API 手册，查看其他接口使用方法
</Card>
