> ## 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로 구축한 에이전트를 자동으로 트레이스하며, 각 에이전트 호출, 하위 에이전트 핸드오프, 모델 Call, 도구 Call을 모두 기록합니다. Agent Lens는 캡처한 데이터를 프로젝트의 **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로 구축한 멀티턴 리서치 에이전트를 실행하여, 세션 전반에 걸친 모든 에이전트 호출, 모델 Call, 도구 Call을 Agent Lens로 캡처하는 방법을 설명합니다.

    <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`)와 통합되어 에이전트 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-agent-lens-in-your-code">
  코드에서 Agent Lens 초기화하기
</h3>

<Tabs>
  <Tab title="Python">
    프로젝트에 `weave.init`을 추가하고 Forge 팀 이름과 프로젝트 이름을 지정한 다음, 평소와 같은 방식으로 에이전트를 구축하세요. 다음 코드는 `gemini-3.6-flash`와 `wikipedia_search` 도구를 사용하는 `research_assistant` 에이전트를 생성하고, 하나의 ADK 세션에서 세 가지 질문을 실행합니다. 이 과정에서 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())
    ```

    이 예시는 하나의 ADK 세션에서 세 개의 턴을 실행합니다. 처음 두 턴은 Wikipedia 조회를 트리거하고, 세 번째 턴은 도구 Call 없이 이전 대화 컨텍스트를 활용해 요약을 생성합니다.

    모든 턴은 동일한 `session_id`를 전달합니다. ADK가 이 세션을 기반으로 `gen_ai.conversation.id`를 설정하므로, Agent Lens는 **Conversations** 탭에서 세 턴을 하나의 대화로 표시합니다. 반면 턴마다 세션을 새로 생성하면 각 턴이 별도의 대화로 표시됩니다.
  </Tab>

  <Tab title="TypeScript">
    Weave는 `WeaveAdkPlugin`을 통해 `@google/adk` 러너를 트레이스합니다. 이 플러그인은 러너의 `plugins` 배열에 직접 등록합니다. 플러그인을 명시적으로 등록하면 ESM 프로젝트와 CommonJS 프로젝트에서 동일하게 작동하므로 모듈 로더 훅을 따로 설정할 필요가 없습니다.

    다음 코드는 `wikipedia_search` 도구를 사용하는 `research_assistant` 에이전트를 생성한 후, 하나의 ADK 세션에서 세 가지 질문을 실행합니다. 그동안 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);
    ```

    이 예시는 하나의 ADK 세션에서 세 개의 턴을 실행합니다. 처음 두 턴은 Wikipedia 조회를 트리거하고, 세 번째 턴은 도구 Call 없이 이전 대화 컨텍스트를 바탕으로 요약을 생성합니다.

    모든 턴에 동일한 `sessionId`를 전달합니다. ADK가 이 세션을 기반으로 `gen_ai.conversation.id`를 설정하므로, Agent Lens는 **Conversations** 탭에서 세 턴을 하나의 대화로 표시합니다. 반면 턴마다 세션을 새로 생성하면 각 턴이 별도의 대화로 표시됩니다.
  </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).
