OpenAI SDK

使用 OpenAI Python 或 Node.js SDK 調用 Essevin。

現有 OpenAI SDK 專案只需切換 Base URL、套餐金鑰和模型 ID;請保留目前的框架與錯誤處理。

項目填寫值
Base URLhttps://api.essevin.com/v1
金鑰環境變數ESSEVIN_OPENAI_API_KEY
適用模型GPT、Gemini 對話模型,以及 OpenAI 相容模型
模型 ID以目前金鑰調用 GET /v1/models 的返回值為準

不要把金鑰寫進原始碼

請透過部署平台、.env 或系統環境變數注入 ESSEVIN_OPENAI_API_KEY,並確保 .env 不會提交到 Git。

安裝並發送最小請求

安裝 SDK:

python -m pip install openai

發送請求:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.essevin.com/v1",
    api_key=os.environ["ESSEVIN_OPENAI_API_KEY"],
)

resp = client.chat.completions.create(
    model="gpt-5.6-sol",
    messages=[{"role": "user", "content": "你好"}],
)
print(resp.choices[0].message.content)

先將提示詞設為「只回覆 ok」完成最小驗證;只有專案實際使用串流時,再加入 stream: true 並確認 SSE 事件可以逐段到達。

串流輸出並取得用量

stream_options.include_usage 後,最後一個事件的 choices 為空,usage 是本次 token 用量。

stream = client.chat.completions.create(
    model="gpt-5.6-sol",
    messages=[{"role": "user", "content": "用三句話介紹你自己"}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:  # 最後一個事件:choices 為空,只帶用量
        print()
        print(chunk.usage)

工具調用

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "查詢城市天氣",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]
messages = [{"role": "user", "content": "上海今天天氣怎樣?"}]

resp = client.chat.completions.create(model="gpt-5.6-sol", messages=messages, tools=tools)
msg = resp.choices[0].message
if msg.tool_calls:
    call = msg.tool_calls[0]
    print(call.function.name, call.function.arguments)
    # 執行工具後把結果帶回去,tool_call_id 必須與上一輪的 call.id 一致
    messages += [msg, {"role": "tool", "tool_call_id": call.id, "content": "晴,26°C"}]
    resp = client.chat.completions.create(model="gpt-5.6-sol", messages=messages, tools=tools)
print(resp.choices[0].message.content)

超時與重試

openai-python 預設讀超時 600 秒、自動重試 2 次。長輸出建議用串流;並發上限與超時見並發、超時與計費。

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.essevin.com/v1",
    api_key=os.environ["ESSEVIN_OPENAI_API_KEY"],
    timeout=600,    # 秒;長輸出建議改用串流
    max_retries=2,  # 連線錯誤、429 與 5xx 的自動重試次數
)

本頁目錄