> ## 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.

# AutoGen

AutoGen は、協調型のマルチエージェントワークフローを構築するためのオープンソースフレームワークです。本記事では、SambaNova のモデルと組み合わせて、複雑な複数ステップのタスクを自動化する方法を解説します。

## 前提条件

作業を始める前に、以下の環境を準備してください。

* [SambaCloud](https://cloud.sambanova.ai?utm_source=autogen\&utm_medium=external\&utm_campaign=cloud_signup) アカウントと有効な API キー。
* Python 3.10 以上。`python --version` でご確認ください。AutoGen 0.4 以降は Python 3.10 が必要で、Python 3.9 では `pip` が互換性のない 0.2 リリースをインストールしてしまいます。

## インストール

本ガイドでは、AutoGen 0.4 以降のパッケージを使用します。エージェントとチームには `autogen-agentchat` を、モデルクライアントには `autogen-ext` に含まれるものを使います。

<Warning>
  PyPI には AutoGen の名前を共有するパッケージが複数存在し、それらの API に互換性はありません。インストールするのは `autogen-agentchat` です。`autogen` および `ag2` パッケージは別に保守されているフォークのもので、import が異なるため、一方向けに書かれたコードは他方では動作しません。
</Warning>

1. 仮想環境を作成して有効化します。

   ```bash theme={}
   python -m venv .venv
   source .venv/bin/activate
   ```

2. OpenAI 互換のモデルクライアントとともに AutoGen をインストールします。

   ```bash theme={}
   pip install "autogen-agentchat>=0.7,<0.8" "autogen-ext[openai]>=0.7,<0.8"
   ```

   バージョンの上限指定により、0.7 系の API に固定されます。AutoGen はリリースをまたいでパッケージ構成の再編を重ねてきたため、マイナーバージョンを固定し、アップグレード前にテストしてください。

3. API キーを環境変数に設定します。

   ```bash theme={}
   export SAMBANOVA_API_KEY="your-api-key"
   ```

## AutoGen から SambaCloud への接続

SambaCloud は OpenAI 互換のエンドポイントを公開しているため、`base_url` に `https://api.sambanova.ai/v1` を設定した `OpenAIChatCompletionClient` を通じて接続します。

SambaNova のモデル名は OpenAI のモデル名ではないため、モデルの機能を記述した `model_info` ディクショナリも渡す必要があります。これがないと、クライアントは `ValueError: model_info is required when model name is not a valid OpenAI model` エラーを送出します。

以下の例では、2 つのエージェントからなるチームを構築します。writer が説明文の下書きを作成し、reviewer がそれを承認するか修正を求めます。reviewer が `APPROVED` と応答するまで、両者が交互にやり取りを続けます。

```python theme={}
import asyncio
import os

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient


async def main() -> None:
    model_client = OpenAIChatCompletionClient(
        model="Meta-Llama-3.3-70B-Instruct",
        base_url="https://api.sambanova.ai/v1",
        api_key=os.environ["SAMBANOVA_API_KEY"],
        model_info={
            "vision": False,
            "function_calling": True,
            "json_output": False,
            "structured_output": False,
            "family": "unknown",
        },
    )

    writer = AssistantAgent(
        "writer",
        model_client=model_client,
        description="Drafts short technical explanations.",
        system_message="You draft short technical explanations. Keep them under 120 words.",
    )

    reviewer = AssistantAgent(
        "reviewer",
        model_client=model_client,
        description="Reviews drafts for accuracy and clarity.",
        system_message=(
            "You review the draft for accuracy and clarity. "
            "If it is correct and clear, reply with APPROVED. "
            "Otherwise, list the specific fixes needed."
        ),
    )

    team = RoundRobinGroupChat(
        [writer, reviewer],
        termination_condition=TextMentionTermination("APPROVED"),
        max_turns=4,
    )

    await Console(team.run_stream(task="Explain what a mixture-of-experts model is."))
    await model_client.close()


asyncio.run(main())
```

以下のような出力が表示されます。

```text theme={}
# Expected output
---------- TextMessage (user) ----------
Explain what a mixture-of-experts model is.
---------- TextMessage (writer) ----------
A mixture-of-experts model routes each token to a small subset of specialist
subnetworks, so only a fraction of parameters activate per token. That keeps
compute per token low while total capacity stays high.
---------- TextMessage (reviewer) ----------
APPROVED
```

`Console` は各ターンを到着順に、ヘッダーにエージェント名を付けて表示します。この `writer` と `reviewer` のラベルによって、一方が 2 回答えたのではなく両方のエージェントが動作したことを確認できます。実行は、メッセージに `APPROVED` が含まれた時点 (この例ではモデル呼び出し 2 回) で停止し、reviewer が承認しない場合は 4 ターンで終了します。`writer` のターンしか表示されない場合は、終了文字列が一致せず、`max_turns` によって実行が終了したことを意味します。

<Note>
  AutoGen 0.4 以降は非同期ファーストの設計です。エージェントとチームのメソッドは await する必要があり、この例で `asyncio.run()` にラップしているのはそのためです。Jupyter ノートブックでは、`asyncio.run(main())` の行を削除し、セル内で直接それらの呼び出しを `await` してください。
</Note>

### モデルの選択

`model` には任意の [SambaCloud モデル](/docs/ja/models/sambacloud-models) を渡せます。エージェントにツールを持たせるマルチエージェントワークフローでは、Function calling (関数呼び出し) に対応したモデルも必要です。クライアントはツールをアタッチした後になって初めて `ValueError: Model does not support function calling` エラーを送出するため、`"function_calling": True` を設定する前に [対応モデル](/docs/ja/features/function-calling) をご確認ください。

## サンプルノートブック

以下のノートブックで実際の活用例を試してみましょう。

* [旅行プラン作成ノートブック](https://github.com/sambanova/integrations/blob/main/autogen/travel-planning.ipynb): エージェントのチームによって、詳細な旅行スケジュールを構築します。このノートブックに必要なのは SambaNova の API キーのみなので、まずはこちらから始めてください。
* [企業リサーチノートブック](https://github.com/sambanova/integrations/blob/main/autogen/company-research.ipynb): 複数のエージェントからなるチームで Web 検索や株式情報の取得を行い、レポートを生成します。こちらは Google Custom Search の API キーと検索エンジン ID も必要で、`yfinance` と `matplotlib` をインストールします。

どちらのノートブックも `.env` ファイルから `SAMBANOVA_API_KEY` と `SAMBANOVA_URL` を読み込み、見つからない値があれば入力を求めます。`SAMBANOVA_URL` には `https://api.sambanova.ai/v1` を設定してください。

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

<AccordionGroup>
  <Accordion title="ModuleNotFoundError: No module named 'autogen_agentchat'">
    0.2 リリースがインストールされています。0.2 は代わりに `autogen` モジュールを提供します。0.4 以降は Python 3.10 が必要なため、Python 3.9 では `pip` が 0.2 を暗黙のうちに選択します。

    `python --version` が 3.10 以上であることを確認し、[インストール](#インストール) に記載のバージョン上限付きコマンドで再インストールしてください。
  </Accordion>

  <Accordion title="ValueError: model_info is required when model name is not a valid OpenAI model">
    `OpenAIChatCompletionClient` はモデル名をもとに機能を参照しますが、SambaNova のモデル名は認識できません。

    [AutoGen から SambaCloud への接続](#autogen-から-sambacloud-への接続) に示した `model_info` ディクショナリを渡してください。
  </Accordion>

  <Accordion title="ValueError: Missing required field in ModelInfo">
    `model_info` では、`vision`、`function_calling`、`json_output`、`family` がそれぞれ必須です。

    不足しているキーを追加してください。`structured_output` の省略は `UserWarning: Missing required field 'structured_output' in ModelInfo` の表示のみで構築自体は成功しますが、今後のリリースで必須になるため、上記のとおり 5 つすべてを設定してください。
  </Accordion>

  <Accordion title="ValueError: Model does not support function calling">
    `model_info` で `"function_calling": False` を設定したエージェントにツールをアタッチしています。

    [Function calling の対応モデル](/docs/ja/features/function-calling) からモデルを選択し、`"function_calling": True` を設定してください。
  </Accordion>

  <Accordion title="エンドポイントからの 401 または 403 エラー">
    `SAMBANOVA_API_KEY` が未設定か期限切れになっているか、スクリプトを実行するシェルにエクスポートが反映されていません。

    キーを再度エクスポートし、以下のコマンドで動作をご確認ください。

    ```bash theme={}
    curl -H "Authorization: Bearer $SAMBANOVA_API_KEY" https://api.sambanova.ai/v1/models
    ```
  </Accordion>
</AccordionGroup>

## 参考情報

* [AutoGen の公式ドキュメント](https://microsoft.github.io/autogen/stable/)（英語）
* [Function calling](/docs/ja/features/function-calling)
* [SambaCloud モデル](/docs/ja/models/sambacloud-models)
