TokenLab

原生 SDK

OpenAI SDK

在官方 OpenAI SDK 及相容客戶端中使用 TokenLab

概覽

TokenLab 可與官方 OpenAI SDK 一起使用,方法是將客戶端指向 https://api.tokenlab.sh/v1。

對於大多數新專案,預設建議使用 Chat Completions 作為 OpenAI 相容路徑。僅在你明確需要 Responses 特定行為時才使用 Responses API。

Responses 特有的欄位不保證在每個模型與路由的路徑中行為一致。

Python、JavaScript 和 Go 有官方的 OpenAI SDK。PHP 與 OpenAI 相容的社群客戶端相容性良好,但 PHP 並不是官方的 OpenAI SDK。

類型: Native SDK

主要路徑: OpenAI 相容 / Chat Completions

支援信心: 核心支援路徑

安裝

pip install openai

僅在你明確需要 Responses 特定行為時使用 POST /v1/responses。有些僅限 Responses 的欄位仍可能依賴所選模型與路由路徑。

設定用戶端

from openai import OpenAI

client = OpenAI(
    api_key="sk-your-tokenlab-key",
    base_url="https://api.tokenlab.sh/v1",
)

建議:Chat Completions

response = client.chat.completions.create(
    model="gpt-5.6-terra",
    messages=[{"role": "user", "content": "Reply with: Connected to TokenLab."}]
)

print(response.choices[0].message.content)

進階:Responses API

僅在你的工具或工作流程明確依賴 OpenAI Responses 語意時使用此路徑。

使用 Responses 進行串流

stream = client.responses.create(
    model="gpt-5.6-terra",
    input="Write a short poem about coding.",
    stream=True,
)

for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="")

工具 / 函數調用

response = client.responses.create(
    model="gpt-5.6-terra",
    input="What's the weather in Tokyo?",
    tools=[{
        "type": "function",
        "name": "get_weather",
        "description": "Get weather for a location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string"}
            },
            "required": ["location"]
        }
    }]
)

for item in response.output:
    if item.type == "function_call":
        print(item.name)
        print(item.arguments)

Responses 的視覺功能

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[{
        "role": "user",
        "content": [
            {"type": "input_text", "text": "What's in this image?"},
            {"type": "input_image", "image_url": "https://example.com/image.jpg"}
        ]
    }]
)

print(response.output_text)

Embeddings

response = client.embeddings.create(
    model="text-embedding-3-small",
    input="Hello world"
)

print(response.data[0].embedding[:5])

Chat Completions

Chat Completions 是 TokenLab 的預設 OpenAI 相容路徑:

response = client.chat.completions.create(
    model="gpt-5.6-terra",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ]
)

print(response.choices[0].message.content)

疑難排解

本頁內容