Skip to content

Python 示例

本示例使用 Python 3 标准库发送非流式聊天请求,无需安装额外依赖。适合先验证接入信息是否正确。

准备环境

在终端检查 Python 是否可用:

bash
python3 --version

准备一枚可用令牌,以及支持 Chat Completions 接口的模型 ID。

设置环境变量

以下设置方式适用于 macOS、Linux 的 Bash 或 Zsh。替换占位值,并在同一个终端执行后面的脚本:

bash
export NEW_API_BASE_URL='https://api.example.com/v1'
export NEW_API_KEY='your-api-key'
export NEW_API_MODEL='your-model-id'

不要把完整令牌直接写进将要分享或提交到仓库的 Python 文件。正式应用可以使用部署平台的密钥配置功能提供这些变量。

创建脚本

新建 chat.py,写入:

python
import json
import os
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

required = ('NEW_API_BASE_URL', 'NEW_API_KEY', 'NEW_API_MODEL')
missing = [name for name in required if not os.environ.get(name)]
if missing:
    raise SystemExit('请先设置环境变量:' + ', '.join(missing))

base_url = os.environ['NEW_API_BASE_URL'].rstrip('/')
api_key = os.environ['NEW_API_KEY']
model = os.environ['NEW_API_MODEL']

payload = {
    'model': model,
    'messages': [
        {'role': 'user', 'content': '你好,请用一句话介绍自己。'}
    ],
    'stream': False,
}

request = Request(
    base_url + '/chat/completions',
    data=json.dumps(payload, ensure_ascii=False).encode('utf-8'),
    headers={
        'Authorization': 'Bearer ' + api_key,
        'Content-Type': 'application/json',
    },
    method='POST',
)

try:
    with urlopen(request, timeout=60) as response:
        result = json.load(response)
except HTTPError as error:
    details = error.read().decode('utf-8', errors='replace')
    raise SystemExit(f'HTTP {error.code}: {details}')
except (URLError, TimeoutError) as error:
    raise SystemExit(f'网络或超时错误:{error}')

choices = result.get('choices', [])
message = choices[0].get('message', {}) if choices else {}
content = message.get('content')

if content:
    print(content)
else:
    print('响应没有普通文本内容,请检查返回结构:')
    print(json.dumps(result, ensure_ascii=False, indent=2))

运行并查看结果

bash
python3 chat.py

正常情况下,终端会输出模型的回复。随后可以在控制台查看该次调用的用量记录。

本示例只发送一条消息,不会自动保留历史对话,也不会在失败后自动重试。

修改对话内容

更换问题

修改 messages 中的 content 即可。

携带历史对话

后续请求可以按时间顺序包含之前的用户消息和助手回复:

python
messages = [
    {'role': 'user', 'content': '什么是 API?'},
    {'role': 'assistant', 'content': 'API 是应用之间交换数据和能力的接口。'},
    {'role': 'user', 'content': '请再举一个生活中的例子。'},
]

将这份列表作为请求中的 messages 使用。携带历史内容会增加输入量,具体消耗见费用说明

常见错误

  • 提示缺少环境变量:确认变量和脚本在同一个终端或进程环境中。
  • 返回 401:检查是否使用了完整、有效的模型调用令牌。
  • 返回 404:检查 Base URL 和模型 ID,并阅读具体错误内容。
  • 网络超时:检查网络与服务状态;重试前先核对是否已有调用记录。

更多处理方法见错误排查