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

# Google ADK

> Weave を使用して、Google の Agent Development Kit（ADK）で構築したエージェントをトレースします。

Google の Agent Development Kit (ADK) は、エージェントの構築とオーケストレーションのための、柔軟でモデル非依存のフレームワークです。Gemini 向けに最適化されていますが、ADK はあらゆるモデルをサポートしており、シンプルなタスクから複雑なマルチエージェント ワークフローまで対応します。Weave は、ADK で構築されたエージェントを自動的にトレースし、各エージェント呼び出し、サブエージェントへのハンドオフ、モデルの Call、ツール呼び出しを含むデータを取得します。Weave は、取得したデータを project の **Agents** ビューに表示します。

<div id="trace-google-adk-agents-with-weave">
  ## Weave で Google ADK エージェントをトレースする
</div>

<Tabs>
  <Tab title="Python">
    Weave SDK は [Google ADK for Python](https://google.github.io/adk-docs/) を自動的にパッチするため、最小限の設定で ADK エージェントのトレースを取得できます。このガイドでは、Weave を初期化したうえで、Google ADK で構築したマルチターンのリサーチエージェントを実行し、セッション全体にわたるすべてのエージェント呼び出し、モデルの Call、ツール呼び出しを Weave で取得する方法を説明します。

    ### 前提条件

    * `WANDB_API_KEY` 環境変数として設定された W\&B アカウントと [APIキー](https://wandb.ai/authorize)。
    * Gemini 用の [Google APIキー](https://aistudio.google.com/apikey)。
    * Python 3.10+。
  </Tab>

  <Tab title="TypeScript">
    Weave は [Google ADK for Node.js](https://google.github.io/adk-docs/) (`@google/adk`) と連携し、エージェントの実行を自動的にトレースします。

    ### 前提条件

    * `WANDB_API_KEY` 環境変数として設定された W\&B アカウントと [APIキー](https://wandb.ai/authorize)。
    * `GEMINI_API_KEY` または `GOOGLE_GENAI_API_KEY` 環境変数として設定された [Google APIキー](https://aistudio.google.com/apikey)。
    * Node.js 18+。
    * `@google/adk` バージョン `1.0.0` 以降。
  </Tab>
</Tabs>

<div id="install-packages">
  ### パッケージをインストールする
</div>

開発用の環境に、次のパッケージをインストールします。これらのパッケージに、Weave SDK、Google ADK フレームワーク、およびサンプルツールで使用する HTTP クライアントが含まれます。

<CodeGroup>
  ```bash Python theme={null}
  pip install weave google-adk requests
  ```

  ```bash TypeScript theme={null}
  npm install weave @google/adk zod
  ```
</CodeGroup>

<div id="initialize-weave-in-your-code">
  ### コードで Weave を初期化する
</div>

<Tabs>
  <Tab title="Python">
    `weave.init` をprojectに追加し、W\&B のチーム名とproject名を指定してから、通常どおりエージェントを構築します。次のコードでは、`gemini-2.5-flash` と `wikipedia_search` ツールを使用する `research_assistant` エージェントを作成し、Weave でトレースを取得しながら、1 つの ADK セッション内で 3 つの質問を実行します。

    ```python lines highlight="8" theme={null}
    import asyncio
    import requests
    import weave
    from google.adk.agents import Agent
    from google.adk.runners import InMemoryRunner
    from google.genai import types

    weave.init("<your-team>/<your-project-name>")

    def wikipedia_search(query: str) -> dict:
        """Search Wikipedia for a topic and return its title and intro paragraph.

        Args:
            query: The topic to search for.

        Returns:
            A dictionary with the article title and intro extract.
        """
        r = requests.get(
            "https://en.wikipedia.org/w/api.php",
            params={
                "action": "query", "generator": "search", "gsrsearch": query, "gsrlimit": 1,
                "prop": "extracts", "exintro": True, "explaintext": True, "format": "json",
            },
            headers={"User-Agent": "weave-demo"},
        ).json()
        page = next(iter(r["query"]["pages"].values()))
        return {"title": page["title"], "extract": page["extract"]}

    agent = Agent(
        name="research_assistant",
        model="gemini-2.5-flash",
        instruction=(
            "You are a research assistant. Use the wikipedia_search tool to look up "
            "topics when needed, and cite the article titles you used."
        ),
        tools=[wikipedia_search],
    )

    async def main():
        runner = InMemoryRunner(agent=agent, app_name="research-app")
        session = await runner.session_service.create_session(
            app_name="research-app", user_id="user-1"
        )

        questions = [
            "Who founded Anthropic?",
            "What is Claude (the AI assistant)?",
            "Summarize what we discussed in one sentence.",
        ]

        for question in questions:
            print(f"USER: {question}")
            async for event in runner.run_async(
                user_id="user-1",
                session_id=session.id,
                new_message=types.Content(
                    role="user",
                    parts=[types.Part(text=question)],
                ),
            ):
                if event.is_final_response() and event.content:
                    print(f"AGENT: {event.content.parts[0].text}\n")

    asyncio.run(main())
    ```

    この例では、1 つの ADK セッション内で 3 つのターンを実行します。最初の 2 つのターンでは Wikipedia のルックアップがトリガーされ、3 つ目のターンではそれまでの会話コンテキストを使用して、ツール呼び出しなしで要約を生成します。
  </Tab>

  <Tab title="TypeScript">
    Weave は `WeaveAdkPlugin` を通じて `@google/adk` のランナーをトレースします。このプラグインは、ランナーの `plugins` 配列に直接登録します。プラグインを明示的に登録する方法は、ESM プロジェクトでも CommonJS プロジェクトでも同様に機能するため、モジュールローダーのフックを設定する必要はありません。

    次のコードでは、`wikipedia_search` ツールを持つ `research_assistant` エージェントを作成し、Weave でトレースを取得しながら、1 つの ADK セッション内で 3 つの質問を実行します。

    ```typescript lines highlight="35" theme={null}
    import * as weave from "weave";
    import { FunctionTool, Gemini, InMemoryRunner, LlmAgent } from "@google/adk";
    import { WeaveAdkPlugin } from "weave";
    import { z } from "zod";

    const GEMINI_API_KEY = process.env.GEMINI_API_KEY

    const wikipediaSearchTool = new FunctionTool({
      name: "wikipedia_search",
      description: "Search Wikipedia for a topic and return its title and intro paragraph.",
      parameters: z.object({
        query: z.string().describe("The topic to search for"),
      }),
      execute: async ({ query }) => {
        const url = new URL("https://en.wikipedia.org/w/api.php");
        url.search = new URLSearchParams({
          action: "query",
          generator: "search",
          gsrsearch: query,
          gsrlimit: "1",
          prop: "extracts",
          exintro: "true",
          explaintext: "true",
          format: "json",
        }).toString();

        const response = await fetch(url, { headers: { "User-Agent": "weave-demo" } });
        const data = await response.json();
        const page = Object.values(data.query.pages)[0] as { title: string; extract: string };
        return { title: page.title, extract: page.extract };
      },
    });

    async function main() {
      await weave.init("<your-team>/<your-project-name>");

      const agent = new LlmAgent({
        name: "research_assistant",
        description: "Answers research questions using Wikipedia.",
        instruction:
          "You are a research assistant. Use the wikipedia_search tool to look up " +
          "topics when needed, and cite the article titles you used.",
        model: new Gemini({ model: "gemini-2.5-flash", apiKey: GEMINI_API_KEY }),
        tools: [wikipediaSearchTool],
      });

      const APP_NAME = "weave-adk-example";
      const USER_ID = "example-user";

      const runner = new InMemoryRunner({
        agent,
        appName: APP_NAME,
        plugins: [new WeaveAdkPlugin()],
      });
      const session = await runner.sessionService.createSession({
        appName: APP_NAME,
        userId: USER_ID,
      });

      const questions = [
        "Who founded Anthropic?",
        "What is Claude (the AI assistant)?",
        "Summarize what we discussed in one sentence.",
      ];

      for (const question of questions) {
        console.log(`USER: ${question}`);
        for await (const event of runner.runAsync({
          userId: USER_ID,
          sessionId: session.id,
          newMessage: {
            role: "user",
            parts: [{ text: question }],
          },
        })) {
          const text = event.content?.parts
            ?.map(part => part.text)
            .filter(Boolean)
            .join("");
          if (text) {
            console.log(`AGENT: ${text}\n`);
          }
        }
      }

      await weave.flushOTel();
    }

    main().catch(console.error);
    ```

    この例では、1 つの ADK セッション内で 3 つのターンを実行します。最初の 2 つのターンでは Wikipedia のルックアップがトリガーされ、3 つ目のターンではそれまでの会話コンテキストを使用して、ツール呼び出しなしで要約を生成します。
  </Tab>
</Tabs>

<div id="see-your-agent-traces-in-the-agents-view">
  ### Agents ビューでエージェントのトレースを確認する
</div>

スクリプトの実行後、`weave.init()` によって project へのリンクが出力されます。**Agents** ビューを開くと、次の内容を確認できます。

* 会話のターンを含むセッション。
* 各ターンは `invoke_agent` span として表示され、その子要素として `chat` と `execute_tool` がネストされています。
* 各ステップでの入力全体、モデル、出力、トークン使用量、ツールの実行結果。

Weave で Agents データを表示する方法の詳細については、[エージェントのアクティビティを表示する](/ja/weave/guides/tracking/view-agent-activity)を参照してください。
