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

# ターン検出なしの OpenAI Realtime Transcription からの移行

このガイドでは、`turn_detection: null` を指定して使用している OpenAI Realtime Transcription からの移行について説明します。

<Card horizontal title="すべての移行ガイド" icon="arrow-left-from-arc" href="/ja-jp/use-the-api/stt/migrations" />

このガイドには、素の API の説明と SDK コードの両方が含まれています。SDK をインストールするには次のようにします。

<CodeGroup>
  ```bash Python theme={null}
  pip install cartesia
  ```

  ```bash TypeScript theme={null}
  npm i @cartesia/cartesia-js
  ```
</CodeGroup>

<Info>
  すでに Cartesia SDK を使用している場合は、バージョン `>=3.2.0` にアップグレードしてください
</Info>

## 接続

OpenAI の WebSocket URL と認証ヘッダーを Cartesia の `/stt/websocket` に置き換え、使用するモデルと入力音声フォーマットをクエリパラメーターとして指定します。

```diff theme={null}
- wss://api.openai.com/v1/realtime?intent=transcription
+ wss://api.cartesia.ai/stt/websocket?model=ink-2&encoding=pcm_s16le&sample_rate=24000
```

```diff theme={null}
- Authorization: Bearer <OPENAI_API_KEY>
+ Authorization: Bearer <CARTESIA_API_KEY>
+ Cartesia-Version: 2026-03-01
```

ブラウザでは、WebSocket はリクエストヘッダーをサポートしていません。代わりに、API バージョンを `cartesia_version` クエリパラメーターとして渡し、API キーの代わりに `access_token` クエリパラメーターで有効期限の短い[アクセストークン](/get-started/authenticate-your-client-applications)を使用してください。

Cartesia SDK で手動ファイナライズ WebSocket に接続します。

<CodeGroup>
  ```python Python (Async) theme={null}
  import os
  from cartesia import AsyncCartesia

  client = AsyncCartesia(api_key=os.getenv("CARTESIA_API_KEY"))

  async with client.stt.manual_finalize.websocket(
      model="ink-2", encoding="pcm_s16le", sample_rate=24000
  ) as connection:
      ...
  ```

  ```python Python theme={null}
  import os
  from cartesia import Cartesia

  client = Cartesia(api_key=os.getenv("CARTESIA_API_KEY"))

  with client.stt.manual_finalize.websocket(
      model="ink-2", encoding="pcm_s16le", sample_rate=24000
  ) as connection:
      ...
  ```

  ```typescript TypeScript theme={null}
  import Cartesia from "@cartesia/cartesia-js";

  const client = new Cartesia({ apiKey: process.env.CARTESIA_API_KEY });

  const connection = client.stt.manualFinalize.websocket({
    model: "ink-2",
    encoding: "pcm_s16le",
    sample_rate: 24000,
  });
  ```

  ```typescript TypeScript (Browser) theme={null}
  // Server-side: Generate access-tokens using your API key
  import Cartesia from '@cartesia/cartesia-js';

  const client = new Cartesia({ apiKey: process.env.CARTESIA_API_KEY });

  export async function GET() {
    const { token } = await client.accessToken.create({
      grants: { stt: true, tts: false, agent: false },
      // How long the token lasts in seconds
      // Allowed values: 0–3600
      expires_in: 3600,
    });
    return Response.json({ token });
  }


  // Client-side
  // 1. Fetch an access token from your server
  // 2. Connect to Cartesia via WebSocket
  import Cartesia from "@cartesia/cartesia-js";

  async function getToken(): Promise<string> {
    const res = await fetch('/replace-with-your-server');
    const { token } = await res.json();
    return token;
  }
  const audioContext = new AudioContext();

  const client = new Cartesia({ token: await getToken() });

  const connection = client.stt.manualFinalize.websocket({
    model: "ink-2",
    encoding: "pcm_f32le",
    sample_rate: audioContext.sampleRate,
  });
  ```
</CodeGroup>

## セッション設定

