Skip to content

Python 调用示例 ​

先完成 本地密钥设置。

使用 openai 库 ​

安装 Python 后,在测试目录执行:

sh
# 创建独立虚拟环境,避免改动系统 Python 包。
python3 -m venv .venv
source .venv/bin/activate
# 安装本节两个 Python 示例使用的依赖。
python -m pip install openai requests python-dotenv

新建 test_openai.py,填入:

python
import os
from pathlib import Path
from dotenv import load_dotenv
from openai import OpenAI

# 读取脚本旁边的 .env,密钥不写进代码。
load_dotenv(Path(__file__).with_name(".env"))
client = OpenAI(
    api_key=os.environ["XKAPI_API_KEY"],
    base_url=os.environ["XKAPI_BASE_URL"],
    timeout=60.0,
    max_retries=0,  # 首次排错不自动重复请求。
)
try:
    reply = client.chat.completions.create(
        model=os.environ["XKAPI_MODEL"],
        messages=[{"role": "user", "content": "你好"}],
    )
    print(reply.choices[0].message.content)
except Exception as error:
    # 不打印完整请求或认证头;详细错误在本人控制台中查看。
    print("请求失败:", type(error).__name__,
          "HTTP 状态:", getattr(error, "status_code", "未知"))
sh
# 在已激活虚拟环境的终端运行,收到问候即通过。
python test_openai.py

使用 requests ​

新建 test_requests.py,填入:

python
import os
from pathlib import Path
import requests
from dotenv import load_dotenv

# 加载脚本旁的本地配置。
load_dotenv(Path(__file__).with_name(".env"))
try:
    response = requests.post(
        os.environ["XKAPI_BASE_URL"].rstrip("/") + "/chat/completions",
        headers={"Authorization": "Bearer " + os.environ["XKAPI_API_KEY"]},
        json={
            "model": os.environ["XKAPI_MODEL"],
            "messages": [{"role": "user", "content": "你好"}],
        },
        timeout=(10, 60),  # 分别限制连接等待和读取等待。
    )
    response.raise_for_status()
    print(response.json()["choices"][0]["message"]["content"])
except requests.RequestException as error:
    # 保留状态码,不把认证头打印出来。
    status = error.response.status_code if error.response is not None else "未知"
    print("请求失败:", type(error).__name__, "HTTP 状态:", status)
sh
# 使用前面安装的 requests,发送一次请求。
python test_requests.py

✅ 本节完成检查点

  • [ ] 已完成本页操作,真实 Key 没有写进代码或提交到 GitHub。

使用 VitePress 构建