> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tokenlab.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAI SDK

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

## 概覽

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

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

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

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

<Note>
  **類型**: Native SDK

  **主要路徑**: OpenAI 相容 / Chat Completions

  **支援信心**: 核心支援路徑
</Note>

## 安裝

<CodeGroup>
  ```bash Python theme={null}
  pip install openai
  ```

  ```bash JavaScript theme={null}
  npm install openai
  ```

  ```bash Go theme={null}
  go get github.com/openai/openai-go/v3
  ```
</CodeGroup>

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

## 設定用戶端

<CodeGroup>
  ```python Python theme={null}
  from openai import OpenAI

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

  ```javascript JavaScript theme={null}
  import OpenAI from 'openai';

  const client = new OpenAI({
    apiKey: 'sk-your-tokenlab-key',
    baseURL: 'https://api.tokenlab.sh/v1',
  });
  ```

  ```go Go theme={null}
  package main

  import (
      openai "github.com/openai/openai-go/v3"
      "github.com/openai/openai-go/v3/option"
  )

  func main() {
      client := openai.NewClient(
          option.WithAPIKey("sk-your-tokenlab-key"),
          option.WithBaseURL("https://api.tokenlab.sh/v1"),
      )

      _ = client
  }
  ```
</CodeGroup>

## 建議：Chat Completions

<CodeGroup>
  ```python Python theme={null}
  response = client.chat.completions.create(
      model="gpt-5.4",
      messages=[{"role": "user", "content": "Explain what TokenLab does in one sentence."}]
  )

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

  ```javascript JavaScript theme={null}
  const response = await client.chat.completions.create({
    model: 'gpt-5.4',
    messages: [{ role: 'user', content: 'Explain what TokenLab does in one sentence.' }],
  });

  console.log(response.choices[0].message.content);
  ```

  ```bash cURL theme={null}
  curl https://api.tokenlab.sh/v1/chat/completions \
    -H "Authorization: Bearer sk-your-tokenlab-key" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-5.4",
      "messages": [
        {"role": "user", "content": "Explain what TokenLab does in one sentence."}
      ]
    }'
  ```
</CodeGroup>

## 進階：Responses API

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

### 使用 Responses 進行串流

<CodeGroup>
  ```python Python theme={null}
  stream = client.responses.create(
      model="gpt-5.4",
      input="Write a short poem about coding.",
      stream=True,
  )

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

  ```javascript JavaScript theme={null}
  const stream = await client.responses.create({
    model: 'gpt-5.4',
    input: 'Write a short poem about coding.',
    stream: true,
  });

  for await (const event of stream) {
    if (event.type === 'response.output_text.delta') {
      process.stdout.write(event.delta);
    }
  }
  ```
</CodeGroup>

## 工具 / 函數調用

```python theme={null}
response = client.responses.create(
    model="gpt-5.4",
    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 的視覺功能

```python theme={null}
response = client.responses.create(
    model="gpt-4o",
    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

```python theme={null}
response = client.embeddings.create(
    model="text-embedding-3-small",
    input="Hello world"
)

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

## Chat Completions

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

```python theme={null}
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ]
)

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

## 疑難排解

<AccordionGroup>
  <Accordion title="連線錯誤">
    * 驗證 base URL 是否完全為 `https://api.tokenlab.sh/v1`
    * 檢查是否有代理干擾或自訂的 HTTP 客戶端覆寫
    * 在偵錯供應商行為前，確保你的 SDK 版本是最新的
  </Accordion>

  <Accordion title="驗證失敗">
    * 檢查你的 API key 是否以 `sk-` 開頭
    * 驗證該金鑰在 TokenLab 控制台中是否為啟用狀態
    * 確認 SDK 是否傳送 `Authorization: Bearer ...`
  </Accordion>

  <Accordion title="錯誤的 API 路徑">
    * `responses.create(...)` 會發送請求到 `/v1/responses`
    * `chat.completions.create(...)` 會發送請求到 `/v1/chat/completions`
    * 預設使用 Chat Completions，除非你明確需要 Responses 特定行為
  </Accordion>
</AccordionGroup>
