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

# LiteLLM

## LiteLLM の概要

LiteLLM は [BerriAI](https://github.com/BerriAI/litellm) によって開発されたオープンソースの **統一 AI ゲートウェイ** です。市場のほぼすべての主要 LLM を呼び出すための単一の標準化されたインターフェースを提供します。リポジトリ：[https://github.com/BerriAI/litellm](https://github.com/BerriAI/litellm)

<Frame>
  <img src="https://mintcdn.com/aihubmix/HWcKoL0Wliaf75A6/images/image-90.png?fit=max&auto=format&n=HWcKoL0Wliaf75A6&q=85&s=340719652443a06b570d103064a64989" alt="Image" width="2688" height="1600" data-path="images/image-90.png" />
</Frame>

LLM プロバイダーごとに独自の SDK と API 形式があります — OpenAI、Anthropic、Google はすべて異なります。モデルを切り替えたり複数のモデルを同時に使ったりするには、別々のコードベースを維持する必要があります。LiteLLM はこれを解決します：**一度書けば、1 つのパラメータを変えるだけで、任意のモデルを呼び出せます**。

### 2 つの使用モード

| モード              | 説明                                | 最適なケース               |
| :--------------- | :-------------------------------- | :------------------- |
| **Python SDK**   | `pip install litellm`、コード内で直接呼び出し | 個人プロジェクト、迅速なプロトタイピング |
| **Proxy Server** | スタンドアロンデプロイ可能な AI ゲートウェイ          | チーム共有、エンタープライズアクセス制御 |

### コア機能

* **統一された OpenAI 形式**：OpenAI、Anthropic、Gemini、Bedrock、Azure を含む 100+ プロバイダーをサポート
* **仮想キー管理**：オリジナルを公開せずにチームの API キーを集中管理
* **コストトラッキング**：ユーザーまたはプロジェクトごとのトークン使用量と支出をモニタリング
* **ロードバランシング**：フェイルオーバーサポート付きのモデル間自動トラフィック分散
* **高パフォーマンス**：1,000 RPS で P95 レイテンシ約 8ms

***

## インストール

### 要件

Python 3.8+

**macOS**

[Homebrew](https://brew.sh/) 経由でインストール：

```bash theme={null}
brew install python
```

確認：

```bash theme={null}
python3 --version
```

**Windows**

[python.org/downloads](https://www.python.org/downloads/) からインストーラーをダウンロードします。インストール中に **"Add Python to PATH"** にチェックを入れてください。

確認：

```bash theme={null}
python --version
```

**Linux (Ubuntu/Debian)**

```bash theme={null}
sudo apt update
sudo apt install python3 python3-pip
```

### pip

pip は通常 Python に同梱されています。利用可能か確認：

```bash theme={null}
pip --version
# or
pip3 --version
```

見つからない場合は、手動でインストール：

```bash theme={null}
# Universal method
python3 -m ensurepip --upgrade

# Ubuntu/Debian
sudo apt install python3-pip

# Upgrade to latest
pip install --upgrade pip
```

### LiteLLM のインストール

環境の準備ができたら：

```bash theme={null}
python3 -m pip install litellm
```

インストールを確認：

```bash theme={null}
python3 -m pip show litellm
```

### オプションの依存関係

一部のプロバイダーには追加のパッケージが必要です：

```bash theme={null}
# AWS Bedrock
pip install litellm[bedrock]

# Google Vertex AI
pip install litellm[vertex]

# All dependencies (not recommended for production)
pip install litellm[all]
```

### Proxy Server のインストール

スタンドアロンゲートウェイをデプロイするには：

```bash theme={null}
pip install 'litellm[proxy]'
```

### Docker（オプション）

```bash theme={null}
docker pull ghcr.io/berriai/litellm:main-latest
```

> **推奨**：個人開発には `pip install litellm` を使用し、チームデプロイメントには Proxy + Docker を選択してください。

***

## API キーの設定と初回呼び出し

### AiHubMix API キーの取得

[aihubmix.com](https://aihubmix.com) ダッシュボードに移動して API キーを作成します。

### 環境変数の設定

```bash theme={null}
export AIHUBMIX_API_KEY="your-aihubmix-key"
```

### 初回呼び出し

```python theme={null}
import os
from litellm import completion

response = completion(
    model="openai/gpt-4o-mini",
    api_base="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY"),
    messages=[{"role": "user", "content": "Hello, introduce yourself"}]
)

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

***

## 基本的な使い方

### 1. モデルの切り替え

AiHubMix はすべての主要モデルをサポートします。切り替えるには `model` パラメータを変更するだけです：

```python theme={null}
import os
from litellm import completion

response = completion(
    model="openai/claude-sonnet-4-6",  # change this
    api_base="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY"),
    messages=[{"role": "user", "content": "Hello, introduce yourself"}]
)

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

***

### 2. ストリーミング

`stream=True` を追加して、トークン単位で出力を受け取ります：

```python theme={null}
import os
from litellm import completion

response = completion(
    model="openai/claude-sonnet-4-6",
    api_base="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY"),
    messages=[{"role": "user", "content": "Explain Python in 100 words"}],
    stream=True
)

for chunk in response:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
print()
```

***

### 3. マルチターン会話

`messages` リストに会話履歴を渡すと、モデルがコンテキストを記憶します：

```python theme={null}
import os
from litellm import completion

messages = [
    {"role": "user", "content": "My name is Alex"},
    {"role": "assistant", "content": "Hello, Alex!"},
    {"role": "user", "content": "What is my name?"}
]

response = completion(
    model="openai/claude-sonnet-4-6",
    api_base="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY"),
    messages=messages
)

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

***

### 4. 非同期呼び出し

各リクエストの完了を待たずに、複数のリクエストを並行して送信します：

```python theme={null}
import os
import asyncio
from litellm import acompletion

async def ask(question):
    response = await acompletion(
        model="openai/claude-sonnet-4-6",
        api_base="https://aihubmix.com/v1",
        api_key=os.environ.get("AIHUBMIX_API_KEY"),
        messages=[{"role": "user", "content": question}]
    )
    return response.choices[0].message.content

async def main():
    questions = [
        "What color is an apple?",
        "What color is the sky?",
        "What color is grass?"
    ]
    results = await asyncio.gather(*[ask(q) for q in questions])
    for q, r in zip(questions, results):
        print(f"Q: {q}")
        print(f"A: {r}")
        print()

asyncio.run(main())
```

***

### 5. タイムアウトとリトライ

ネットワーク問題でリクエストがハングしたり失敗したりするのを防ぎます：

```python theme={null}
import os
from litellm import completion

response = completion(
    model="openai/claude-sonnet-4-6",
    api_base="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY"),
    messages=[{"role": "user", "content": "Hello"}],
    timeout=10,      # raise an error after 10 seconds
    num_retries=3    # retry up to 3 times on failure
)

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

> `timeout` は秒単位です。`num_retries` は 2-3 に設定してください。値が大きいと応答が遅くなります。

***

### 6. トークン使用量とコスト追跡

すべてのレスポンスにはトークン使用量データが含まれます：

```python theme={null}
import os
from litellm import completion

response = completion(
    model="openai/claude-sonnet-4-6",
    api_base="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY"),
    messages=[{"role": "user", "content": "Explain Python in 100 words"}]
)

print(response.choices[0].message.content)
print()
print("Token usage:")
print(f"  Input:  {response.usage.prompt_tokens}")
print(f"  Output: {response.usage.completion_tokens}")
print(f"  Total:  {response.usage.total_tokens}")
```

呼び出しごとのコストを追跡：

```python theme={null}
import os
from litellm import completion, completion_cost

response = completion(
    model="openai/claude-sonnet-4-6",
    api_base="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY"),
    messages=[{"role": "user", "content": "Explain Python in 100 words"}]
)

cost = completion_cost(completion_response=response)
print(f"Cost: ${cost:.6f}")
```

***

### 7. ロードバランシングとフェイルオーバー

複数のモデルを設定して、トラフィックを自動的に分散したり、1 つが失敗したときにバックアップに切り替えたりします：

```python theme={null}
import os
from litellm import Router

router = Router(
    model_list=[
        {
            "model_name": "my-model",
            "litellm_params": {
                "model": "openai/claude-sonnet-4-6",
                "api_base": "https://aihubmix.com/v1",
                "api_key": os.environ.get("AIHUBMIX_API_KEY"),
            }
        },
        {
            "model_name": "my-model",
            "litellm_params": {
                "model": "openai/gpt-4o",
                "api_base": "https://aihubmix.com/v1",
                "api_key": os.environ.get("AIHUBMIX_API_KEY"),
            }
        }
    ]
)

response = router.completion(
    model="my-model",
    messages=[{"role": "user", "content": "Hello"}]
)

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

> 両方のモデルは同じ `model_name` を共有します。LiteLLM はそれらの間をラウンドロビンし、1 つがエラーを返した場合は自動的にフェイルオーバーします。

***

### 8. Proxy Server のデプロイ

Proxy Server はスタンドアロンゲートウェイです。チームメンバーは独自の API キーを持たずに、すべてのリクエストをそれを通してルーティングします。

**インストール**

```bash theme={null}
python3 -m pip install 'litellm[proxy]'
```

**config.yaml の作成**

```yaml theme={null}
model_list:
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_base: https://aihubmix.com/v1
      api_key: os.environ/AIHUBMIX_API_KEY

  - model_name: claude-sonnet
    litellm_params:
      model: openai/claude-sonnet-4-6
      api_base: https://aihubmix.com/v1
      api_key: os.environ/AIHUBMIX_API_KEY

  - model_name: gemini-flash
    litellm_params:
      model: openai/gemini-2.0-flash
      api_base: https://aihubmix.com/v1
      api_key: os.environ/AIHUBMIX_API_KEY
```

**サーバーの起動**

```bash theme={null}
litellm --config config.yaml --port 4000
```

起動が成功すると以下が表示されます：

```text theme={null}
LiteLLM: Proxy running on http://0.0.0.0:4000
```

**ローカルサーバーの呼び出し**

```python theme={null}
import os
from litellm import completion

response = completion(
    model="gpt-4o",
    api_base="http://localhost:4000",
    api_key="any-string",
    messages=[{"role": "user", "content": "Hello"}]
)

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

> ここでの `api_key` は任意の文字列で構いません。実際の AiHubMix キーは Proxy で管理されます。

***

### 9. 仮想キー管理

仮想キーを使用すると、異なるチームメンバーやプロジェクトに独立したキーを割り当てることができ、実際の AiHubMix キーを公開することなくアクセスと使用量を制御できます。

**前提条件：PostgreSQL インスタンスを起動**

```bash theme={null}
docker run -d \
  --name litellm-db \
  -e POSTGRES_USER=litellm \
  -e POSTGRES_PASSWORD=litellm \
  -e POSTGRES_DB=litellm \
  -p 5432:5432 \
  postgres
```

**config.yaml の更新**

```yaml theme={null}
model_list:
  - model_name: gpt-4o
    litellm_params:
      model: openai/gpt-4o
      api_base: https://aihubmix.com/v1
      api_key: os.environ/AIHUBMIX_API_KEY

  - model_name: claude-sonnet
    litellm_params:
      model: openai/claude-sonnet-4-6
      api_base: https://aihubmix.com/v1
      api_key: os.environ/AIHUBMIX_API_KEY

general_settings:
  master_key: sk-my-master-key
  database_url: postgresql://litellm:litellm@localhost:5432/litellm
```

**サーバーの再起動**

```bash theme={null}
litellm --config config.yaml --port 4000
```

**仮想キーの作成**

```bash theme={null}
curl -X POST http://localhost:4000/key/generate \
  -H "Authorization: Bearer sk-my-master-key" \
  -H "Content-Type: application/json" \
  -d '{
    "key_alias": "team-a",
    "max_budget": 10,
    "models": ["gpt-4o", "claude-sonnet"]
  }'
```

レスポンスの `key` フィールドが仮想キーです。例：`sk-xxxxxx`

**仮想キーの使用**

```python theme={null}
from litellm import completion

response = completion(
    model="claude-sonnet",
    api_base="http://localhost:4000",
    api_key="sk-xxxxxx",
    messages=[{"role": "user", "content": "Hello"}]
)

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

**使用状況の確認**

```bash theme={null}
curl http://localhost:4000/key/info \
  -H "Authorization: Bearer sk-my-master-key" \
  -H "Content-Type: application/json" \
  -d '{"key": "sk-xxxxxx"}'
```

> 各仮想キーは個別のモデル制限、予算制限、有効期限をサポートします — 複数メンバーのチームワークフローに最適です。

***

## 実践例：マルチモデル比較

同じ質問を複数のモデルに同時に送信し、出力品質、速度、トークン使用量を比較します。

**API キーの設定**

```bash theme={null}
export AIHUBMIX_API_KEY="your-key"
```

**比較の実行**

```python theme={null}
import os
import time
import asyncio
from litellm import acompletion

MODELS = [
    "gpt-5.5",
    "claude-opus-4-7",
    "deepseek-v4-flash",
    "coding-glm-5.1-free",
]

QUESTION = "If you could give a programmer only one piece of advice, what would it be?"

async def ask_model(model, question):
    start = time.time()
    try:
        response = await acompletion(
            model=f"openai/{model}",
            api_base="https://aihubmix.com/v1",
            api_key=os.environ.get("AIHUBMIX_API_KEY"),
            messages=[{"role": "user", "content": question}]
        )
        return {
            "model": model,
            "answer": response.choices[0].message.content.strip(),
            "tokens": response.usage.total_tokens,
            "time": round(time.time() - start, 2),
            "error": None
        }
    except Exception as e:
        return {
            "model": model,
            "answer": None,
            "tokens": 0,
            "time": round(time.time() - start, 2),
            "error": str(e)
        }

async def main():
    print(f"Question: {QUESTION}")
    print("=" * 60)
    tasks = [ask_model(m, QUESTION) for m in MODELS]
    results = await asyncio.gather(*tasks)
    for r in results:
        print(f"\nModel: {r['model']}")
        print(f"Time: {r['time']}s  |  Tokens: {r['tokens']}")
        print("-" * 40)
        if r["error"]:
            print(f"Error: {r['error']}")
        else:
            print(r["answer"])
    print("\n" + "=" * 60)
    print(f"{'Model':<30} {'Time':>8} {'Tokens':>8}")
    print("-" * 50)
    for r in sorted(results, key=lambda x: x["time"]):
        status = f"{r['time']}s" if not r["error"] else "failed"
        print(f"{r['model']:<30} {status:>8} {r['tokens']:>8}")

asyncio.run(main())
```

<Frame>
  <img src="https://mintcdn.com/aihubmix/Duxh_jCgN8ysLDLU/images/image-91.png?fit=max&auto=format&n=Duxh_jCgN8ysLDLU&q=85&s=e733318a7b9fcfc9eb2d12b9790ea60b" alt="Image" width="1500" height="500" data-path="images/image-91.png" />
</Frame>

最終更新日：2026 年 4 月 29 日
