ai について
`ai` は Python 3.12 以降向けの AI SDK です。モデル呼び出しに加え、Python ツールを実行し会話履歴を管理するエージェントを構築できます。AI Gateway またはプロバイダーを直接指定してモデルにアクセスします。
主な機能
- 01AI Gateway またはプロバイダー経由のモデル呼び出し
- 02モデル応答のストリーミング
- 03実行可能な Python ツールの定義
- 04ツールループと履歴を管理するエージェント
活用シーン
- 01Python アプリケーションから LLM を呼び出す
- 02Python ツールを実行するエージェントの構築
- 03応答ストリームと会話履歴の処理
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ vercel-labs/ ai-python --skill aiインストール後、Claude Code で/aiを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/custom-loops.mdcustom-provider.mddurable.mdserverless.mdstreaming-tools.mdui.md詳細
Python 向け AI SDK
パッケージ:ai。Python 3.12 以降が必要です。uv add ai でインストールします。
プレフィックスのないモデル ID は AI Gateway と AI_GATEWAY_API_KEY を使用します。直接プロバイダーを使う場合は、provider:model、その API キー、および追加パッケージを使用します。
uv add "ai[openai]" # OPENAI_API_KEY, ai.get_model("openai:gpt-5")
uv add "ai[anthropic]" # ANTHROPIC_API_KEY, ai.get_model("anthropic:claude-sonnet-4")
基本的な使い方
Python ツールを実行せずに 1 回だけモデルを呼び出すには、ai.stream を使用します。
import ai
model = ai.get_model("anthropic/claude-sonnet-4")
messages = [
ai.system_message("Be concise."),
ai.user_message("Write a haiku about rain."),
]
async with ai.stream(model, messages) as stream:
async for event in stream:
if isinstance(event, ai.events.TextDelta):
print(event.chunk, end="", flush=True)
answer = stream.output
message = stream.message
Python ツールを実行して履歴を管理するループには、ai.Agent を使用します。
@ai.tool
async def get_weather(city: str) -> str:
"""Get the weather for a city."""
return "Sunny"
agent = ai.Agent(tools=[get_weather])
async with agent.run(model, messages) as run:
async for event in run:
if isinstance(event, ai.events.TextDelta):
print(event.chunk, end="", flush=True)
answer = run.output
history = run.messages
これらの例で、基本的なモデル呼び出し、メッセージ、ツール、エージェントの使い方を十分に確認できます。
高度な作業
高度なタスクに取り組む場合は、https://ai-python.dev/docs/ 配下にある該当ページを取得し、コードを書く前に、一覧にあるローカルの補足資料を読んでください。
| タスク | ページ | ローカルの補足資料 |
|---|---|---|
| プロバイダークライアント、オプション、検出 | basics/providers.md | — |
| 構造化出力、複雑なストリーム | basics/streaming.md | — |
| バッファリングされた言語モデルの呼び出し | basics/streaming.md | — |
| 画像、動画、音声、埋め込み、文字起こし、再ランキング、評価 | basics/model-operations.md | — |
| イベントとシリアライズ | basics/messages-and-events.md | — |
| 高度なツール、ストリーミング、集約 | basics/tools.md | streaming-tools.md |
| 高度なエージェントの動作 | basics/agents.md | — |
| 決定的なモデルとエージェントのテスト | basics/testing.md | — |
| サブエージェントとマルチエージェント | basics/subagents-and-multi-agent.md | streaming-tools.md |
| カスタムエージェントループ | basics/custom-loops.md | custom-loops.md |
| 承認とフック | basics/human-in-the-loop.md | — |
| サーバーレスでの再開 | basics/human-in-the-loop.md | serverless.md |
| 永続的な実行 | basics/durable-execution.md | durable.md |
| テレメトリーとトレーシング | basics/telemetry.md | — |
| AI SDK UI バックエンド | basics/ai-sdk-ui.md | ui.md |
| カスタムプロバイダー | basics/providers.md | custom-provider.md |
API の詳細は、reference.md と該当する reference/*.md ページを参照してください。
コメント
Markdown 対応