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

# Pi 확장

> Weave에서 Pi의 에이전트형 세션, LLM Call, 도구 실행을 트레이스하세요.

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="/ko/products/agent-lens/integrations/pi" />

[Pi](https://pi.dev/)는 터미널 기반 코딩 에이전트입니다. Weave는 [GenAI 시맨틱 규칙](https://opentelemetry.io/docs/specs/semconv/gen-ai/)을 준수하는 `createOtelExtension` 인테그레이션을 통해 Pi 세션, LLM Call, 도구 실행을 자동으로 트레이스합니다. 이 페이지에서는 Pi 애플리케이션에서 Weave 트레이싱을 활성화하는 방법을 설명합니다. 트레이싱을 활성화하면 에이전트 동작을 관찰하고, run을 디버그하고, 토큰 사용량과 비용을 분석할 수 있습니다.

<Warning>
  이 인테그레이션은 Pi 세션 데이터를 Weave로 전송합니다. 이 데이터에는 사용자 프롬프트, 모델 응답, 도구 입력 및 출력, Pi 도구가 읽은 파일 내용, 셸 명령어 및 출력, 가져온 URL 및 페이지 콘텐츠가 포함될 수 있습니다.

  이 인테그레이션은 PII 제거나 민감한 데이터 마스킹 기능을 제공하지 않습니다. 보안 또는 규정 준수 요구 사항으로 인해 이 데이터를 Weave로 전송할 수 없다면 Pi 애플리케이션에서 Weave 트레이싱을 활성화하지 마세요.
</Warning>

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

* [Node.js](https://nodejs.org/) (v18 이상).
* CoreWeave Forge 계정과 `WANDB_API_KEY` 환경 변수로 설정한 [API 키](https://forge.coreweave.com/settings#apikeys).

<Note>
  Pi는 TypeScript 및 Node.js 프레임워크이며 Python 버전은 제공되지 않습니다. Pi를 사용하려면 ESM 모듈 시스템이 필요합니다. 프로젝트의 `package.json`에 `"type": "module"`을 지정하거나 TypeScript를 ESM 형식으로 컴파일해야 합니다. CommonJS 프로젝트에서는 오류가 발생합니다. ESM 프로젝트 설정에 대한 자세한 내용은 [TypeScript SDK 인테그레이션](/ko/products/wandb/weave/guides/integrations/js#set-up-an-esm-project)을 참조하세요.
</Note>

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

Weave, Pi 및 Node 타입 정의를 로컬 프로젝트 의존성으로 설치하세요:

```bash lines theme={"system"}
npm install weave @earendil-works/pi-coding-agent
npm install --save-dev @types/node tsx typescript
```

<h2 id="trace-a-pi-prompt-and-response">
  Pi 프롬프트와 응답 트레이스하기
</h2>

다음 예시는 Pi 프롬프트 하나와 그 응답을 트레이스하는 데 필요한 최소한의 설정을 보여 줍니다. 에이전트 세션을 생성하기 전에 `weave.init()`을 호출한 다음, `createOtelExtension()`을 확장 팩토리로 전달하세요. Weave는 대화, 각 프롬프트-응답 주기(`invoke_agent`), 개별 LLM Call(`chat`), 도구 실행(`execute_tool`)을 포함하여 에이전트의 전체 라이프사이클을 트레이스합니다. 세션 ID는 `SessionManager.inMemory()`가 자동으로 생성합니다.

```typescript lines twoslash theme={"system"}
// @noErrors
import {init, createOtelExtension} from 'weave';

import {
  createAgentSession,
  DefaultResourceLoader,
  SessionManager,
  getAgentDir,
} from '@earendil-works/pi-coding-agent';

async function main() {
  // 1. Weave를 초기화합니다. Weave 프로젝트를 가리키는 OTEL TracerProvider를
  //    설정합니다. createOtelExtension()으로 생성된 모든 span은
  //    이 프로젝트로 자동으로 내보내집니다.
  await init('[YOUR-TEAM]/[YOUR-PROJECT]');

  // 2. 리소스 로더를 생성하고 Weave OTEL 확장을 주입합니다.
  //    리소스 로더는 에이전트 활동 트레이싱에 사용되는 Pi 런타임 환경과
  //    확장 라이프사이클을 제공합니다.
  const resourceLoader = new DefaultResourceLoader({
    cwd: process.cwd(),
    agentDir: getAgentDir(),
    extensionFactories: [createOtelExtension({})],
  });

  await resourceLoader.reload();

  // 3. 에이전트 세션을 시작합니다
  const {session} = await createAgentSession({
    resourceLoader,
    sessionManager: SessionManager.inMemory(),
  });

  // 4. 확장을 바인딩합니다. session_start 이벤트가 트리거되어 OTEL 어댑터가
  //    루트 대화 span을 생성하고 대화 ID를 캡처합니다.
  await session.bindExtensions({});

  // 5. assistant 출력을 stdout으로 스트리밍합니다
  session.subscribe(event => {
    if (
      event.type === 'message_update' &&
      event.assistantMessageEvent.type === 'text_delta'
    ) {
      process.stdout.write(event.assistantMessageEvent.delta);
    }
  });

  // 6. 프롬프트를 보내고 전체 응답이 올 때까지 기다립니다
  await session.prompt('What files are in the current directory?');
  console.log();
}

main();
```

`[FILENAME]`을 사용 중인 TypeScript 파일 이름으로 바꾼 후 `tsx`로 스크립트를 컴파일하고 실행하세요.

```bash theme={"system"}
npx tsx [FILENAME].ts
```

코드를 실행하면 트레이스가 Weave 프로젝트의 **Agents** 탭(`https://forge.coreweave.com/wandb/[YOUR-TEAM]/[YOUR-PROJECT]/weave/agents`)에 표시됩니다. Weave는 애플리케이션을 실행할 때마다 Pi 세션, LLM Call, 도구 실행을 캡처합니다.

<h3 id="next-steps">
  다음 단계
</h3>

이 예제를 멀티턴 대화로 확장하려면 프롬프트를 더 추가하세요. Weave는 `session.prompt()`의 각 Call을 별도의 `invoke_agent` span으로 트레이스하며, 이 span들은 모두 하나의 루트 span 아래에 중첩됩니다. 에이전트는 프롬프트 간 컨텍스트를 자동으로 유지합니다.

코드를 실행하면 **Agents** 탭에서 중첩된 LLM Call, 도구 실행, 토큰 사용량, 비용을 포함한 전체 멀티턴 타임라인을 확인할 수 있습니다.


## Related topics

- [에이전트 인테그레이션 선택](/ko/products/wandb/weave/agent-integration-quickstart.md)
