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

# Google ADK

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

export const AgentLensBanner = ({href}) => <Tip>
    <strong>This workflow is also available in CoreWeave Agent Lens.</strong> Agent Lens is the Forge experience built for tracing, monitoring, and analyzing AI agents, with automated insights into agent failures and user intents. It uses the same trace data as Weights & Biases Weave, so the traces you already send appear there with nothing to migrate.{' '}
    <a href={href || '/products/agent-lens'}>{href ? 'See how to do this in Agent Lens' : 'Learn about Agent Lens'}</a>.
  </Tip>;

<AgentLensBanner href="/ja/products/agent-lens/integrations/google-adk" />

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

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

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

    <h3 id="prerequisites">
      前提条件
    </h3>

    * CoreWeave Forge アカウントと、`WANDB_API_KEY` 環境変数に設定した [APIキー](https://forge.coreweave.com/settings#apikeys)。
    * 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`) と連携し、エージェントの run を自動的にトレースします。

    <h3 id="prerequisites-2">
      前提条件
    </h3>

    * CoreWeave Forge アカウントと、`WANDB_API_KEY` 環境変数に設定した [APIキー](https://forge.coreweave.com/settings#apikeys)。
    * `GEMINI_API_KEY` または `GOOGLE_GENAI_API_KEY` 環境変数に設定した [Google APIキー](https://aistudio.google.com/apikey)。
    * Node.js 18 以降。
    * `@google/adk` バージョン `1.0.0` 以降。
  </Tab>
</Tabs>

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

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

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

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

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

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

    ```python lines highlight="8" theme={"system"}
    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())
    ```

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

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

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

    ```typescript lines highlight="35" theme={"system"}
    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);
    ```

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

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

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

* 会話のターンを含むセッション
* `invoke_agent` スパンとしてレンダリングされた各ターン (子として `chat` と `execute_tool` がネストされます)
* 各ステップの入力、モデル、出力、トークン使用量、ツール結果の全容

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