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

# Pydantic AI

> [!NOTE]
>
> **本ガイドで構築するもの:** SambaCloud でホストされているモデル上で動作する Pydantic AI エージェントを構築します。構造化出力、ツール呼び出し、ストリーミングの例を掲載しています。

## 概要

[Pydantic AI](https://pydantic.dev/docs/ai/) は、Pydantic チームが開発した Python 向けの型安全 (type-safe) なエージェントフレームワークです。SambaNova プロバイダーが組み込まれているため、以下のことが可能になります。

> **組み込みの SambaNova プロバイダー**
>
> `"sambanova:<model>"` を `Agent` に渡すだけで、API キーは `SAMBANOVA_API_KEY` から自動で読み込まれます。追加のインストールや設定は不要です。

> **型安全なエージェント**
>
> エージェントに期待する出力を Pydantic モデルとして定義すると、自分でパースしなければならない生テキストではなく、検証済みの Python オブジェクトが返されます。

> **ツール呼び出し**
>
> `@agent.tool` で通常の Python 関数をツールとして登録できます。スキーマは関数シグネチャから Pydantic AI が自動生成します。

> **モデル非依存**
>
> モデル文字列を変更するだけでモデルを切り替えられます。それ以外のエージェントコードはそのまま使えます。

## 前提条件

* [SambaCloud アカウント](https://cloud.sambanova.ai/?utm_source=pydantic-ai\&utm_medium=external\&utm_campaign=cloud_signup)と、[SambaCloud ポータル](https://cloud.sambanova.ai/apis?utm_source=pydantic-ai\&utm_medium=external\&utm_campaign=cloud_signup) で取得した API キー
* Python 3.11 以上。それより古いバージョンでは、`pip` がエラーを出さずに古い `pydantic-ai` をインストールします。詳細は [トラブルシューティング](#トラブルシューティング) をご参照ください。
* Python の仮想環境と Pydantic モデルに関する基本的な知識

## セットアップ

**1. 仮想環境の作成と有効化**

```bash macOS / Linux theme={}
python3 -m venv .venv
source .venv/bin/activate
```

```powershell Windows theme={}
python -m venv .venv
.venv\Scripts\Activate.ps1
```

**2. Pydantic AI のインストール**

```bash theme={}
pip install pydantic-ai
```

> [!TIP]
>
> このコマンドで `pydantic`、`openai`、および Pydantic AI 自体の依存パッケージがまとめてインストールされます。SambaCloud に必要なものだけに絞った軽量なインストールにするには、`pip install "pydantic-ai-slim[openai]"` を使用してください。

**3. SambaCloud API キーのエクスポート**

```bash macOS / Linux theme={}
export SAMBANOVA_API_KEY="your-sambacloud-api-key"
```

```powershell Windows theme={}
$env:SAMBANOVA_API_KEY="your-sambacloud-api-key"
```

Pydantic AI の SambaNova プロバイダーは、この環境変数を自動で読み込みます。

> [!WARNING]
>
> API キーは絶対にソース管理にコミットしないでください。`python-dotenv` で読み込む `.env` ファイルか、お使いのシェルのシークレット管理ツールを使用してください。

**4. 最初のエージェントの実行**

```python quickstart.py theme={}
from pydantic_ai import Agent

agent = Agent("sambanova:MiniMax-M3")
result = agent.run_sync("What can you do?")
print(result.output)
```

```bash theme={}
python quickstart.py
```

`sambanova:` プレフィックスは Pydantic AI の [SambaNova プロバイダー](https://pydantic.dev/docs/ai/models/compatible-apis/#sambanova) を選択し、リクエストを `https://api.sambanova.ai/v1` に送信します。プレフィックス以降の部分が SambaCloud のモデル ID です。

> [!TIP]
>
> Pydantic AI は、出力の前に起動バナーを標準エラー出力に表示します。これは情報表示であり、エラーではありません。`PYDANTIC_AI_NO_BANNER=1` を設定すると無効化できます。

## 使用例: 構造化出力

エージェントの `output_type` に Pydantic モデルを指定します。エージェントは、自分でパースしなければならない文字列ではなく、そのモデルの検証済みインスタンスを返します。

```python structured_example.py theme={}
from pydantic import BaseModel
from pydantic_ai import Agent


class CityInfo(BaseModel):
    city: str
    country: str
    population_estimate: int


agent = Agent("sambanova:MiniMax-M3", output_type=CityInfo)
result = agent.run_sync("Tell me about Paris, France.")
print(result.output)
```

実行します。

```bash theme={}
python structured_example.py
```

```text Output theme={}
city='Paris' country='France' population_estimate=2161000
```

> [!NOTE]
>
> `MiniMax-M3` は、[SambaCloud の対応モデル](https://docs.sambanova.ai/docs/ja/models/sambacloud-models.md) ページに掲載されている任意のモデルに差し替えられます。デフォルト設定では、構造化出力は強制的なツール呼び出しとして実行されるため、モデルが Function calling (関数呼び出し) に対応している必要があります。現在の対応一覧は [Function calling と JSON モード](https://docs.sambanova.ai/docs/ja/features/function-calling.md) をご参照ください。

> **Pydantic AI が実際に SambaCloud に送信する内容**
>
> Pydantic AI は `output_type=CityInfo` を、指定した Pydantic モデルの JSON スキーマをパラメータに持つ `final_result` という名前の単一の関数ツールに変換し、`tool_choice: "required"` でモデルにその呼び出しを強制します。実際に `https://api.sambanova.ai/v1/chat/completions` へ送信されるリクエストは以下のとおりです。
>
> ```json Request body theme={}
> {
>   "model": "MiniMax-M3",
>   "stream": false,
>   "messages": [{"role": "user", "content": "Tell me about Paris, France."}],
>   "tool_choice": "required",
>   "tools": [
>     {
>       "type": "function",
>       "function": {
>         "name": "final_result",
>         "description": "The final response which ends this conversation",
>         "parameters": {
>           "type": "object",
>           "properties": {
>             "city": {"type": "string"},
>             "country": {"type": "string"},
>             "population_estimate": {"type": "integer"}
>           },
>           "required": ["city", "country", "population_estimate"],
>           "additionalProperties": false
>         },
>         "strict": true
>       }
>     }
>   ]
> }
> ```
>
> ```json Response (choices[0].message) theme={}
> {
>   "role": "assistant",
>   "content": null,
>   "tool_calls": [
>     {
>       "id": "call_50823124eee04fb1a4",
>       "type": "function",
>       "function": {
>         "name": "final_result",
>         "arguments": "{\"city\": \"Paris\", \"country\": \"France\", \"population_estimate\": 2161000}"
>       }
>     }
>   ]
> }
> ```
>
> Pydantic AI はこのツール呼び出しの `arguments` をパースして Pydantic モデルとして検証します。これにより、上記の JSON が `result.output` の返す `CityInfo(...)` オブジェクトになります。

## 使用例: ツール呼び出し

`@agent.tool` で Python 関数をツールとして登録します。Pydantic AI は関数の型ヒントと docstring からツールスキーマを生成してモデルに送信し、モデルがツールを呼び出すとその関数を実行します。

```python tool_example.py theme={}
from pydantic_ai import Agent, RunContext

agent = Agent(
    "sambanova:MiniMax-M3",
    instructions="Use the get_weather tool to answer weather questions.",
)


@agent.tool
def get_weather(ctx: RunContext[None], city: str) -> str:
    """Get the current weather for a city."""
    return f"It is sunny and 22C in {city}."


result = agent.run_sync("What's the weather like in Tokyo right now?")
print(result.output)
```

実行します。

```bash theme={}
python tool_example.py
```

```text Output theme={}
The weather in Tokyo right now is **sunny** with a temperature of **22°C** (about 72°F). Sounds like a lovely day to be outside! ☀️
```

> [!NOTE]
>
> `MiniMax-M3` は Reasoning モデルであり、各応答の前に `ThinkingPart` を出力しますが、ツール呼び出しの妨げにはなりません。散文で回答するのではなく、最初の試行で正しくツール呼び出しを返します。すべての Reasoning モデルがこのように動作するとは限らないため、モデルを切り替えた場合は再確認してください。

> **メッセージトレースの全体 (result.all\_messages())**
>
> `result.all_messages()` を確認すると、やり取りの全体が見えます: `ThinkingPart` と `ToolCallPart`、関数の結果を含む `ToolReturnPart`、そして最終回答の前の 2 つ目の `ThinkingPart` です。モデルが推測で回答するのではなく、実際に `get_weather` を呼び出したことの確認に使用してください。
>
> ```text theme={}
> ModelRequest [
>     UserPromptPart(content="What's the weather like in Tokyo right now?"),
> ]
> ModelResponse [
>     ThinkingPart(content='The user is asking about the current weather in Tokyo. I should use the get_weather tool to fetch this information.'),
>     ToolCallPart(tool_name='get_weather', args='{"city": "Tokyo"}'),
> ]
> ModelRequest [
>     ToolReturnPart(tool_name='get_weather', content='It is sunny and 22C in Tokyo.'),
> ]
> ModelResponse [
>     ThinkingPart(content='The tool returned the weather information for Tokyo. Let me provide a clear response to the user.'),
>     TextPart(content='The weather in Tokyo right now is **sunny** with a temperature of **22°C** (about 72°F). Sounds like a lovely day to be outside! ☀️'),
> ]
> ```

## 使用例: ストリーミング

完全な回答を待つのではなく、生成と同時に応答を表示するには `run_stream` を使用します。

```python stream_example.py theme={}
import asyncio

from pydantic_ai import Agent

agent = Agent("sambanova:MiniMax-M3")


async def main() -> None:
    async with agent.run_stream("What are your capabilities?") as result:
        async for chunk in result.stream_text(delta=True):
            print(chunk, end="", flush=True)
    print()


asyncio.run(main())
```

実行します。

```bash theme={}
python stream_example.py
```

`stream_text(delta=True)` は、各チャンクの新規テキストのみを返します。ストリーミングは `output_type` と組み合わせることもできます: `result.stream_output()` をイテレートすると、部分的に検証されたオブジェクトを順次取得できます。

## プロバイダーの明示的な設定

`sambanova:` のモデル文字列は省略記法です。API キーを自分で渡す場合や、ベース URL を変更する場合は、`SambaNovaProvider` でモデルを構築します。

```python theme={}
import os

from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.sambanova import SambaNovaProvider

model = OpenAIChatModel(
    "MiniMax-M3",
    provider=SambaNovaProvider(api_key=os.environ["SAMBANOVA_API_KEY"]),
)
agent = Agent(model)
```

| パラメータ | 説明 |
| :- | :- |
| `api_key` | SambaCloud の API キー。デフォルトでは環境変数 `SAMBANOVA_API_KEY` が使用されます。 |
| `base_url` | SambaCloud API のベース URL。デフォルトでは環境変数 `SAMBANOVA_BASE_URL`、次いで `https://api.sambanova.ai/v1` が使用されます。 |

> **汎用の OpenAIProvider を使用する場合**
>
> SambaCloud は OpenAI 互換のため、Pydantic AI の汎用 `OpenAIProvider` でも同じ例が動作します。
>
> ```python theme={}
> import os
>
> from pydantic_ai import Agent
> from pydantic_ai.models.openai import OpenAIChatModel
> from pydantic_ai.providers.openai import OpenAIProvider
>
> model = OpenAIChatModel(
>     "MiniMax-M3",
>     provider=OpenAIProvider(
>         base_url="https://api.sambanova.ai/v1",
>         api_key=os.environ["SAMBANOVA_API_KEY"],
>     ),
> )
> agent = Agent(model)
> ```

## ユースケースの例

上記の例はそれぞれ 1 つの機能を示したものです。以下の例は、構造化出力とツール呼び出しを組み合わせた、完全で実行可能なアプリです。

* [旅行アシスタント](https://github.com/sambanova/integrations/tree/main/pydantic_ai_integration): 2 つのツールを連鎖させて都市の情報と最新の天気予報を調べ、検証済みの `TripBrief` オブジェクトを返す、ターミナルで動くサンプルアプリです。会話を保持するため、追加の質問でもどの都市の話かが伝わります。本ページで扱っていない機能である依存性注入 (dependency injection)、ツールの再試行、型付きのツール結果の例にもなっています。

## 参考情報

> **[Pydantic AI リポジトリ](https://github.com/pydantic/pydantic-ai)**
>
> Pydantic AI のソースコード、サンプル、リリースノート。

> **[Pydantic AI ドキュメント](https://pydantic.dev/docs/ai/)**
>
> エージェント、ツール、依存性注入、マルチエージェントワークフローを扱う公式ガイド。

> **[Pydantic AI の SambaNova プロバイダー](https://pydantic.dev/docs/ai/models/compatible-apis/#sambanova)**
>
> `sambanova:` モデルプレフィックスと `SambaNovaProvider` に関する Pydantic AI 側のリファレンス。

> **[対応モデル](https://docs.sambanova.ai/docs/ja/models/sambacloud-models.md)**
>
> SambaCloud で現在利用可能なモデルの一覧。

> **[Function calling と JSON モード](https://docs.sambanova.ai/docs/ja/features/function-calling.md)**
>
> ツール呼び出しと構造化出力に対応する SambaCloud モデルの一覧。

## トラブルシューティング

> **ModuleNotFoundError: No module named 'pydantic\_ai'**
>
> `pip install pydantic-ai` でインストールしたうえで、仮想環境が有効になっていることを確認してください: `which python3`（Windows では `Get-Command python`）が `.venv` 内を指しているはずです。

> **UserError: Set the `SAMBANOVA_API_KEY` environment variable**
>
> SambaNova プロバイダーが API キーを見つけられていません。実行前に `export SAMBANOVA_API_KEY="your-key"` でエクスポートし、`echo $SAMBANOVA_API_KEY` で確認してください。Windows PowerShell では `$env:SAMBANOVA_API_KEY="your-key"` を使用し、`echo $env:SAMBANOVA_API_KEY` で確認します。`export` は実行したシェルにのみ適用されるため、新しいターミナルでは再度の設定が必要です。

> **UserError: Native structured output is not supported by this model**
>
> `output_type` を `NativeOutput(...)` でラップしていますが、Pydantic AI の SambaNova プロバイダーは SambaCloud モデルを JSON スキーマ出力対応として扱っていないため、リクエスト送信前に停止します。Pydantic モデルを直接渡してください (`output_type=CityInfo`)。デフォルトモードは強制的なツール呼び出しを使用します。これは [構造化出力の使用例](#使用例-構造化出力) が実行している方式です。

> **登録したツールをエージェントが呼び出さない**
>
> 渡したモデルが Function calling に対応していることを確認してください。現在の対応一覧は [Function calling と JSON モード](https://docs.sambanova.ai/docs/ja/features/function-calling.md) をご参照ください。Function calling 非対応のモデルは、ツール呼び出しを出力する代わりに散文で回答します。Pydantic AI 側にそのケースのフォールバックはありません。

> **古いバージョンの pydantic-ai がインストールされた**
>
> 現行リリースには Python 3.11 以上が必要です。非対応バージョンの Python では、`pip` はエラーを報告する代わりに、その Python をまだサポートしている最新リリースをインストールするため、インストールは成功したように見えます。`pip show pydantic-ai` でバージョンを確認し、想定より古い場合は Python 3.11 以上で仮想環境を再作成してください。
