> ## 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 拡張機能

> Pi のエージェント型セッション、LLM Call、ツール実行を Weave でトレースします。

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/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 モジュールシステムが必要です。project の `package.json` で `"type": "module"` を使用するか、TypeScript を ESM 形式でコンパイルしてください。CommonJS の project ではエラーが発生します。ESM project のセットアップの詳細については、[TypeScript SDK インテグレーション](/ja/products/wandb/weave/guides/integrations/js#set-up-an-esm-project)を参照してください。
</Note>

<h2 id="install-packages">
  パッケージのインストール
</h2>

Weave、Pi、Node のタイプ定義をローカル project の依存関係としてインストールします：

```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`) という、エージェントのライフサイクル全体をトレースします。`SessionManager.inMemory()` はセッション ID を自動的に生成します。

```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() が作成したすべてのスパンは
  //    ここに自動的にエクスポートされます。
  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 アダプターが
  //    会話のルートスパンを作成し、会話 ID を取得するようにします。
  await session.bindExtensions({});

  // 5. アシスタントの出力を 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 は、アプリケーションのすべての run について、Pi のセッション、LLM Call、およびツール実行を取得します。

<h3 id="next-steps">
  次のステップ
</h3>

この例をマルチターンの会話にするには、プロンプトを追加します。Weave は `session.prompt()` への各 Call を個別の `invoke_agent` スパンとしてトレースし、それらはすべて単一のルートスパンの下にネストされます。エージェントはプロンプト間でコンテキストを自動的に保持します。

コードを実行すると、**Agents** タブに、ネストされた LLM Call、ツール実行、トークン使用量、コストを含むマルチターンのタイムライン全体が表示されます。


## Related topics

- [エージェント統合を選択](/ja/products/wandb/weave/agent-integration-quickstart.md)
