原生 SDK
OpenAI SDK
使用 TokenLab 搭配官方 OpenAI SDK 及相容於 OpenAI 的客戶端
概覽
將 OpenAI SDK 客戶端指向 https://api.tokenlab.sh/v1 並使用 TokenLab API 金鑰。保留您應用程式目前使用的 API 方法,並透過 accepted_request_formats 確認所選模型是否支援該方法。
Python、JavaScript 和 Go 擁有官方的 OpenAI SDK。PHP 可與相容於 OpenAI 的社群客戶端良好運作,但它並非官方的 OpenAI SDK。
安裝
pip install openai針對 Responses 輸入項目、工具或延續內容,請使用 POST /v1/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 進行串流 (Streaming)
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="")工具 / 函式呼叫 (Tools / Function Calling)
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 進行視覺辨識 (Vision)
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])