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

# 自動ファイナライズによる Deepgram Nova からの移行

このガイドでは、セッション中に `Finalize` コマンドを送信せずに Deepgram Live Audio (Nova) を利用している場合の移行方法を説明します。

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

<Note>
  Ink 2 は現時点で英語のみをサポートしています。\
  今後数ヶ月のうちに他言語の追加を予定しています。
</Note>

## 接続

Deepgram の WebSocket URL と認証ヘッダーを、Cartesia の `/stt/turns/websocket` に置き換えます。

```diff theme={null}
- wss://api.deepgram.com/v1/listen?model=nova-3&encoding=linear16&sample_rate=16000
+ wss://api.cartesia.ai/stt/turns/websocket?model=ink-2&encoding=pcm_s16le&sample_rate=16000
```

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

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

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.auto_finalize.websocket(
      model="ink-2", encoding="pcm_s16le", sample_rate=16000
  ) as connection:
      ...
  ```

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

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

  with client.stt.auto_finalize.websocket(
      model="ink-2", encoding="pcm_s16le", sample_rate=16000
  ) 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.autoFinalize.websocket({
    model: "ink-2",
    encoding: "pcm_s16le",
    sample_rate: 16000,
  });
  ```

  ```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.autoFinalize.websocket({
    model: "ink-2",
    encoding: "pcm_f32le",
    sample_rate: audioContext.sampleRate,
  });
  ```
</CodeGroup>

## クエリパラメーター

