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

> CoreWeave Forge SDK를 사용해 Google Gen AI SDK에서 Gemini로 보내는 Call을 Agent Lens에서 트레이싱합니다.

CoreWeave Forge SDK는 Python용(`google-genai`) 및 Node.js용(`@google/genai`) Google Gen AI SDK로 수행하는 Call을 자동으로 트레이싱합니다. 트레이싱을 초기화하면 대화 안에서 수행하는 각 Call이 Agent Lens에 LLM span으로 기록됩니다. 이때 메시지, 시스템 지침, 도구, 미디어, 요청 설정, 응답 메타데이터와 함께 캐시된 입력 토큰 및 사고(thinking) 토큰을 포함한 토큰 사용량도 기록됩니다. Google Gen AI SDK를 Call하는 방식은 바꿀 필요가 없습니다.

이 인테그레이션은 콘텐츠 생성(스트리밍 포함), 채팅 헬퍼, Imagen 이미지 생성을 트레이싱합니다. Vertex AI 클라이언트를 통한 Call은 `vertex_ai`로, Gemini Developer API Call은 `gemini`로 분류됩니다.

<Note>
  Google의 Agent Development Kit(ADK)로 빌드한 에이전트를 트레이싱하려면 [Google ADK](/ko/products/agent-lens/integrations/google-adk)를 참조하세요.
</Note>

<h2 id="prerequisites">
  사전 요구 사항
</h2>

* CoreWeave Forge 계정 및 `WANDB_API_KEY` 환경 변수로 설정한 [API 키](https://forge.coreweave.com/settings#apikeys)
* `GEMINI_API_KEY` 환경 변수로 설정한 [Gemini API 키](https://aistudio.google.com/apikey)
* Python: Python 3.10 이상 및 `google-genai` 1.0.0\~1.23.0
* TypeScript: Node.js 18.19 이상(또는 20.6 이상) 및 `@google/genai` 0.2.0 이상

<h2 id="install-packages">
  패키지 설치
</h2>

<CodeGroup>
  ```bash Python theme={"system"}
  pip install "coreweave[google-genai]"
  ```

  ```bash TypeScript theme={"system"}
  npm install @coreweave/forge-sdk @google/genai
  ```
</CodeGroup>

<h2 id="trace-google-gen-ai-conversations">
  Google Gen AI 대화 트레이싱
</h2>

Forge 팀 이름과 프로젝트 이름을 지정해 `tracing.init()`을 호출하세요. Python에서는 Google Gen AI SDK를 이 호출 전에 임포트하든 후에 임포트하든 `tracing.init()`이 SDK를 패치합니다. TypeScript에서는 TypeScript 탭에 나와 있는 계측 플래그를 사용해 Node를 시작하세요.

Agent Lens에는 대화 안에서 실행된 Call만 표시됩니다. 대화 밖에서 실행된 Call에는 대화 ID가 없으므로 Agent Lens에 나타나지 않습니다. 에이전트 세션마다 대화를 하나씩 생성하고, 사용자 메시지마다 턴을 시작하세요. 모든 턴이 대화의 ID를 공유하므로 Agent Lens는 이 턴들을 하나의 대화로 묶으며, 각 Call은 자신이 실행된 턴의 LLM span이 됩니다.

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    from google import genai
    from coreweave.forge.agentlens import tracing

    tracing.init("[YOUR-TEAM]/[YOUR-PROJECT]")
    client = genai.Client()

    questions = [
        "What is inference latency?",
        "How does batching affect it?",
        "Summarize what we discussed in one sentence.",
    ]

    chat = client.chats.create(model="gemini-flash-latest")
    with tracing.Conversation(agent_name="support-agent") as conversation:
        for question in questions:
            with conversation.start_turn(user_message=question):
                response = chat.send_message(question)
                print(response.text)

    tracing.shutdown()
    ```
  </Tab>

  <Tab title="TypeScript">
    각 에이전트 실행을 `tracing.runIsolated()`로 래핑하여, 해당 실행의 대화와 턴이 동시에 진행되는 다른 실행과 섞이지 않도록 하세요.

    ```typescript lines title="app.mjs" theme={"system"}
    import {GoogleGenAI} from '@google/genai';
    import {tracing} from '@coreweave/forge-sdk/agentlens';

    await tracing.init('[YOUR-TEAM]/[YOUR-PROJECT]');
    const google = new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY});

    const questions = [
      'What is inference latency?',
      'How does batching affect it?',
      'Summarize what we discussed in one sentence.',
    ];

    await tracing.runIsolated(async () => {
      const conversation = tracing.startConversation({agentName: 'support-agent'});
      const chat = google.chats.create({model: 'gemini-flash-latest'});
      try {
        for (const question of questions) {
          const turn = conversation.startTurn({userMessage: question});
          try {
            const response = await chat.sendMessage({message: question});
            console.log(response.text);
          } finally {
            turn.end();
          }
        }
      } finally {
        conversation.end();
      }
    });

    await tracing.shutdown();
    ```

    계측 플래그를 지정해 스크립트를 실행하세요. 이 플래그는 코드보다 먼저 Forge 계측을 로드하므로, 코드에서 Google Gen AI SDK를 임포트하는 시점에 SDK가 패치됩니다.

    ```bash theme={"system"}
    node --import=@coreweave/forge-sdk/instrument app.mjs
    ```

    번들러가 의존성을 하나의 파일로 묶는 경우처럼 플래그를 사용할 수 없다면 클라이언트를 직접 래핑하세요.

    ```typescript theme={"system"}
    import {integrations} from '@coreweave/forge-sdk/agentlens';

    const google = integrations.wrapGoogleGenAI(
      new GoogleGenAI({apiKey: process.env.GEMINI_API_KEY})
    );
    ```

    플래그 없이 실행하면 `tracing.init()`이 이에 대한 경고를 한 번 출력합니다. 클라이언트를 래핑했다면 이 경고는 무시해도 됩니다.
  </Tab>
</Tabs>

요청마다 턴을 하나씩 처리하는 웹 앱처럼 나중에 기존 대화에 턴을 추가하려면, 대화를 생성할 때마다 동일한 `conversation_id`(Python) 또는 `conversationId`(TypeScript)를 전달하세요.

대화, 턴 및 기타 span 유형에 대한 자세한 내용은 [에이전트 트레이싱](/ko/products/agent-lens/tracing/instrument)을 참조하세요.

<h2 id="turn-off-automatic-patching">
  자동 패치 끄기
</h2>

Python에서는 `tracing.init()`에 `autopatch_integrations=False`를 전달하세요. 그런 다음 `tracing.integrations.patch_google_genai()`와 `tracing.integrations.unpatch_google_genai()`로 Google Gen AI SDK를 직접 패치하거나 패치를 해제할 수 있습니다.

TypeScript에서는 `--import=@coreweave/forge-sdk/instrument` 플래그 없이 실행한 다음, 트레이스할 클라이언트만 `integrations.wrapGoogleGenAI()`로 래핑하세요.

<h2 id="view-your-traces">
  트레이스 보기
</h2>

[CoreWeave Forge](https://forge.coreweave.com)의 제품 메뉴에서 Agent Lens를 선택하고, 사이드 메뉴 상단의 프로젝트 선택기에서 프로젝트를 선택한 후 **Conversations**를 선택하세요. 자세한 내용은 [에이전트 활동 보기](/ko/products/agent-lens/conversations/view-activity)를 참조하세요.
