Skip to content

发起对话(Chat Completions)

本页演示如何用 OpenAI API 格式 发起一次对话请求(聊天补全)。

准备工作(必须)

必看:正确配置清单

配置时请务必逐字符核对,90% 的调用失败是因为以下低级错误:

  • Base URL: 必须是 https://ask.ling.rest/api/v1
    • ❌ 结尾不能有斜杠 /
    • ❌ 不能漏掉 /api/v1
  • Model ID: 必须全小写并使用横杠,例如 gemini-1.5-flash
    • ❌ 不能有空格或大写字母
    • ❌ 严禁使用“前端名”或自创缩写
  • Base URL:https://ask.ling.rest/api/v1
  • 模型 ID:请到 模型名获取器 复制(以工具显示的模型名为准)
  • API Key:在 设置 > 账号 > API 密钥 获取

接口信息

  • 方法:POST
  • 路径:/chat/completions
  • 完整地址:https://ask.ling.rest/api/v1/chat/completions
  • 认证:Authorization: Bearer <API_KEY>

最小请求示例(curl)

bash
curl https://ask.ling.rest/api/v1/chat/completions \
  -H "Authorization: Bearer YOUR_API_KEY_HERE" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_MODEL_ID_HERE",
    "messages": [
      { "role": "system", "content": "你是一个简洁的助手。" },
      { "role": "user", "content": "用一句话解释什么是 HTTP。" }
    ]
  }'

Python 示例

python
import requests

BASE_URL = "https://ask.ling.rest/api/v1"
API_KEY = "YOUR_API_KEY_HERE"
MODEL = "YOUR_MODEL_ID_HERE"

resp = requests.post(
    f"{BASE_URL}/chat/completions",
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    },
    json={
        "model": MODEL,
        "messages": [
            {"role": "system", "content": "你是一个简洁的助手。"},
            {"role": "user", "content": "写一个 20 字以内的自我介绍。"},
        ],
    },
    timeout=60,
)

resp.raise_for_status()
data = resp.json()
print(data["choices"][0]["message"]["content"])

JavaScript(浏览器/Node.js)示例

javascript
const BASE_URL = "https://ask.ling.rest/api/v1";
const API_KEY = "YOUR_API_KEY_HERE";
const MODEL = "YOUR_MODEL_ID_HERE";

async function main() {
  const res = await fetch(`${BASE_URL}/chat/completions`, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: MODEL,
      messages: [
        { role: "system", content: "你是一个简洁的助手。" },
        { role: "user", content: "给我 3 个学习英语的建议。" },
      ],
    }),
  });

  if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
  const data = await res.json();
  console.log(data.choices?.[0]?.message?.content ?? "");
}

main().catch(console.error);

常用参数(可选)

不同模型对参数支持不同;以实际返回为准。

  • temperature:更高更随机
  • top_p:采样范围
  • max_tokens:限制输出长度
  • presence_penalty / frequency_penalty:减少重复

多模态(可选)

提示

只有部分模型支持图像/多模态输入;如果模型不支持,会返回错误或忽略相关字段。以 /models 返回与平台标注为准。

若模型支持 OpenAI 风格多模态,可使用 content 数组(示例仅展示结构):

json
{
  "role": "user",
  "content": [
    { "type": "text", "text": "描述这张图。" },
    { "type": "image_url", "image_url": { "url": "https://example.com/a.png" } }
  ]
}

下一步