补全(Completions)
传统文本补全接口,用于根据提示词生成文本。
推荐
对于大多数对话场景,建议使用 Chat API,它支持多轮对话,功能更完整。
发起补全请求
http
POST https://api.nexusmodels.cn/v1/completions请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | 模型 ID |
prompt | string/array | 是 | 提示文本 |
suffix | string | 否 | 插入生成文本后的后缀 |
max_tokens | integer | 否 | 最大生成 Token 数 |
temperature | number | 否 | 采样温度,通常为 0~2 |
top_p | number | 否 | 核采样参数,通常为 0~1 |
n | integer | 否 | 返回的候选结果数量 |
stream | boolean | 否 | 是否使用流式输出 |
logprobs | integer | 否 | 返回指定数量的对数概率 |
echo | boolean | 否 | 是否在响应中包含原始提示词 |
stop | string/array | 否 | 停止生成的字符串 |
presence_penalty | number | 否 | 存在惩罚 |
frequency_penalty | number | 否 | 频率惩罚 |
best_of | integer | 否 | 在服务端生成多个结果并返回最佳结果 |
参数兼容性
不同模型支持的参数可能不同。不支持的参数可能被忽略,或者导致请求返回错误。
cURL 示例
bash
curl -sS -X POST \
'https://api.nexusmodels.cn/v1/completions' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_NEXUSMODELS_API_KEY' \
-d '{
"model": "YOUR_COMPLETION_MODEL",
"prompt": "写一句中文问候语:",
"max_tokens": 50,
"temperature": 0.7
}'响应
成功时返回:
http
200 OKjson
{
"id": "cmpl-abc123",
"object": "text_completion",
"created": 1788163200,
"model": "YOUR_COMPLETION_MODEL",
"choices": [
{
"text": "您好!祝您今天心情愉快,工作顺利!",
"index": 0,
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 15,
"completion_tokens": 18,
"total_tokens": 33
}
}响应字段
| 字段 | 说明 |
|---|---|
id | 本次补全请求的唯一标识 |
object | 响应对象类型 |
created | 响应创建时间 |
model | 实际使用的模型 |
choices | 模型生成的候选结果 |
choices[].text | 生成的文本 |
choices[].index | 候选结果序号 |
choices[].logprobs | Token 对数概率 |
choices[].finish_reason | 停止生成的原因 |
usage | 本次请求的 Token 使用信息 |
代码补全示例
只有支持代码补全能力的模型才能使用该场景。
bash
curl -sS -X POST \
'https://api.nexusmodels.cn/v1/completions' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_NEXUSMODELS_API_KEY' \
-d '{
"model": "YOUR_COMPLETION_MODEL",
"prompt": "// JavaScript:计算数组中所有偶数的和\nfunction sumEvenNumbers(arr) {\n",
"max_tokens": 100,
"temperature": 0.2
}'Python 示例
安装依赖:
bash
pip install requests调用接口:
python
import os
import requests
api_key = os.environ["NEXUSMODELS_API_KEY"]
response = requests.post(
"https://api.nexusmodels.cn/v1/completions",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}",
},
json={
"model": "YOUR_COMPLETION_MODEL",
"prompt": "请解释什么是机器学习:",
"max_tokens": 100,
"temperature": 0.5,
},
timeout=60,
)
response.raise_for_status()
result = response.json()
print(result["choices"][0]["text"])模型兼容性
普通聊天模型不一定支持传统 Completions 接口。
调用前可以通过模型列表接口查询当前虚拟 Key 可使用的模型:
bash
curl -sS \
'https://api.nexusmodels.cn/v1/models' \
-H 'Authorization: Bearer YOUR_NEXUSMODELS_API_KEY'