> ## Documentation Index
> Fetch the complete documentation index at: https://docs.playapi.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 快速开始

> 准备服务地址和 API Key，查询模型并发起第一次对话请求。

本指南使用 OpenAI 兼容的 Chat Completions 接口。示例在终端或服务端执行，不需要安装 SDK。

## 1. 准备服务地址和 API Key

1. 登录管理员提供的控制台。
2. 打开「API Keys」页面（控制台路径 `/keys`），创建并复制一个 API Key。
3. 确认账号和密钥处于可用状态，并具备目标模型的访问权限。
4. 从管理员或控制台提供的 API 地址中确认 API Base URL。

下列命令适用于 macOS、Linux 或 WSL 的 Bash / Zsh。先用自己的地址替换示例地址，再设置环境变量：

```bash theme={null}
export API_BASE_URL='https://gateway.example.com/v1'
export API_KEY='YOUR_API_KEY'
```

`API_BASE_URL` 在本指南中包含一个 `/v1`，末尾不带 `/`。如果服务部署在子路径下，保留完整前缀，例如 `https://example.com/gateway/v1`。不要使用文档域名，也不要重复添加 `/v1`。

请在本地替换 `YOUR_API_KEY`。不要将真实密钥提交到 Git、放进浏览器代码或截图公开；也不要把登录会话或管理用凭据当作模型调用密钥。

## 2. 查询可用模型

```bash theme={null}
curl --fail-with-body --silent --show-error \
  "$API_BASE_URL/models" \
  -H "Authorization: Bearer $API_KEY"
```

响应的 `data` 数组包含模型条目，每个条目的 `id` 是调用时使用的模型 ID。选择一个支持 Chat Completions 的对话模型，并原样使用它的 ID，不要使用展示名称。

将下面的占位符替换为选中的模型 ID，后续请求使用同一个变量：

```bash theme={null}
export API_MODEL='YOUR_CHAT_MODEL_ID'
```

如果列表为空，或无法确定哪个模型支持对话，请先联系部署管理员确认渠道配置、模型能力和密钥权限。

## 3. 发起第一次对话

从下面三种方式中选择一种，使用上面设置的环境变量。发送请求会调用实际模型。

### cURL

需要 cURL 7.76 或更高版本。模型 ID 应使用模型列表返回的原始值。

```bash theme={null}
curl --fail-with-body --silent --show-error \
  "$API_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @- <<EOF
{
  "model": "$API_MODEL",
  "messages": [
    { "role": "user", "content": "Say hello in one short sentence." }
  ]
}
EOF
```

### Python

需要 Python 3，使用标准库，无需安装依赖。将代码保存为 `chat.py`，在设置好环境变量的终端运行 `python3 chat.py`。

```python theme={null}
import json
import os
import urllib.error
import urllib.request

base_url = os.environ["API_BASE_URL"].rstrip("/")
payload = {
    "model": os.environ["API_MODEL"],
    "messages": [
        {"role": "user", "content": "Say hello in one short sentence."}
    ],
}
request = urllib.request.Request(
    f"{base_url}/chat/completions",
    data=json.dumps(payload).encode("utf-8"),
    headers={
        "Authorization": f"Bearer {os.environ['API_KEY']}",
        "Content-Type": "application/json",
    },
    method="POST",
)

try:
    with urllib.request.urlopen(request, timeout=60) as response:
        result = json.load(response)
except urllib.error.HTTPError as error:
    raise SystemExit(f"Request failed (HTTP {error.code}). Check the request logs.")
except urllib.error.URLError:
    raise SystemExit("Connection failed. Check the API address and network.")

print(result["choices"][0]["message"]["content"])
```

### TypeScript

需要 Node.js 22.18 或更高版本，使用内置 `fetch`，无需安装依赖。将代码保存为 `chat.mts`，在设置好环境变量的终端运行 `node chat.mts`。

```typescript theme={null}
const baseUrl = process.env.API_BASE_URL?.replace(/\/+$/, '');
const apiKey = process.env.API_KEY;
const model = process.env.API_MODEL;

if (!baseUrl || !apiKey || !model) {
  throw new Error('Set API_BASE_URL, API_KEY, and API_MODEL first.');
}

const response = await fetch(`${baseUrl}/chat/completions`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${apiKey}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model,
    messages: [
      { role: 'user', content: 'Say hello in one short sentence.' },
    ],
  }),
  signal: AbortSignal.timeout(60_000),
});

if (!response.ok) {
  throw new Error(`Request failed (HTTP ${response.status}). Check the request logs.`);
}

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

## 4. 确认结果

成功时，cURL 会输出 JSON，对话文本位于 `choices[0].message.content`。Python 和 TypeScript 示例直接打印该文本，例如：

```text theme={null}
Hello! How can I help you today?
```

具体文本因模型而异。若返回错误，结合 HTTP 状态和控制台请求日志排查，不要把完整密钥贴入求助信息。

## 常见问题

| 现象 | 检查项 |
| - | - |
| 401 或 403 | 使用模型调用 API Key；检查密钥状态、权限及其他访问限制 |
| 404，或响应是 HTML 页面 | 检查 API 域名和路径，确保没有漏写或重复 `/v1` |
| 提示模型不存在或无可用渠道 | 使用准确模型 ID，确认协议支持及部署端渠道配置 |
| 429 | 查看返回信息和请求日志，降低请求频率，确认账号适用的限制 |
| 连接失败或超时 | 检查网络、服务地址、网关和上游服务状态 |

这些是排查方向，实际状态码和错误信息可能随上游服务而不同。

## 接下来

将同样的 API Base URL、密钥和模型 ID 配置到你的服务端应用中。接入现有 SDK 时，确认 SDK 需要的是包含 `/v1` 的 Base URL，还是完整接口地址。

[了解项目与地址约定](/zh/introduction) · [Read in English](/en/quickstart)

[接入指南](/zh/guides/api-basics) · [API 参考](/zh/api-reference/overview)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.