OpenAI は `session.update` ペイロードでセッションを設定します。Cartesia は同等の設定をクエリパラメーターとして受け取ります。

| OpenAI セッション設定                           | Cartesia Realtime STT (Manual)                                                           | 備考                                                                                                                 |
| ---------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `?intent=transcription`                  | —                                                                                        | Ink は文字起こしのみをサポートします。                                                                                              |
| `audio.input.transcription.model`        | `model=ink-2` <Badge color="red" size="sm">required</Badge>                              | `gpt-realtime-whisper` と `gpt-4o-transcribe` はいずれも `ink-2` にマッピングされます。                                             |
| `audio.input.format`（`audio/pcm`、24 kHz） | `encoding=pcm_s16le` + `sample_rate=24000` <Badge color="red" size="sm">required</Badge> | Cartesia はさらに多くの入力音声フォーマットをサポートします。すべての選択肢は[エンコーディング](#encoding)を参照してください。                                         |
| `audio.input.transcription.language`     | `language`                                                                               | `ink-2` は現在 `en` のみをサポートします。[その他の言語](/build-with-cartesia/stt/older-models#ink-whisper)には `ink-whisper` を使用してください。 |
| `audio.input.turn_detection`（`null`）     | —                                                                                        | サーバーサイドのターン検出については[自動ファイナライズ](/use-the-api/stt/migrate-from-openai-realtime-transcription/auto)を参照してください。          |
| `audio.input.transcription.delay`        | —                                                                                        | 設定できません。                                                                                                           |
| `audio.input.noise_reduction`            | —                                                                                        | 不要です。                                                                                                              |
| —                                        | `cartesia_version=2026-03-01` <Badge color="red" size="sm">required</Badge>              | 詳細は [API 規約](/use-the-api/api-conventions#always-send-a-cartesia-version-header)を参照してください。                         |

<Accordion title="encoding">
  OpenAI は入力形式を `audio.input.format` で設定します。Cartesia は `encoding` と `sample_rate` をクエリパラメーターとして受け取ります。

  | OpenAI `audio.input.format`              | Cartesia `encoding` | Cartesia `sample_rate` |
  | ---------------------------------------- | ------------------- | ---------------------- |
  | `{ "type": "audio/pcm", "rate": 24000 }` | `pcm_s16le`         | `24000`                |
  | `g711_ulaw`                              | `pcm_mulaw`         | `8000`                 |
  | `g711_alaw`                              | `pcm_alaw`          | `8000`                 |

  OpenAI の PCM 形式は 16 ビット、24 kHz、モノラルです。Cartesia はその `sample_rate` をそのまま受け付けるため、リサンプリングせずに同じ音声をストリーミングできます。Cartesia は `pcm_s32le`、`pcm_f16le`、`pcm_f32le` も受け付けます。
</Accordion>

## 音声の送信

OpenAI は各音声チャンクを JSON 形式のテキストフレームでラップし、音声バイトを base64 エンコードします。\
Cartesia は音声チャンクをバイナリフレームとして受け取ります。生の音声バイトを直接送信してください。

```diff theme={null}
- { "type": "input_audio_buffer.append", "audio": "<base64 PCM>" }
+ <raw PCM bytes>
```

OpenAI の `session.update` メッセージに相当するものはありません。パラメーターを変更するには WebSocket を新たに再接続してください。

Cartesia の制御コマンドは JSON ではなく、素のテキストフレームです。

バッファされた音声をコミットしてトランスクリプトを出力するには、`input_audio_buffer.commit` の代わりに `finalize` フレームを送信します。

```text theme={null}
finalize
```

<Warning>
  音声ストリームの適切なタイミングで `finalize` コマンドを送信することが重要です。

  ユーザーがいつ話し終えるかわからない場合は、[自動ファイナライズ](./auto)の使用を検討してください。
</Warning>

残りの音声をすべて文字起こししてセッションを閉じるには、`close` フレームを送信します。

```text theme={null}
close
```

### SDK での音声の送信

<CodeGroup>
  ```python Python (Async) theme={null}
  # raw_audio (bytes) - Raw audio data, about 100 ms at a time
  await connection.send_raw(raw_audio)
  ```

  ```python Python theme={null}
  # raw_audio (bytes) - Raw audio data, about 100 ms at a time
  connection.send_raw(raw_audio)
  ```

  ```typescript TypeScript theme={null}
  // @param {ArrayBufferLike} rawAudio - raw audio data, about 100 ms at a time
  connection.sendRaw(rawAudio);
  ```
</CodeGroup>

### 送信前に base64 エンコードされた音声をデコードする

<CodeGroup>
  ```python Python (Async) theme={null}
  from base64 import b64decode

  await connection.send_raw(b64decode(audio_base_64))
  ```

  ```python Python theme={null}
  from base64 import b64decode

  connection.send_raw(b64decode(audio_base_64))
  ```

  ```typescript TypeScript theme={null}
  connection.sendRaw(Uint8Array.fromBase64(audioBase64));
  ```
</CodeGroup>

### ファイナライズとクローズ

<CodeGroup>
  ```python Python (Async) theme={null}
  # Commit input audio
  await connection.send("finalize")

  # Transcribe remaining audio, then close the socket
  await connection.send("close")
  ```

  ```python Python theme={null}
  # Commit input audio
  connection.send("finalize")

  # Transcribe remaining audio, then close the socket
  connection.send("close")
  ```

  ```typescript TypeScript theme={null}
  // Commit input audio
  connection.send("finalize");

  // Transcribe remaining audio, then close the socket
  connection.send("close");
  ```
</CodeGroup>

## イベントのマッピング

OpenAI は `conversation.item.input_audio_transcription.delta` イベントと、コミットされたターンごとに `completed` イベントをストリーミングします。\
Cartesia は `transcript` デルタに加え、`finalize` および `close` コマンドに対する確認応答を発行します。

| OpenAI `type`                                           | Cartesia `type`                | 備考                                                              |
| ------------------------------------------------------- | ------------------------------ | --------------------------------------------------------------- |
| `session.created` / `session.updated`                   | —                              | Cartesia にはセッション設定のやり取りがありません。そのまま音声の送信を開始してください。               |
| `conversation.item.input_audio_transcription.delta`     | `transcript`                   | Ink 2 と Whisper は `is_final: true` のみを送信します。下の行を参照してください。       |
| `conversation.item.input_audio_transcription.completed` | `transcript`（`is_final: true`） | OpenAI はコミットされた完全なトランスクリプトを送信しますが、Cartesia は**デルタ**をストリーミングします。 |
| `input_audio_buffer.committed`                          | `flush_done`                   | コミット / `finalize` 後にバッファが処理されたことの確認応答。                          |
| —                                                       | `done`                         | `close` に対する確認応答。WebSocket が閉じられる直前に送信されます。                     |
| `error`                                                 | `error`                        | クライアントまたはサーバーのエラー。                                              |

### 完了したトランスクリプト

OpenAI の `conversation.item.input_audio_transcription.completed` イベントは**ターン全体**を含みます。

```json theme={null}
{
  "type": "conversation.item.input_audio_transcription.completed",
  "item_id": "item_003",
  "content_index": 0,
  "transcript": "Hello world! This is the full transcript."
}
```

これは 1 つ以上の Cartesia `transcript` イベントになり、それぞれが**デルタ**を含みます。

```json theme={null}
{
  "type": "transcript",
  "is_final": true,
  "text": "Hello world!",
  "duration": 0.5,
  "words": [
    {
      "word": "Hello",
      "start": 0,
      "end": 0.2
    },
    {
      "word": " world!",
      "start": 0.2,
      "end": 0.5
    }
  ],
  "request_id": "2ff8af53-4d38-479d-8287-58940f01c701"
}
```

> * Ink 2 はまだ `duration` や `words` を返しません
> * Ink 2 と Whisper は現在、確定トランスクリプト（`is_final: true`）のみを発行します

<Tip>Cartesia の確定トランスクリプトは**デルタ**です。空白を除去したり追加したりせずに連結してください。</Tip>

<CodeGroup>
  ```python Python (Async) theme={null}
  import asyncio
  from cartesia.types.stt import STTManualFinalizeWebsocketResponse

  committed_transcript = ""

  async def receive() -> None:
      global committed_transcript
      async for event in connection:
          if event.type == "transcript":
              if event.is_final:
                # Do not strip or add whitespace!
                committed_transcript += event.text
          elif event.type == "flush_done" or event.type == "done":
              print(f"Transcript: {committed_transcript}")
              committed_transcript = ""
          elif event.type == "error":
              print(f"error: {event.message}")

  # Run receive() concurrently with your audio sender:
  #   await asyncio.gather(send_audio(), receive())
  ```

  ```python Python theme={null}
  from cartesia.types.stt import STTManualFinalizeWebsocketResponse

  committed_transcript = ""

  for event in connection:
      if event.type == "transcript":
          if event.is_final:
            # Do not strip or add whitespace!
            committed_transcript += event.text
      elif event.type == "flush_done" or event.type == "done":
          print(f"Transcript: {committed_transcript}")
          committed_transcript = ""
      elif event.type == "error":
          print(f"error: {event.message}")
  ```

  ```typescript TypeScript theme={null}
  import Cartesia from '@cartesia/cartesia-js';

  let committedTranscript = '';

  for await (const event of connection.stream()) {
    if (event.type === 'message') {
      const m = event.message;
      switch (m.type) {
        case 'transcript':
          if (m.is_final) {
            // Do not trim or add whitespace!
            committedTranscript += m.text;
          }
          break;
        case 'flush_done':
        case 'done':
          console.log(`Transcript: ${committedTranscript}`);
          committedTranscript = '';
          break;
      }
    } else if (event.type === 'error') {
      console.error(`error: ${event.error.message}`);
    }
  }
  ```
</CodeGroup>

## サーバーメッセージの例

> GPT は完全なトランスクリプトを送信します。Ink はデルタを送信し、単語の途中で区切られることがあります。

| OpenAI gpt-realtime-whisper                                                                     | Cartesia Realtime STT (Manual)                                             |
| ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| <Badge color="orange">…transcription.delta</Badge> `"GPT sends"`                                | <Badge color="green">is\_final: true</Badge> `"GPT sends"`                 |
| <Badge color="orange">…transcription.delta</Badge> `" full transcripts."`                       | <Badge color="green">is\_final: true</Badge> `" full transc"`              |
| <Badge>commit</Badge> *(client)*                                                                | <Badge>finalize</Badge> *(client)*                                         |
| <Badge>input\_audio\_buffer.committed</Badge>                                                   | <Badge color="green">is\_final: true</Badge> `"ripts."`                    |
| <Badge color="green">…transcription.completed</Badge> `"GPT sends full transcripts."`           | <Badge>flush\_done</Badge>                                                 |
| <Badge color="orange">…transcription.delta</Badge> `"Ink sends deltas"`                         | <Badge color="green">is\_final: true</Badge> `" Ink sends"`                |
| <Badge color="orange">…transcription.delta</Badge> `" and may break words."`                    | <Badge color="green">is\_final: true</Badge> `" deltas and may break wor"` |
| <Badge>commit</Badge> *(client)*                                                                | <Badge>finalize</Badge> *(client)*                                         |
| <Badge>input\_audio\_buffer.committed</Badge>                                                   | <Badge color="green">is\_final: true</Badge> `"ds."`                       |
| <Badge color="green">…transcription.completed</Badge> `"Ink sends deltas and may break words."` | <Badge>flush\_done</Badge>                                                 |

## 参考資料

<CardGroup cols={2}>
  <Card icon="code" title="API リファレンス" href="/api-reference/stt/websocket">
    Cartesia Realtime STT (Manual)
  </Card>

  <Card icon="brackets-curly" title="完全なコード例" href="/examples/stt-manual-finalize-websocket">
    Cartesia SDK を使用
  </Card>
</CardGroup>