| Deepgram Nova                                                   | Cartesia Realtime STT (Auto)                                                | 備考                                                                                         |
| --------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `model=nova-3` <Badge color="red" size="sm">required</Badge>    | `model=ink-2` <Badge color="red" size="sm">required</Badge>                 | すべての選択肢は[モデル](/build-with-cartesia/stt/latest)を参照してください。                                   |
| `version=latest`                                                | —                                                                           | モデルバージョンは `model` パラメーターで制御できます。                                                           |
| `encoding=linear16`                                             | `encoding=pcm_s16le` <Badge color="red" size="sm">required</Badge>          | すべての選択肢は[エンコーディング](#encoding)を参照してください。                                                    |
| `sample_rate`                                                   | `sample_rate` <Badge color="red" size="sm">required</Badge>                 | 変更なし。                                                                                      |
| `language`                                                      | —                                                                           | `ink-2` は現時点では `en` のみをサポートしています。今後さらに多くの言語に対応予定です。                                        |
| —                                                               | `cartesia_version=2026-03-01` <Badge color="red" size="sm">required</Badge> | 詳細は [API 規約](/use-the-api/api-conventions#always-send-a-cartesia-version-header)を参照してください。 |
| `channels`、`multichannel`                                       | —                                                                           | WebSocket 接続ごとにモノラルの音声ストリームを送信してください。                                                      |
| `endpointing`、`interim_results`、`utterance_end_ms`、`vad_events` | —                                                                           | 不要です。                                                                                      |
| `keyterm`、`keywords`                                            | `keyterm`                                                                   | [キータームプロンプティング](/use-the-api/stt/keyterms)を参照してください。                                       |
| `mip_opt_out`                                                   | —                                                                           | 組織によって制御されます。                                                                              |

<Accordion title="encoding">
  | Deepgram   | Cartesia    |
  | ---------- | ----------- |
  | `linear16` | `pcm_s16le` |
  | `linear32` | `pcm_s32le` |
  | `mulaw`    | `pcm_mulaw` |
  | `alaw`     | `pcm_alaw`  |
  | 非対応        | `pcm_f16le` |
  | 非対応        | `pcm_f32le` |
  | `flac`     | 非対応         |
  | `amr-nb`   | 非対応         |
  | `amr-wb`   | 非対応         |
  | `opus`     | 非対応         |
  | `ogg-opus` | 非対応         |
  | `speex`    | 非対応         |
  | `g729`     | 非対応         |
</Accordion>

## 音声の送信

どちらの API も、同じ方法でバイナリ WebSocket フレームとして生の PCM 音声を受け付けます。

> Cartesia は次のエンコーディングをサポートしていません: `flac`、`amr-nb`、`amr-wb`、`opus`、`ogg-opus`、`speex`、`g729`

Deepgram の `Finalize` コマンドに**相当するものはありません**。Ink はターン境界を自動的に検出し、ユーザーが話し終えると `turn.end` を発行するため、フラッシュする必要はありません。

```diff theme={null}
- { "type": "Finalize" }
```

<Warning>
  現在 Deepgram Nova でセッション中に `Finalize` コマンドを送信している場合は、代わりに[手動ファイナライズ](/use-the-api/stt/migrate-from-deepgram-nova/manual)を使った Cartesia Ink の利用を検討してください。

  詳細は[移行ガイド](/use-the-api/stt/migrations)のページを参照してください。
</Warning>

セッションをクリーンに閉じるには、JSON テキストフレームを送信します。

```diff theme={null}
- { "type": "CloseStream" }
+ { "type": "close" }
```

Cartesia には Deepgram の `KeepAlive` メッセージに相当するものはありません。接続には 3 分のアイドルタイムアウトがあり、音声チャンクを送信するたびにリセットされます。接続を維持するには、音声（無音かどうかを問わず）をストリーミングし続けてください。

<CodeGroup>
  ```python Python (Async) theme={null}
  # Equivalent to 
  # deepgram_connection.send_media(audio_chunk)
  await connection.send_raw(audio_chunk)

  # Equivalent to
  # deepgram_connection.send_close_stream()
  await connection.send({"type": "close"})
  ```

  ```python Python theme={null}
  # Equivalent to 
  # deepgram_connection.send_media(audio_chunk)
  connection.send_raw(audio_chunk)

  # Equivalent to
  # deepgram_connection.send_close_stream()
  connection.send({"type": "close"})
  ```

  ```typescript TypeScript theme={null}
  // Equivalent to deepgramConnection.sendMedia(audioChunk)
  // @param {ArrayBufferLike} audioChunk - Note: Blob is not accepted
  connection.sendRaw(audioChunk);

  // Equivalent to
  // deepgramConnection.sendCloseStream({ type: "CloseStream" })
  connection.send({ type: "close" });
  ```
</CodeGroup>

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

Deepgram は 4 種類のサーバーメッセージを発行し、トランスクリプト結果と個別の音声区間シグナルを混在させています。

Cartesia は同じ情報をターンのライフサイクルにまとめます: `turn.start`、`turn.update`、`turn.eager_end`、`turn.resume`、`turn.end`。完全なステートマシンについては[ターン検出](/use-the-api/stt/turns)を参照してください。

| Deepgram `type`               | Cartesia `type`  | 備考                                             |
| ----------------------------- | ---------------- | ---------------------------------------------- |
| `SpeechStarted`               | `turn.start`     | ユーザーが話し始めた。トランスクリプトは含まない。                      |
| `Results` (`is_final: false`) | `turn.update`    | 発話／ターンの暫定トランスクリプト。                             |
| `Results` (`is_final: true`)  | `turn.end`       | 発話／ターンの確定トランスクリプト。                             |
| `UtteranceEnd`                | `turn.end`       | ユーザーが話し終えた。                                    |
| —                             | `turn.eager_end` | モデルがユーザーが話し終えた可能性を予測する。無視してもよい。                |
| —                             | `turn.resume`    | ユーザーが話し続けた。直前の `turn.eager_end` を無視する。         |
| `Metadata`                    | —                | 相当するものはなし。                                     |
| —                             | `connected`      | WebSocket が確立されると一度だけ発火する。音声を送信する前にこれを待つ必要はない。 |
| —                             | `error`          | クライアントまたはサーバーのエラー。                             |

### Deepgram の `Results` メッセージ

Deepgram の `Results` には多くの情報が含まれています。同様の情報は Cartesia の `turn.update` および `turn.end` イベントから取得できます。

| Deepgram `Results`   | Cartesia      | 備考                                   |
| -------------------- | ------------- | ------------------------------------ |
| `is_final: false`    | `turn.update` | 発話／ターンの暫定トランスクリプト。直前の確定トランスクリプト以降の累積 |
| `is_final: true`     | `turn.end`    | 発話／ターンの確定トランスクリプト。                   |
| `speech_final: true` | `turn.end`    | ユーザーが話し終えた。                          |

<Info>
  Deepgram は `UtteranceEnd` と `speech_final: true` を別々に送信しますが、これらは「ユーザーが話し終えた」という同じ意味を持ちます。

  Cartesia はこれを単一の高精度シグナル `turn.end` に簡素化しています。
</Info>

Deepgram の `Results` メッセージ:

```json theme={null}
{
  "type": "Results",
  "is_final": true,
  "speech_final": true,
  "channel": {
    "alternatives": [
      {
        "transcript": "Hello world!",
        "confidence": 0.99,
        "words": [ ... ]
      }
    ]
  },
  "metadata": { ... }
}
```

は、Cartesia の `turn.update` / `turn.end` イベントになります:

```json theme={null}
{
  "type": "turn.end",
  "transcript": "Hello world!",
  "request_id": "33cacee6-1936-4949-a05b-ecc9f2393248"
}
```

<Info>`turn.start` と `turn.resume` イベントはトランスクリプトを含みません。</Info>

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

  final_transcript = ""

  def on_message(message: STTAutoFinalizeWebsocketResponse) -> None:
      global final_transcript
      if message.type == "turn.start":
          print("User started speaking")
      elif message.type == "turn.update":
          print("Transcript so far: " + final_transcript + message.transcript)
      elif message.type == "turn.end":
          print("User stopped speaking")
          # Do not strip or add spaces!
          final_transcript += message.transcript
      elif message.type == "error":
          print(f"Error: {message.message}")

  # Equivalent to
  # deepgram_connection.on(EventType.MESSAGE, on_message)
  connection.on("event", on_message)

  # Equivalent to
  # asyncio.create_task(deepgram_connection.start_listening())
  recv_task = asyncio.create_task(connection.dispatch_events())
  ```

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

  final_transcript = ""

  def on_message(message: STTAutoFinalizeWebsocketResponse) -> None:
      global final_transcript
      if message.type == "turn.start":
          print("User started speaking")
      elif message.type == "turn.update":
          print("Transcript so far: " + final_transcript + message.transcript)
      elif message.type == "turn.end":
          print("User stopped speaking")
          # Do not strip or add spaces!
          final_transcript += message.transcript
      elif message.type == "error":
          print(f"Error: {message.message}")

  # Equivalent to
  # deepgram_connection.on(EventType.MESSAGE, on_message)
  connection.on("event", on_message)

  # Equivalent to
  # threading.Thread(target=deepgram_connection.start_listening, daemon=True).start()
  threading.Thread(target=connection.dispatch_events, daemon=True).start()
  ```

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

  let finalTranscript = '';

  // Equivalent to
  // deepgramConnection.on("message", (message) => { ... });
  connection.on("event", (message: Cartesia.STT.AutoFinalize.STTAutoFinalizeWebsocketResponse) => {
    switch (message.type) {
      case "turn.start":
        console.log("User started speaking");
        break;
      case "turn.update":
        console.log("Transcript so far: " + finalTranscript + message.transcript);
        break;
      case "turn.end":
        console.log("User stopped speaking");
        // Do not trim or add spaces!
        finalTranscript += message.transcript
        break;
    }
  });

  // Equivalent to
  // deepgramConnection.on("error", (error) => { ... });
  connection.on("error", (error) => {
    if (error.error) {
      // Server sent error (may be a bad request or internal server error)
      console.error(`Server sent an error: ${error.error.message}`);
    } else {
      // Client error
      console.error(`Client had an error: ${error.message}`);
    }
  });
  ```
</CodeGroup>

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

> Hello! Nova's transcripts are joined with spaces. Ink's are not.

| Deepgram Nova                                                                                        | Cartesia Realtime STT (Auto)                                                                    |
| ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| <Badge>SpeechStarted</Badge>                                                                         | <Badge>turn.start</Badge>                                                                       |
| <Badge color="orange">is\_final: false</Badge> `"Hello!"`                                            | <Badge color="orange">turn.update</Badge> `"Hello!"`                                            |
| —                                                                                                    | <Badge>turn.eager\_end</Badge> `"Hello!"`                                                       |
| —                                                                                                    | <Badge>turn.resume</Badge>                                                                      |
| <Badge color="orange">is\_final: false</Badge> `"Hello! Nova's transcripts are joined with spaces."` | <Badge color="orange">turn.update</Badge> `"Hello! Nova's transcripts are joined with spaces."` |
| —                                                                                                    | <Badge>turn.eager\_end</Badge> `"Hello! Nova's transcripts are joined with spaces."`            |
| <Badge color="green">is\_final: true</Badge> `"Hello! Nova's transcripts are joined with spaces."`   | <Badge color="green">turn.end</Badge> `"Hello! Nova's transcripts are joined with spaces."`     |
| <Badge>UtteranceEnd</Badge>                                                                          | —                                                                                               |
| <Badge>SpeechStarted</Badge>                                                                         | <Badge>turn.start</Badge>                                                                       |
| <Badge color="orange">is\_final: false</Badge> `"Ink's are not."`                                    | <Badge color="orange">turn.update</Badge> `" Ink's are not."`                                   |
| —                                                                                                    | <Badge>turn.eager\_end</Badge> `" Ink's are not."`                                              |
| <Badge color="green">is\_final: true</Badge> `"Ink's are not."`                                      | <Badge color="green">turn.end</Badge> `" Ink's are not."`                                       |
| <Badge>UtteranceEnd</Badge>                                                                          | —                                                                                               |

## 参考資料

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

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