跳到主要内容

cURL 调用

通过 HTTP API 直接调用 CloudBase AI 大模型,适用于后端服务、脚本、任意编程语言。

准备工作

  1. 已创建云开发环境(旧套餐可升级),并已启用模型开关(见 接入大模型
  2. 已创建 API Key(获取地址

API 端点

https://<ENV_ID>.api.tcloudbasegateway.com/v1/ai/<PROVIDER>/chat/completions
参数说明示例
ENV_ID环境 IDyour-env-id
PROVIDER模型提供商cloudbase

认证

在请求头中添加 API Key:

Authorization: Bearer <YOUR_API_KEY>

文本生成

非流式调用

curl -X POST 'https://<ENV_ID>.api.tcloudbasegateway.com/v1/ai/cloudbase/chat/completions' \
-H 'Authorization: Bearer <YOUR_API_KEY>' \
-H 'Content-Type: application/json' \
-d '{
"model": "hy3-preview",
"messages": [
{"role": "user", "content": "介绍一下李白"}
],
"stream": false
}'

响应示例:

{
"id": "chatcmpl-xxx",
"object": "chat.completion",
"created": 1234567890,
"model": "hy3-preview",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "李白(701年—762年),字太白,号青莲居士..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 150,
"total_tokens": 160
}
}

流式调用

curl -X POST 'https://<ENV_ID>.api.tcloudbasegateway.com/v1/ai/cloudbase/chat/completions' \
-H 'Authorization: Bearer <YOUR_API_KEY>' \
-H 'Content-Type: application/json' \
-H 'Accept: text/event-stream' \
-d '{
"model": "hy3-preview",
"messages": [
{"role": "user", "content": "介绍一下你自己"}
],
"stream": true
}'

响应格式(SSE):

data: {"id":"chatcmpl-xxx","choices":[{"delta":{"content":"我"},"index":0}]}

data: {"id":"chatcmpl-xxx","choices":[{"delta":{"content":"是"},"index":0}]}

data: {"id":"chatcmpl-xxx","choices":[{"delta":{"content":"DeepSeek"},"index":0}]}

data: [DONE]

请求参数

参数类型必填说明
modelstring模型名称
messagesarray消息列表
streamboolean是否流式返回,默认 false
temperaturenumber采样温度,范围 0-2
top_pnumber核采样,范围 0-1
max_tokensnumber最大生成 token 数

messages 格式

[
{"role": "system", "content": "你是一个有帮助的助手"},
{"role": "user", "content": "用户问题"},
{"role": "assistant", "content": "助手回复"},
{"role": "user", "content": "后续问题"}
]
role说明
system系统提示,设定助手行为
user用户消息
assistant助手回复

多轮对话

多轮对话需要在每次请求中携带完整的历史消息,详见多轮对话文档。

错误处理

调用过程中遇到错误?请参考 常见错误码

编程语言示例

Python

import requests

url = "https://<ENV_ID>.api.tcloudbasegateway.com/v1/ai/cloudbase/chat/completions"
headers = {
"Authorization": "Bearer <YOUR_API_KEY>",
"Content-Type": "application/json"
}
data = {
"model": "hy3-preview",
"messages": [{"role": "user", "content": "你好"}],
"stream": False
}

response = requests.post(url, headers=headers, json=data)
result = response.json()
print(result["choices"][0]["message"]["content"])

Node.js

const response = await fetch(
"https://<ENV_ID>.api.tcloudbasegateway.com/v1/ai/cloudbase/chat/completions",
{
method: "POST",
headers: {
"Authorization": "Bearer <YOUR_API_KEY>",
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "hy3-preview",
messages: [{ role: "user", content: "你好" }]
})
}
);

const result = await response.json();
console.log(result.choices[0].message.content);