litellm について
LiteLLMは、統一されたOpenAI形式で複数のLLMプロバイダーを呼び出すPythonインターフェースです。複数プロバイダーを扱うアプリ開発向けに、エラー処理、リトライとフォールバック、ストリーミング、コスト追跡、プロキシ運用を提供します。
主な機能
- 01単一のインターフェースで100以上のプロバイダーを呼び出し
- 02プロバイダーのエラーを標準型に変換
- 03リトライとフォールバックの設定
- 04同期・非同期ストリーミングに対応
- 05利用量とコストの自動追跡
- 06集中型LLMゲートウェイのデプロイ
活用シーン
- 01複数のLLMプロバイダー間でリクエストを振り分け
- 02プロバイダーのエラーを統一的に処理
- 03呼び出しにリトライとフォールバックを設定
- 04プロバイダーごとのLLMコストを追跡
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ jamie-bitflight/ claude_skills --skill litellmインストール後、Claude Code で/litellmを入力して読み込まれたか確認します。
詳細
LiteLLM
100 以上の LLM API を、一貫した OpenAI 形式で呼び出すための統一 Python インターフェースです。複数のプロバイダーにわたる標準化された例外処理、再試行/フォールバックロジック、コスト追跡を提供します。
このスキルを使用する場面
次のような場合に、このスキルを使用します。
- 単一のインターフェースを通じて、複数の LLM プロバイダーと連携する
- OpenAI 互換エンドポイントを使用して、ローカルの llamafile サーバーにリクエストをルーティングする
- LLM 呼び出しの再試行およびフォールバックロジックを実装する
- プロバイダー間で一貫したエラー処理が必要なアプリケーションを構築する
- さまざまなプロバイダーにわたる LLM の利用コストを追跡する
- プロバイダー固有の API と OpenAI 形式を相互に変換する
- 統一された設定で LLM プロキシサーバーをデプロイする
- クラウドとローカルの両方の LLM エンドポイントに対してアプリケーションをテストする
主な機能
プロバイダーのサポート
LiteLLM は、一貫した OpenAI スタイルの API を通じて 100 以上のプロバイダーをサポートします。
- クラウドプロバイダー:OpenAI、Anthropic、Google、Azure、AWS Bedrock
- ローカルサーバー:llamafile、Ollama、LocalAI、vLLM
- 統一形式:すべてのリクエストで OpenAI のメッセージ形式を使用します
- 例外のマッピング:すべてのプロバイダーのエラーを OpenAI の例外型にマッピングします
主な機能
- 統一 API:すべてのプロバイダーで単一の
completion()関数を使用します - 例外処理:すべての例外が OpenAI の型を継承します
- 再試行ロジック:試行回数を設定できる組み込みの再試行機能
- ストリーミング対応:すべてのプロバイダーで同期および非同期ストリーミングに対応します
- コスト追跡:利用状況とコストを自動計算します
- プロキシモード:一元化された LLM ゲートウェイをデプロイします
インストール
# Using pip
pip install litellm
# Using uv
uv add litellm
Llamafile との連携
プロバイダーの設定
ルーティングには、すべての llamafile モデルで llamafile/ プレフィックスを必ず使用してください。
model = "llamafile/mistralai/mistral-7b-instruct-v0.2"
model = "llamafile/gemma-3-3b"
API ベース URL
api_base は、llamafile の OpenAI 互換エンドポイントを必ず指定してください。
api_base = "http://localhost:8080/v1"
重要な要件:
/v1サフィックスを含めてください/chat/completionsのようなエンドポイントパスを追加しないでください(LiteLLM が自動的に追加します)- llamafile のデフォルトポートは 8080 です
環境変数の設定
import os
os.environ["LLAMAFILE_API_BASE"] = "http://localhost:8080/v1"
基本的な使用パターン
同期補完
import litellm
response = litellm.completion(
model="llamafile/mistralai/mistral-7b-instruct-v0.2",
messages=[{"role": "user", "content": "Summarize this diff"}],
api_base="http://localhost:8080/v1",
temperature=0.2,
max_tokens=80,
)
print(response.choices[0].message.content)
非同期補完
from litellm import acompletion
import asyncio
async def generate_message():
response = await acompletion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Write a commit message"}],
api_base="http://localhost:8080/v1",
temperature=0.3,
max_tokens=200,
)
return response.choices[0].message.content
result = asyncio.run(generate_message())
print(result)
非同期ストリーミング
from litellm import acompletion
import asyncio
async def stream_response():
response = await acompletion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Hello, how are you?"}],
api_base="http://localhost:8080/v1",
stream=True,
)
async for chunk in response:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
asyncio.run(stream_response())
埋め込み
from litellm import embedding
import os
os.environ["LLAMAFILE_API_BASE"] = "http://localhost:8080/v1"
response = embedding(model="llamafile/sentence-transformers/all-MiniLM-L6-v2", input=["Hello world"])
print(response)
例外処理
インポート方法
すべての例外を litellm から直接インポートできます。
from litellm import (
BadRequestError, # 400 errors
AuthenticationError, # 401 errors
NotFoundError, # 404 errors
Timeout, # 408 errors (alias: openai.APITimeoutError)
RateLimitError, # 429 errors
APIConnectionError, # 500 errors / connection issues (default)
ServiceUnavailableError, # 503 errors
)
例外型のリファレンス
| ステータスコード | 例外型 | 継承元 | 説明 |
|---|---|---|---|
| 400 | BadRequestError | openai.BadRequestError | 無効なリクエスト |
| 400 | ContextWindowExceededError | litellm.BadRequestError | トークン上限超過 |
| 400 | ContentPolicyViolationError | litellm.BadRequestError | コンテンツポリシー違反 |
| 401 | AuthenticationError | openai.AuthenticationError | 認証失敗 |
| 403 | PermissionDeniedError | openai.PermissionDeniedError | アクセス拒否 |
| 404 | NotFoundError | openai.NotFoundError | 無効なモデル/エンドポイント |
| 408 | Timeout | openai.APITimeoutError | リクエストのタイムアウト |
| 429 | RateLimitError | openai.RateLimitError | レート制限 |
| 500 | APIConnectionError | openai.APIConnectionError | マッピングされないエラーのデフォルト |
| 500 | APIError | openai.APIError | 一般的な 500 エラー |
| 503 | ServiceUnavailableError | openai.APIStatusError | サービス利用不可 |
| >=500 | InternalServerError | openai.InternalServerError | マッピングされない 500 以上のエラー |
例外属性
すべての LiteLLM 例外には、次の属性が含まれます。
status_code:HTTP ステータスコードmessage:エラーメッセージllm_provider:例外を発生させたプロバイダー
例外処理の例
import litellm
import openai
try:
response = litellm.completion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Hello"}],
api_base="http://localhost:8080/v1",
timeout=30.0,
)
except openai.APITimeoutError as e:
# LiteLLM exceptions inherit from OpenAI types
print(f"Timeout: {e}")
except litellm.APIConnectionError as e:
print(f"Connection failed: {e.message}")
print(f"Provider: {e.llm_provider}")
litellm.exceptions からの別のインポート方法
from litellm.exceptions import BadRequestError, AuthenticationError, APIError
try:
response = litellm.completion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Hello"}],
api_base="http://localhost:8080/v1",
)
except AuthenticationError as e:
print(f"Authentication failed: {e}")
except BadRequestError as e:
print(f"Bad request: {e}")
except APIError as e:
print(f"API error: {e}")
例外を再試行するかどうかの確認
import litellm
try:
response = litellm.completion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Hello"}],
api_base="http://localhost:8080/v1",
)
except Exception as e:
if hasattr(e, "status_code"):
should_retry = litellm._should_retry(e.status_code)
print(f"Should retry: {should_retry}")
再試行とフォールバックの設定
from litellm import completion
response = completion(
model="llamafile/gemma-3-3b",
messages=[{"role": "user", "content": "Hello"}],
api_base="http://localhost:8080/v1",
num_retries=3, # Retry 3 times on failure
timeout=30.0, # 30 second timeout
)
プロキシサーバーの設定
プロキシをデプロイする場合は、config.yaml を使用します。
model_list:
- model_name: commit-polish-model
litellm_params:
model: llamafile/gemma-3-3b # add llamafile/ prefix
api_base: http://localhost:8080/v1 # add api base for OpenAI compatible provider
アプリケーション統合パターン
接続確認パターン
import litellm
from litellm import APIConnectionError
def verify_llamafile_connection(api_base: str = "http://localhost:8080/v1") -> bool:
"""Check if llamafile server is running."""
try:
litellm.completion(
model="llamafile/test", messages=[{"role": "user", "content": "test"}], api_base=api_base, max_tokens=1
)
return True
except APIConnectionError:
return False
非同期サービスパターン
import litellm
from litellm import acompletion, APIConnectionError
import asyncio
class AIService:
"""LiteLLM wrapper with llamafile routing."""
def __init__(self, model: str, api_base: str, temperature: float = 0.3, max_tokens: int = 200):
self.model = model
self.api_base = api_base
self.temperature = temperature
self.max_tokens = max_tokens
async def generate_commit_message(self, diff: str, system_prompt: str) -> str:
"""Generate a commit message using the LLM."""
try:
response = await acompletion(
model=self.model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"Generate a commit message for this diff:\n\n{diff}"},
],
api_base=self.api_base,
temperature=self.temperature,
max_tokens=self.max_tokens,
)
return response.choices[0].message.content.strip()
except APIConnectionError as e:
raise RuntimeError(f"Failed to connect to llamafile server at {self.api_base}: {e.message}")
よくある落とし穴
llamafile/プレフィックスの欠落:プレフィックスがないと、LiteLLM は OpenAI 互換エンドポイントにルーティングできません- ポートの誤り:Llamafile のデフォルトポートは 8000 ではなく 8080 です
/v1サフィックスの欠落:API ベース URL の末尾には/v1が必要です- 余分なパス要素の追加:
http://localhost:8080/v1/chat/completionsは使用しないでください。LiteLLM がエンドポイントのパスを自動的に追加します - API キーの要件:ローカルの llamafile では API キーは不要です(検証で必要な場合は、空文字列または任意の値を使用します)
設定例
TOML 設定
# ~/.config/commit-polish/config.toml
[ai]
model = "llamafile/gemma-3-3b" # MUST have llamafile/ prefix
temperature = 0.3
max_tokens = 200
環境変数
export LLAMAFILE_API_BASE="http://localhost:8080/v1"
export LITELLM_LOG="INFO" # Enable LiteLLM debug logging
関連スキル
関連ツールの詳しいドキュメントについては、次をご覧ください。
- llamafile:ワークスペースにインストール済みの llamafile プラグインがある場合は、サーバーのセットアップ、モデル管理、ローカル LLM のデプロイパターンに使用してください。ない場合は、このドキュメントに記載されているエンドポイントとモデルプレフィックスのガイダンスに従ってください。
- uv:ワークスペースにインストール済みの Python/uv プラグインがある場合は、プロジェクト管理、依存関係の処理、仮想環境のワークフローに使用してください。ない場合は、標準の
uvコマンドとプロジェクト内の環境を使用してください。
参考資料
公式ドキュメント
- LiteLLM のドキュメント - メインのドキュメントポータル
- Llamafile プロバイダーのドキュメント - Llamafile 固有の設定
- 例外マッピング - 例外に関する完全なリファレンス
- GitHub リポジトリ - ソースコードと例
プロバイダー固有のドキュメント
- Llamafile API エンドポイント - Llamafile の OpenAI 互換 API リファレンス
- 補完のストリーミング - ストリーミング実装ガイド
バージョン情報
- ドキュメントの確認対象:LiteLLM GitHub リポジトリ(main ブランチ、2025-01-15 にアクセス)
- Python:3.11+
- Llamafile:0.9.3+
コメント
Markdown 対応