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

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

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

<Note>
  This integration uses the Weights & Biases Weave SDK (`weave`), because the CoreWeave Forge SDK doesn't support this framework yet. Traces you send with Weave appear in Agent Lens, because both products share the same trace data.
</Note>

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

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

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

    <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-agent-lens-in-your-code">
  コードで Agent Lens を初期化する
</h3>

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

    ```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]")

    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-3.6-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 つ目のターンではツール呼び出しを行わずに、それまでの会話のコンテキストを使用して要約を生成します。

    すべてのターンで同じ `session_id` を渡します。ADK はそのセッションに基づいて `gen_ai.conversation.id` を設定するため、Agent Lens は **Conversations** タブで 3 つのターンを 1 つの会話としてレンダリングします。ターンごとにセッションを作成した場合は、各ターンが個別の会話として表示されます。
  </Tab>

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

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

    ```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]");

      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-3.6-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 つ目のターンではツール呼び出しを行わずに、それまでの会話のコンテキストを使用して要約を生成します。

    すべてのターンで同じ `sessionId` を渡します。ADK はこのセッションに基づいて `gen_ai.conversation.id` を設定するため、Agent Lens は 3 つのターンを **Conversations** タブに 1 つの会話としてレンダリングします。ターンごとにセッションを作成した場合は、各ターンがそれぞれ別の会話として表示されます。
  </Tab>
</Tabs>

### View your traces in Agent Lens

After the script runs, `weave.init()` prints a link to your project in Weave. The same traces appear in Agent Lens, because both products share the same trace data. To view them in Agent Lens:

1. Navigate to [CoreWeave Forge](https://forge.coreweave.com) and select **Agent Lens** from the product menu.
2. Select your project.
3. In the Agent Lens side menu, select **Conversations**, and then select your conversation.

Each turn renders as an `invoke_agent` span with nested `chat` and `execute_tool` spans. Each span shows its input, model, output, token usage, and tool results.

For more information, see [View agent activity](/products/agent-lens/conversations/view-activity).
