本文へスキップ

ドキュメントを検索

入力すると、ドキュメントのすべてのページを検索できます。

ドキュメントメニュー
チュートリアル対象読者 · Agent-Lab を初めて使う方

最初のエージェント

ゼロから、動作して観測可能なエージェントまで — 約 15 分で

このページは英語から機械翻訳されました。相違がある場合は原文が優先されます。英語の原文を読む

作成するもの

完全に動作する Agent-Lab アプリケーションを作成します。エコーエージェント、MCP サーバー、 PostgreSQL による永続化、OpenTelemetry による計装をホストする FastAPI サービスで、すべてが 1 つのコマンドで生成され、手作業での配線は一切ありません。その過程で、REST 経由でエージェントインスタンスを作成し、メッセージを送信し、フレームワークのトレースを確認します。

前提条件

  • Python 3.12+ と uv(pip install uv)
  • 実行中の Docker(または他のコンテナランタイム)

このチュートリアルでは API キーは不要です。エコーエージェントは LLM を呼び出さないためです。 LLM を使うエージェントはこの後に扱います(次のステップを参照)。


1. プロジェクトの雛形を生成する

uvx cookiecutter gh:btech-software/agent-lab --directory cookiecutter

プロンプトに回答します。デフォルトのままにすると、My Agent App という名前のプロジェクトが作成されます。

cd my-agent-app

生成されたプロジェクトはフレームワークのフォークではなく、フレームワークを利用する薄いコンシューマーです。 btech-agent-lab は pyproject.toml の通常の依存関係であり、あなたのコードはその隣に置かれ、公開 API を通じてフレームワークを拡張します。

2. 生成された内容を理解する

my-agent-app/
├── my_agent_app/
│   ├── main.py              # the composition root — one create_app() call
│   ├── core/container.py    # your DI container — add providers here
│   ├── agents/echo/agent.py # your first agent (echo)
│   └── mcp/tools.py         # your first MCP tool
├── config-dev.yml / config-test.yml / config-docker.yml
├── tests/                   # unit tests (no infra) + optional testcontainers suite
├── compose.yml              # app + postgres (pgvector) + redis + vault
└── Makefile, docker/, .github/, pyproject.toml

my_agent_app/main.py を開いてください。これがアプリケーションのすべてです。

from agent_lab import create_app

from my_agent_app.core.container import Container

# An explicit scan_packages list replaces agent_lab's DEFAULT_SCAN_PACKAGES:
# only this project's agents, MCP tools, and prompts are discovered — none of
# the framework's built-in examples. Add "agent_lab.services.agent_types" or
# "agent_lab.interface.mcp" here if you want the built-ins back.
app = create_app(
    container=Container(),
    scan_packages=[
        "my_agent_app.agents",
        "my_agent_app.mcp",
    ],
)

そして my_agent_app/agents/echo/agent.py がエージェント本体です。

from langchain_core.messages import AIMessage
from langgraph.graph import MessagesState

from agent_lab import AgentBase, AgentUtils, discoverable_agent
from agent_lab.interface.api.messages.schema import Message, MessageRequest
from agent_lab.services.tasks import TaskProgress


@discoverable_agent("my_agent_app_echo")
class EchoAgent(AgentBase):
    """Minimal agent: echoes the incoming message without calling an LLM."""

    def __init__(self, agent_utils: AgentUtils):
        super().__init__(agent_utils)

    def create_default_settings(self, agent_id: str, schema: str):
        pass

    def get_input_params(self, message_request: MessageRequest, schema: str) -> dict:
        return message_request.model_dump()

    def process_message(self, message_request: MessageRequest, schema: str) -> Message:
        message_content, response_data = self.format_response(
            MessagesState(
                messages=[AIMessage(content=f"Echo: {message_request.message_content}")]
            )
        )

        self.task_notification_service.publish_update(
            task_progress=TaskProgress(
                agent_id=message_request.agent_id,
                status="completed",
                message_content=message_content,
                response_data=response_data,
            )
        )

        return Message(
            message_role="assistant",
            message_content=message_content,
            response_data=response_data,
            agent_id=message_request.agent_id,
        )

注目すべき点が 2 つあります。

  • @discoverable_agent("my_agent_app_echo"):この 1 つのデコレーターだけで、クラスが agent_type として登録されます。レジストリの編集もスキーマの変更も不要です。REST API は agent_type をレジストリに対して動的に検証します。
  • AgentUtils は DI コンテナによってコンストラクター経由で注入されます。さらに依存関係が必要な場合は extra_deps=("my_provider",) で宣言し、対応するプロバイダーを core/container.py に追加します(開発者ガイドを参照)。

