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

# OpenAI の Python および Node.js SDK で Flatkey を使用する

> OpenAI の Python または Node.js SDK のベース URL に Flatkey を指定するだけで、300 以上のモデルに最大 50% オフでアクセスできます — コードの書き直しは不要です。

OpenAI の Python または Node.js SDK を Flatkey 経由でルーティングすることで、300 以上の AI モデルに最大 50% オフでアクセスできます。切り替えに必要なのはコード 1 行だけです。`base_url` を `https://router.flatkey.ai/v1` に設定し、Flatkey の API キーを使用してください。ストリーミング、ファンクション呼び出し、非同期クライアント、リトライロジックなど、その他の SDK 機能はすべてこれまでどおり動作します。

## インストール

<CodeGroup>
  ```bash pip theme={"dark"}
  pip install openai
  ```

  ```bash npm theme={"dark"}
  npm install openai
  ```

  ```bash yarn theme={"dark"}
  yarn add openai
  ```

  ```bash pnpm theme={"dark"}
  pnpm add openai
  ```
</CodeGroup>

## 基本的なセットアップ

<CodeGroup>
  ```python python theme={"dark"}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["FLATKEY_API_KEY"],
      base_url="https://router.flatkey.ai/v1",
  )
  ```

  ```javascript node theme={"dark"}
  import OpenAI from "openai";

  const client = new OpenAI({
    apiKey: process.env.FLATKEY_API_KEY,
    baseURL: "https://router.flatkey.ai/v1",
  });
  ```
</CodeGroup>

## チャット補完

<CodeGroup>
  ```python python theme={"dark"}
  response = client.chat.completions.create(
      model="gpt-4o",
      messages=[
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Explain quantum entanglement simply."},
      ],
      max_tokens=512,
      temperature=0.7,
  )
  print(response.choices[0].message.content)
  ```

  ```javascript node theme={"dark"}
  const response = await client.chat.completions.create({
    model: "gpt-4o",
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: "Explain quantum entanglement simply." },
    ],
    max_tokens: 512,
    temperature: 0.7,
  });
  console.log(response.choices[0].message.content);
  ```
</CodeGroup>

## ストリーミング

<CodeGroup>
  ```python python theme={"dark"}
  stream = client.chat.completions.create(
      model="gpt-4o-mini",
      messages=[{"role": "user", "content": "Write a haiku about the ocean."}],
      stream=True,
  )

  for chunk in stream:
      delta = chunk.choices[0].delta.content
      if delta:
          print(delta, end="", flush=True)
  print()  # newline at end
  ```

  ```javascript node theme={"dark"}
  const stream = await client.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [{ role: "user", content: "Write a haiku about the ocean." }],
    stream: true,
  });

  for await (const chunk of stream) {
    const delta = chunk.choices[0]?.delta?.content || "";
    process.stdout.write(delta);
  }
  console.log();
  ```
</CodeGroup>

## ファンクション呼び出し / ツール使用

```python python theme={"dark"}
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"},
                },
                "required": ["location"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
    tools=tools,
    tool_choice="auto",
)
print(response.choices[0].message.tool_calls)
```

## OpenAI 以外のモデルを使用する

同じクライアントを使って Flatkey がサポートする任意のモデルを呼び出せます — `model` パラメータを変更するだけです。

```python python theme={"dark"}
# Claude via Flatkey
response = client.chat.completions.create(
    model="claude-sonnet-4-5",
    messages=[{"role": "user", "content": "Review this code for bugs."}],
)

# DeepSeek via Flatkey
response = client.chat.completions.create(
    model="deepseek-v3",
    messages=[{"role": "user", "content": "Solve this math problem step by step."}],
)

# Gemini via Flatkey
response = client.chat.completions.create(
    model="gemini-2.5-flash",
    messages=[{"role": "user", "content": "Summarize this article."}],
)
```

## 非同期クライアント

```python python theme={"dark"}
import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI(
    api_key=os.environ["FLATKEY_API_KEY"],
    base_url="https://router.flatkey.ai/v1",
)

async def main():
    response = await client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "Hello!"}],
    )
    print(response.choices[0].message.content)

asyncio.run(main())
```

<Tip>
  [モデルディレクトリ](https://flatkey.ai/models) に掲載されているモデル ID はすべて、Flatkey を通じて OpenAI SDK で使用できます — Claude、Gemini、DeepSeek、Qwen のモデルも含まれます。
</Tip>
