工具与客户端

Python SDK 接入

用官方 Python SDK 发送 Responses 流式请求。

准备独立环境

Bash
python -m venv .venv
# macOS / Linux / WSL
source .venv/bin/activate
python -m pip install openai

Windows 可以使用 .venv\Scripts\python.exe -m pip install openai,并使用同一个解释器运行脚本,无需修改全局执行策略。

设置三个环境变量

使用首个请求中的对应终端示例,设置 SOTAAI_API_KEY、SOTAAI_BASE_URL 和 SOTAAI_MODEL。密钥不写入脚本。

保存并运行示例

sota_example.py
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["SOTAAI_API_KEY"],
    base_url=os.environ["SOTAAI_BASE_URL"].rstrip("/") + "/v1",
    timeout=120.0,
    max_retries=0,
)

completed = False
stream = client.responses.create(
    model=os.environ["SOTAAI_MODEL"],
    input="Reply with exactly OK.",
    stream=True,
    store=False,
)
try:
    for event in stream:
        if event.type == "response.output_text.delta":
            print(event.delta, end="", flush=True)
        elif event.type == "response.completed":
            completed = True
        elif event.type in ("error", "response.failed", "response.incomplete"):
            raise RuntimeError(f"Stream ended with {event.type}")
finally:
    stream.close()
if not completed:
    raise RuntimeError("Stream ended without response.completed")
print()
Bash
python sota_example.py

集成到应用时

示例关闭 SDK 自动重试,方便辨认第一条错误。正式项目应根据请求性质设置有上限的重试、超时和并发控制。不要把此服务端代码放进可公开读取密钥的浏览器页面。

发现内容有误,或有未解答的问题?反馈文档问题 ↗
SOTA AI / 文档中心为每一次创造,减少一点阻力。
输入关键词,查找 28 篇文档
↑ ↓ 选择Enter 打开Esc 关闭