3. 実行する前にテストする

生成されたプロジェクトの単体テストは、インフラを一切使わずにアプリケーション全体を起動します。

uv lock && uv sync --group dev --group test
make test_unit

統合テスト版も用意されています。make test_integration は testcontainers を使って実際の Postgres、Redis、Vault のコンテナを起動します(Docker が必要です)。

4. アプリを実行する

docker compose up --build -d
curl http://localhost:18000/status/liveness

スタックは、アプリ(ポート 18000)、pgvector 付きの PostgreSQL(3 つのデータベース:リレーショナル、ベクトル、LangGraph のチェックポイント)、Pub/Sub によるステータス更新用の Redis、シークレット管理用の Vault で構成されています。インタラクティブな OpenAPI ドキュメントは http://localhost:18000/docs で確認できます。

生成されたプロジェクトでは認証が無効になっています(auth.enabled: false)。有効にすると、すべての リクエストに Bearer トークンが必要になります。Keycloak による認証を参照してください。

5. REST でエージェントと対話する

エージェントは実装のインスタンスであり、API を通じて作成・設定します。 1 つ作成してみましょう。

curl -s -X POST http://localhost:18000/agents/create \
  -H "Content-Type: application/json" \
  -d '{"agent_name": "my-first-agent", "agent_type": "my_agent_app_echo"}' | jq

レスポンスから id をコピーし、メッセージを送信します。

curl -s -X POST http://localhost:18000/messages/post \
  -H "Content-Type: application/json" \
  -d '{
        "agent_id": "<agent_id>",
        "message_role": "human",
        "message_content": "Hello, framework!"
      }' | jq

応答は同期的に返ってきます。

{
  "message_role": "assistant",
  "message_content": "Echo: Hello, framework!",
  "agent_id": "<agent_id>",
  "id": "…"
}

この往復で、スタック全体が動作しました。REST リクエスト → レジストリの検索 → DI コンテナ → あなたのエージェント → メッセージの永続化(応答も保存されます。 POST /messages/list で確認してください)。全エンドポイントの一覧は REST API リファレンスにあります。

6. トレースを確認する

Agent-Lab のオブザーバビリティは、純粋な OpenTelemetry です。環境変数 OTEL_EXPORTER_OTLP_ENDPOINT が設定されていると、アプリは OTLP のトレース/メトリクス/ログをエクスポートします。設定されていない場合はトレースが無効になるだけで、どちらの場合もコードの変更は不要です。

(フレームワークのリポジトリから)同梱の Grafana スタックを起動し、アプリの送信先をそのコレクターに向けます。

# In the agent-lab framework repo — collector on :4318, Grafana UI on :3000
docker compose -f compose-grafana.yml up --build

# Back in your project — restart the app with the endpoint set
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 docker compose up --build -d

もう一度メッセージを送信してから、http://localhost:3000 で Grafana を開き(admin/admin)、Agent-Lab ダッシュボードを確認してください。HTTP スパン、SQL クエリ、そして LLM を使うエージェントの場合はトークン数を含むすべてのモデル呼び出しが表示されます。ホスト型の LLM オブザーバビリティプラットフォームを使いたい場合は、代わりに LANGFUSE_HOST/LANGFUSE_PUBLIC_KEY/LANGFUSE_SECRET_KEY(または LANGWATCH_ENDPOINT/ LANGWATCH_API_KEY)を設定します。詳しくはオブザーバビリティガイドを参照してください。

7. MCP クライアントから使う

生成されたプロジェクトには、すでに MCP ツール(my_agent_app/mcp/tools.py)が同梱されており、フレームワークのエージェント検出、履歴、メッセージングの各ツールとともに /mcp で公開されています。 MCP Inspector で試してみましょう。

npx @modelcontextprotocol/inspector

http://localhost:18000/mcp(Streamable HTTP)に接続し、ツールの一覧を表示して、 my_agent_app_hello_tool を呼び出します。同じサーバーは Claude Desktop やあらゆる MCP クライアントでも動作します。MCP サーバーガイドを参照してください。


次のステップ

ページ
🏗️ 本格的な(LLM を使う)エージェントを構築する 開発者ガイド — エージェントワークフローの構築
⚙️ データベース、認証、シークレットを設定する 設定リファレンス
🌐 全エンドポイントの一覧 REST API リファレンス
🧪 LLM ジャッジでエージェントの振る舞いを評価する テストとシミュレーション
🚀 リリースする デプロイガイド