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

# イベント

イベントは、エージェントと Cartesia プラットフォーム間の通信に使う型付きの Python オブジェクトです。エージェントはハーネス（実行環境）から **入力イベント** を受け取り、**出力イベント** を yield（生成）して会話を制御します。

<Tip>
  どのイベントがエージェントをトリガーするか、また DTMF への応答や割り込みの抑止などの動作をカスタマイズする方法については [会話ループの制御](/line/sdk/agents#controlling-the-conversational-loop) を参照してください。
</Tip>

## 入力イベント

入力イベントは、Cartesia ハーネスからエージェントが受け取るイベントです。すべての入力イベントには、完全な会話履歴を含むオプションの `history` フィールドがあります。`history` が `None` の場合、そのイベントは履歴リスト内で使用されています。`history` にリストが含まれている場合、そのイベントには完全な会話コンテキストが添付されています。

### 通話ライフサイクル

| イベント          | 説明       |
| ------------- | -------- |
| `CallStarted` | 通話が接続された |
| `CallEnded`   | 通話が終了した  |

```python theme={null}
from line.events import CallStarted, CallEnded

async def process(self, env, event):
    if isinstance(event, CallStarted):
        yield AgentSendText(text="Hello! How can I help?")
    elif isinstance(event, CallEnded):
        # Perform cleanup
        pass
```

### ユーザーターンイベント

| イベント              | 説明                                     |
| ----------------- | -------------------------------------- |
| `UserTurnStarted` | ユーザーが発話を開始（デフォルトで割り込みをトリガー）            |
| `UserTurnEnded`   | ユーザーが発話を終了（デフォルトで新しいエージェントターンをトリガー）    |
| `UserTextSent`    | ユーザーのテキスト内容（`UserTurnEnded.content` 内） |
| `UserDtmfSent`    | ユーザーが DTMF ボタンを押した                     |

```python theme={null}
from line.events import UserTurnEnded, UserTextSent

if isinstance(event, UserTurnEnded):
    for content in event.content:
        if isinstance(content, UserTextSent):
            user_message = content.content
```

### エージェントターンイベント（履歴内）

| イベント               | 説明                   |
| ------------------ | -------------------- |
| `AgentTurnStarted` | エージェントがターンを開始        |
| `AgentTurnEnded`   | エージェントがターンを終了        |
| `AgentTextSent`    | エージェントが話したテキスト       |
| `AgentDtmfSent`    | エージェントが送信した DTMF トーン |

### ハンドオフイベント

| イベント             | 説明               |
| ---------------- | ---------------- |
| `AgentHandedOff` | ハンドオフツールに制御を移譲した |

### カスタムイベント

| イベント             | 説明                                                                                                |
| ---------------- | ------------------------------------------------------------------------------------------------- |
| `UserCustomSent` | クライアントが WebSocket の [`custom` イベント](/line/integrations/websocket-api#custom-event) で送信したカスタムメタデータ |

クライアントアプリケーションがコールストリームに `custom` WebSocket イベントを送信したときに受信します。イベントには、クライアントが含めた任意のキーと値のペアを持つ `metadata` 辞書が含まれます：

```python theme={null}
from line.events import UserCustomSent

async def process(self, env, event):
    if isinstance(event, UserCustomSent):
        action = event.metadata.get("action")
        # React to client-side triggers (e.g., button clicks, form submissions)
```

***

## 出力イベント

出力イベントは、会話を制御するためにエージェントが yield（生成）するイベントです。

### 発話

`AgentSendText` でメッセージを送信できます。

```python theme={null}
from line.events import AgentSendText

yield AgentSendText(text="Hello! How can I help you today?")
```

デフォルトでは、ユーザーはエージェントを中断できます。免責事項やその他の重要なメッセージで中断されたくない場合は、`interruptible` フラグを false に設定できます。

```python theme={null}
from line.events import AgentSendText

yield AgentSendText(
    text="Before we continue, I need to share a quick disclaimer.",
    interruptible=False,
)
```

### 通話制御

```python theme={null}
from line.events import AgentEndCall, AgentTransferCall, AgentSendDtmf

# End the call
yield AgentEndCall()

# Transfer to another number
yield AgentTransferCall(target_phone_number="+14155551234")

# Send DTMF tone
yield AgentSendDtmf(button="1")
```

### 動的設定

`AgentUpdateCall` を使って、会話の途中で通話設定（ボイス、発音、言語）を更新します：

```python theme={null}
from line.events import AgentUpdateCall

# Change voice
yield AgentUpdateCall(voice_id="5ee9feff-1265-424a-9d7f-8e4d431a12c7")

# Change pronunciation dictionary
yield AgentUpdateCall(pronunciation_dict_id="dict-123")

# Change language
yield AgentUpdateCall(language="es")

# Update multiple settings at once
yield AgentUpdateCall(
    voice_id="spanish-voice-id",
    pronunciation_dict_id="spanish-dict-id",
    language="es"
)
```

**AgentUpdateCall パラメータ:**

| フィールド                   | 型                        | 説明                                  |
| ----------------------- | ------------------------ | ----------------------------------- |
| `type`                  | `Literal["update_call"]` | イベントタイプ識別子（自動設定）                    |
| `voice_id`              | `Optional[str]`          | エージェントのボイスを更新                       |
| `pronunciation_dict_id` | `Optional[str]`          | 発音辞書を更新                             |
| `language`              | `Optional[str]`          | 音声認識（STT）および音声合成（TTS）モデルで使用される言語を更新 |

すべてのフィールドはオプションで、設定されたフィールドのみが更新されます。

### ツールイベント

`LlmAgent` がツール実行を追跡するために発行します：

```python theme={null}
from line.events import AgentToolCalled, AgentToolReturned

# Emitted when LLM calls a tool
yield AgentToolCalled(
    tool_call_id="call_123",
    tool_name="get_weather",
    tool_args={"city": "San Francisco"}
)

# Emitted when tool returns
yield AgentToolReturned(
    tool_call_id="call_123",
    tool_name="get_weather",
    tool_args={"city": "San Francisco"},
    result="72°F and sunny"
)
```

### ロギング

```python theme={null}
from line.events import LogMetric, LogMessage

# Log a metric
yield LogMetric(name="response_time_ms", value=150)

# Log a message
yield LogMessage(
    name="order_lookup",
    level="info",
    message="Found order #12345",
    metadata={"order_id": "12345"}
)
```

### カスタムイベント

エージェントからハーネスに任意のメタデータを送信します：

```python theme={null}
from line.events import AgentSendCustom

yield AgentSendCustom(metadata={"action": "show_form", "form_id": "checkout"})
```

[`UserCustomSent`](#custom-event) と組み合わせて、メタデータの双方向交換を実現できます。

### ボイスと言語の制御

通話の途中でボイスや音声認識言語を変更します：

```python theme={null}
from line.events import AgentUpdateCall

# Switch to Spanish voice and speech recognition
yield AgentUpdateCall(voice_id="spanish-voice-id", language="es")

# Enable multilingual auto-detect mode
yield AgentUpdateCall(language="multilingual")
```

`language` フィールドは ASR（音声認識）言語を設定します。[Ink STT](/build-with-cartesia/stt-models/older-models#ink-whisper) がサポートする任意の言語コード、または自動言語検出のための `"multilingual"` を指定できます。

***

## イベント履歴

すべての入力イベントには、会話履歴を含むオプションの `history` フィールドがあります。`history` が `None` の場合、そのイベントは履歴リスト内にあります。リストが含まれている場合は、完全な会話コンテキストが添付されています。`LlmAgent` はこれを自動的に処理するため、履歴を理解する必要があるのはカスタムエージェントを構築する場合のみです。

### 履歴へのアクセス

```python theme={null}
from line.events import UserTextSent, AgentTextSent

async def process(self, env, event):
    for past_event in event.history:
        if isinstance(past_event, UserTextSent):
            print(f"User said: {past_event.content}")
        elif isinstance(past_event, AgentTextSent):
            print(f"Agent said: {past_event.content}")
```

<Accordion title="履歴に含まれるイベントタイプ">
  履歴リストに含まれるイベントは、冗長なネストを避けるため `history=None` を持ちます。イベントタイプは通常の入力イベントと同じです：

  | イベントタイプ            | 説明               |
  | ------------------ | ---------------- |
  | `CallStarted`      | 通話が開始            |
  | `UserTurnStarted`  | ユーザーが発話を開始       |
  | `UserTextSent`     | ユーザーの書き起こされた発話   |
  | `UserDtmfSent`     | ユーザーの DTMF ボタン押下 |
  | `UserTurnEnded`    | ユーザーが発話を終了       |
  | `AgentTurnStarted` | エージェントが応答を開始     |
  | `AgentTextSent`    | エージェントが話したテキスト   |
  | `AgentDtmfSent`    | エージェントの DTMF トーン |
  | `AgentTurnEnded`   | エージェントが応答を終了     |
  | `CallEnded`        | 通話が終了            |
</Accordion>

<Accordion title="LlmAgent による履歴の処理">
  `LlmAgent` はイベント履歴を自動的に LLM メッセージに変換します：

  * **ユーザーメッセージ**: `UserTextSent` イベントから
  * **アシスタントメッセージ**: `AgentTextSent` イベントから
  * **ツール呼び出し**: `AgentToolCalled` および `AgentToolReturned` イベントから

  つまり LLM は、過去のツール呼び出しとその結果を含む完全なコンテキストを把握できるため、不必要な API 呼び出しを行わずにその情報を参照できます。
</Accordion>

<Accordion title="カスタムエージェント: 履歴の利用">
  `LlmAgent` を使わずにカスタムエージェントを構築する場合、コンテキスト、要約、パターン検出のために履歴を使用できます：

  ```python theme={null}
  class CustomAgent:
      async def process(self, env, event):
          user_turns = sum(
              1 for e in event.history
              if isinstance(e, UserTurnEnded)
          )

          if user_turns > 5:
              yield AgentSendText(text="We've been chatting for a while! Is there anything else I can help with?")
  ```
</Accordion>
