Source: https://wiki.niceai.dev/guide/api/chat-completions

# Chat Completions 接口

向 `POST https://api.niceai.dev/v1/chat/completions` 发送 `model` 和 `messages`，即可得到模型回复。请求和返回格式与 OpenAI 官方 Chat Completions 一致，现有代码只需替换 Base URL 和密钥。

## 请求示例

**-group**

```bash [curl]
curl https://api.niceai.dev/v1/chat/completions \
  -H "Authorization: Bearer $NICEAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<模型名，见模型广场>",
    "messages": [
      {"role": "system", "content": "你是一个简洁的助手。"},
      {"role": "user", "content": "用一句话介绍 HTTP 状态码 429"}
    ]
  }'
```

```python [Python]
import os
from openai import OpenAI

client = OpenAI(base_url="https://api.niceai.dev/v1", api_key=os.environ["NICEAI_API_KEY"])

resp = client.chat.completions.create(
    model="<模型名，见模型广场>",
    messages=[
        {"role": "system", "content": "你是一个简洁的助手。"},
        {"role": "user", "content": "用一句话介绍 HTTP 状态码 429"},
    ],
)
print(resp.choices[0].message.content)
```

```js [Node.js]
import OpenAI from 'openai'

const client = new OpenAI({ baseURL: 'https://api.niceai.dev/v1', apiKey: process.env.NICEAI_API_KEY })

const resp = await client.chat.completions.create({
  model: '<模型名，见模型广场>',
  messages: [
    { role: 'system', content: '你是一个简洁的助手。' },
    { role: 'user', content: '用一句话介绍 HTTP 状态码 429' },
  ],
})
console.log(resp.choices[0].message.content)
```



## 常用参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `model` | string | 必填。模型名，以 [模型广场](https://niceai.dev/model-plaza) 为准 |
| `messages` | array | 必填。对话历史，每条包含 `role`（`system` / `user` / `assistant` / `tool`）和 `content` |
| `stream` | boolean | 设为 `true` 时以 SSE 流式返回，见 [流式输出](https://wiki.niceai.dev/guide/api/streaming) |
| `max_tokens` / `max_completion_tokens` | integer | 限制输出长度。部分推理模型只接受 `max_completion_tokens` |
| `temperature` | number | 随机性，越低越稳定。推理模型可能忽略或不支持 |
| `top_p` | number | 核采样，一般与 `temperature` 二选一调整 |
| `stop` | string / array | 遇到这些字符串时停止生成 |
| `tools` / `tool_choice` | array / string | 工具调用，见 [Function Calling](https://wiki.niceai.dev/guide/api/tools) |
| `response_format` | object | 要求输出 JSON，例如 `{"type": "json_object"}`，需模型支持 |

**参数支持以模型为准**
NiceAI 会把参数按原样转给上游。某个参数是否生效，取决于所选模型本身是否支持；不支持时可能被忽略或返回 400。


## 返回结构

```json
{
  "id": "chatcmpl-...",
  "object": "chat.completion",
  "model": "<模型名>",
  "choices": [
    {
      "index": 0,
      "message": {"role": "assistant", "content": "……"},
      "finish_reason": "stop"
    }
  ],
  "usage": {"prompt_tokens": 25, "completion_tokens": 30, "total_tokens": 55}
}
```

- `finish_reason`：`stop` 表示正常结束，`length` 表示达到输出上限被截断，`tool_calls` 表示模型要调用工具。
- `usage`：本次请求的输入、输出 token 数，计费以控制台使用记录为准。上面的数字只是格式示意。

## 多轮对话

接口本身不保存上下文。每次请求都要把之前的 `user` 和 `assistant` 消息一起放进 `messages`，历史越长，输入 token 越多。长对话可以考虑截断旧消息，或使用支持 [提示词缓存](https://wiki.niceai.dev/guide/tech/prompt-caching) 的模型。

## 常见问题

### 返回 404？

Base URL 要带 `/v1`，完整路径是 `https://api.niceai.dev/v1/chat/completions`。见 [接口地址要不要加 /v1](https://wiki.niceai.dev/guide/v1-404)。

### 返回 400？

多半是参数不被该模型支持，例如给推理模型传了 `temperature`，或 `max_tokens` 应改为 `max_completion_tokens`。先删掉可选参数，只保留 `model` 和 `messages` 测试。

### 回复被截断？

`finish_reason` 为 `length` 时，调大 `max_tokens`，或让模型分段输出。

## 下一步

- [流式输出（SSE）](https://wiki.niceai.dev/guide/api/streaming)
- [工具调用（Function Calling）](https://wiki.niceai.dev/guide/api/tools)
- [Chat Completions 与 Responses 的区别](https://wiki.niceai.dev/guide/tech/responses-vs-chat-completions)
