> ## Documentation Index
> Fetch the complete documentation index at: https://onbridge.jp/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 初めてのLiveKit Agent

> LiveKit Agents フレームワークを使用した音声AIエージェントの実装

## 作成するエージェント

シンプルなパイプライン型のエージェントを作成します。

## プロジェクトを初期化します

プロジェクト用のフォルダを作成し初期化します。

<CodeGroup>
  ```bash NodeJS theme={null}
  mkdir onbridge-agent
  cd onbridge-agent
  pnpm init --init-type module
  pnpm add -D typescript tsx
  pnpm exec tsc --init
  ```

  ```bash Python theme={null}
  uv init onbridge-agent --bare
  cd onbridge-agent
  ```
</CodeGroup>

## 環境変数の設定

LiveKit Cloud, OpenAI からAPIキーを取得し、環境変数として設定します。以下の内容で`.env.local`ファイルを作成してください：

```env .env.local theme={null}
# LiveKit Cloud
LIVEKIT_API_KEY=<your API Key>
LIVEKIT_API_SECRET=<your API Secret>
LIVEKIT_URL=<your LiveKit server URL>
LIVEKIT_SIP_URI=<your SIP URI>

# OpenAI
OPENAI_API_KEY=<Your OpenAI API Key>
```

### LiveKit Cloud

API Key の取得

1. [LiveKit Cloud](https://cloud.livekit.io/) にアクセス
2. 「Sign Up」または「Get Started」をクリック
3. メールアドレスとパスワードでアカウントを作成
4. ログイン後、ダッシュボードに移動
5. 「Create Project」をクリック
6. プロジェクト名を「onBridge Example」として作成
7. 左側メニューの「Settings」→「API Keys」を開く
8. 「Create Key」ボタンをクリック
9. キー名を「onBridge Example Key」として作成
10. "Environment variables" をコピーして、.env.local に設定

```
LIVEKIT_URL=wss://your-project.livekit.cloud
LIVEKIT_API_KEY=your_api_key_here
LIVEKIT_API_SECRET=your_api_secret_here
```

SIP URI の取得

1. 左側メニューの「Settings」→「Project」を開く
2. 「SIP URI」の値をメモ
3. 以下を .env.localに設定

```
LIVEKIT_SIP_URI=sip:your-project.livekit.cloud
```

### OpenAI

1. [OpenAI Platform](https://platform.openai.com/) にアクセス
2. 「Sign up」をクリック
3. メールアドレスとパスワードでアカウントを作成
4. 必要に応じて電話番号認証を完了
5. ログイン後、ダッシュボードに移動
6. [プロジェクト作成ページ](https://platform.openai.com/settings/organization/projects) にアクセス
7. 「Create new project」をクリック
8. プロジェクト名を「onBridge Example」として作成
9. プロジェクトの設定ページに移動
10. 左側メニューの「API Keys」をクリック
11. 「Create new secret key」ボタンをクリック
12. キー名を「onBridge Example Key」として作成
13. 音声モデルを利用するために、以下の権限を設定：

* **Permissions**: All または Restricted
* **Models**: チェック済み
* **Model capabilities**: チェック済み

14. 作成されたAPI Key をコピーして、.env.local に追記

```
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

## エージェントを実装

シンプルなパイプライン型のエージェントを作成します。 以下のコードを`agent.ts`（Node.js）または`agent.py`（Python）として保存してください：

<CodeGroup>
  ```typescript agent.ts theme={null}
  import {
      type JobContext,
      type JobProcess,
      WorkerOptions,
      cli,
      defineAgent,
      voice,
      stt as sttCore,
  } from '@livekit/agents';
  import * as livekit from '@livekit/agents-plugin-livekit';
  import * as openai from '@livekit/agents-plugin-openai';
  import * as silero from '@livekit/agents-plugin-silero';
  import { BackgroundVoiceCancellation } from '@livekit/noise-cancellation-node';
  import { fileURLToPath } from 'node:url';
  import dotenv from 'dotenv';

  dotenv.config({ path: '.env.local' });

  export default defineAgent({
      prewarm: async (proc: JobProcess) => {
          proc.userData.vad = await silero.VAD.load();
      },
      entry: async (ctx: JobContext) => {
          const vad = ctx.proc.userData.vad! as silero.VAD;

          // Non-streaming STT wrapped for chunked (VAD) processing
          const stt = new sttCore.StreamAdapter(
              new openai.STT({ model: 'gpt-4o-mini-transcribe' }),
              vad
          );


          const assistant = new voice.Agent({
              instructions: 'You are a helpful voice AI assistant.',
          });

          const session = new voice.AgentSession({
              vad,
              stt: stt,
              llm: new openai.LLM({ model: 'gpt-4o-mini' }),
              tts: new openai.TTS({
                  model: 'tts-1',
                  voice: 'alloy'
              }),
              turnDetection: new livekit.turnDetector.MultilingualModel(),
          });

          await session.start({
              agent: assistant,
              room: ctx.room,
              inputOptions: {
                  // For telephony applications, use `TelephonyBackgroundVoiceCancellation` for best results
                  noiseCancellation: BackgroundVoiceCancellation(),
              },
          });

          await ctx.connect();

          const handle = session.generateReply({
              instructions: 'Greet the user and offer your assistance.',
          });
      },
  });

  cli.runApp(new WorkerOptions({ agent: fileURLToPath(import.meta.url) }));
  ```
</CodeGroup>

## 必要なモデルをダウンロードする

turn-detector、silero、noise-cancellation プラグインを使用するために、必要なモデルファイルをダウンロードします：

<CodeGroup>
  ```bash Node.JS theme={null}
  pnpm pkg set "scripts.download-files=tsc && node agent.js download-files"
  pnpm download-files
  ```

  ```bash Python theme={null}
  uv run agent.py download-files
  uv run agent.py console
  ```
</CodeGroup>

### 最終的なファイル構成

<CodeGroup>
  ```txt NodeJS theme={null}
  onbridge-agent/
  ├── agent.ts          # メインのエージェントファイル
  ├── package.json      # 依存関係の定義
  ├── tsconfig.json     # TypeScript設定
  └── .env.local        # 環境変数
  ```

  ```txt Python theme={null}
  onbridge-agent/
  ├── agent.ts          # メインのエージェントファイル
  ├── package.json      # 依存関係の定義
  ├── tsconfig.json     # TypeScript設定
  └── .env.local        # 環境変数
  ```
</CodeGroup>

## 音声AIエージェントを起動してプレイグラウンドに接続

エージェントを開発モードで実行します：

<CodeGroup>
  ```bash NodeJS theme={null}
  pnpm pkg set "scripts.dev=tsx agent.ts dev"
  pnpm dev
  ```

  ```bash Python theme={null}
  uv run agent.py dev
  ```
</CodeGroup>

### Playgroud より接続する

1. LiveKit Agent Playground ( [https://agents-playground.livekit.io/](https://agents-playground.livekit.io/) )にアクセス
2. onBridge Example プロジェクトを選択
3. ローカルで起動したエージェントと接続され、会話ができる
