对话补全 API
对话补全(Chat Completions)是最核心的 API 端点,用于生成 AI 对话回复。
Endpoint
POST https://api.beesai.cn/v1/chat/completions请求参数
必填参数
| 参数 | 类型 | 说明 |
|---|---|---|
model | string | 模型 ID,如 gpt-4o、claude-4-5-sonnet-latest |
messages | array | 对话消息列表 |
消息格式
json
{
"role": "system | user | assistant | tool",
"content": "消息内容"
}角色说明
| 角色 | 说明 |
|---|---|
system | 系统指令,设定 AI 的行为和角色 |
user | 用户消息 |
assistant | AI 的回复(用于多轮对话) |
tool | 工具调用结果 |
可选参数
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
temperature | number | 1 | 温度参数 (0-2),越高越随机 |
top_p | number | 1 | 核采样参数 |
max_tokens | number | - | 最大生成 token 数 |
stream | boolean | false | 是否流式输出 |
stop | string/array | - | 停止生成的标记 |
presence_penalty | number | 0 | 存在惩罚 (-2 to 2) |
frequency_penalty | number | 0 | 频率惩罚 (-2 to 2) |
n | integer | 1 | 生成多少个回复 |
response_format | object | - | 指定输出格式(如 JSON) |
请求示例
基础对话
bash
curl https://api.beesai.cn/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-你的API_KEY" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "你好,请介绍一下你自己"}
]
}'带 System Prompt
bash
curl https://api.beesai.cn/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-你的API_KEY" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "你是一个专业的 Python 编程助手,回答简洁准确。"},
{"role": "user", "content": "如何读取 JSON 文件?"}
]
}'多轮对话
bash
curl https://api.beesai.cn/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-你的API_KEY" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "什么是快速排序?"},
{"role": "assistant", "content": "快速排序是一种分治算法..."},
{"role": "user", "content": "它的时间复杂度是多少?"}
]
}'JSON 输出模式
bash
curl https://api.beesai.cn/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-你的API_KEY" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "列出中国的四大发明"}
],
"response_format": {"type": "json_object"}
}'响应格式
json
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1677858242,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "你好!我是 BeesAI 助手..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 25,
"completion_tokens": 42,
"total_tokens": 67
}
}finish_reason 说明
| 值 | 说明 |
|---|---|
stop | 正常结束 |
length | 达到 max_tokens 限制 |
content_filter | 内容被安全过滤器拦截 |
tool_calls | 模型请求调用工具 |
Python 完整示例
python
from openai import OpenAI
client = OpenAI(
api_key="sk-你的API_KEY",
base_url="https://api.beesai.cn/v1"
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个有帮助的AI助手。"},
{"role": "user", "content": "解释一下量子纠缠"}
],
temperature=0.7,
max_tokens=1000
)
print(f"回复: {response.choices[0].message.content}")
print(f"Token 用量: {response.usage.total_tokens}")
print(f"结束原因: {response.choices[0].finish_reason}")