> ## 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 Flux からの移行

このガイドでは、Deepgram の Turn-based Audio (Flux) API からの移行を説明します。

Cartesia と Deepgram Flux はどちらも WebSocket 経由でターンベースのイベントを発行するため、Ink への移行は主にフィールド名の変更といくつかの接続パラメーターの更新だけで済みます。

<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 のものに置き換えます。

```diff theme={null}
- wss://api.deepgram.com/v2/listen?model=flux-general-en&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 Flux                                                         | Cartesia Ink                                                                | 備考                                                                                         |
| --------------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `model=flux-general-en` <Badge color="red" size="sm">required</Badge> | `model=ink-2` <Badge color="red" size="sm">required</Badge>                 | 全オプションは [STT モデル](/build-with-cartesia/stt/latest)を参照してください。                               |
| `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_hint`                                                       | —                                                                           | 現在は英語のみサポートしています。多言語対応は近日公開予定です！                                                           |
| —                                                                     | `cartesia_version=2026-03-01` <Badge color="red" size="sm">required</Badge> | 詳細は [API 規約](/use-the-api/api-conventions#always-send-a-cartesia-version-header)を参照してください。 |
| `eager_eot_threshold`、`eot_threshold`、`eot_timeout_ms`                | `turn_eager_end_threshold`、`turn_end_threshold`、`turn_end_timeout_ms`       | しきい値の挙動は Deepgram とは異なります。下記の[ターン検出](#ターン検出)を参照してください。                                     |
| `keyterm`                                                             | `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` |
  | `opus`     | 非対応         |
  | `ogg-opus` | 非対応         |
</Accordion>

### ターン検出

`turn_end_timeout_ms` は `eot_timeout_ms` に直接相当します。

`turn_eager_end_threshold` と `turn_end_threshold` は `eager_eot_threshold` および `eot_threshold` と同様の機能を提供しますが、方向性が逆になっています。Deepgram では値が高いほど発火前により高い確信度を要求しますが、Cartesia では値が低いほど発火前により高い確信度を要求します。Deepgram の値をそのまま再利用しないでください。各しきい値の挙動、範囲、デフォルト値については[ターン検出の設定](/use-the-api/stt/turns#configuring-turn-detection)を参照してください。

## 音声の送信

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

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

セッションを閉じるには、JSON エンコードされた WebSocket テキストフレームを送信します:

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

Cartesia には、Deepgram の `Configure` 制御メッセージに相当するものはありません。ターンの終了を設定する必要がないためです。

<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 `type` | Cartesia `type` |
| --------------- | --------------- |
| `Connected`     | `connected`     |
| `Error`         | `error`         |
| `TurnInfo`      | 下記参照            |

Deepgram はすべてのターンイベントを単一の `TurnInfo` メッセージに `event` 判別子付きでラップします。Cartesia はイベントごとに 1 つのメッセージタイプを発行し、その型はトップレベルの `type` フィールドに含まれます。

| Deepgram `TurnInfo.event` | Cartesia `type`  | `transcript` を含むか？ |
| ------------------------- | ---------------- | ------------------ |
| `StartOfTurn`             | `turn.start`     | いいえ（Deepgram: はい）  |
| `Update`                  | `turn.update`    | はい                 |
| `EagerEndOfTurn`          | `turn.eager_end` | はい                 |
| `TurnResumed`             | `turn.resume`    | いいえ（Deepgram: はい）  |
| `EndOfTurn`               | `turn.end`       | はい                 |

Deepgram の `TurnInfo` メッセージ:

```json theme={null}
{
  "type": "TurnInfo",
  "event": "EndOfTurn",
  "turn_index": 0,
  "transcript": "Hi I need to cancel my subscription please.",
  "words": [...],
  "end_of_turn_confidence": 0.7,
  "audio_window_start": 0.0,
  "audio_window_end": 1.7
}
```

これは Cartesia の `turn.*` イベントになります:

```json theme={null}
{
  "type": "turn.end",
  "transcript": "Hi I need to cancel my subscription please.",
  "request_id": "2ff8af53-4d38-479d-8287-58940f01c701"
}
```

Deepgram と同様に、`transcript` はターン内で累積的です。

## イベントハンドラー

ハンドラーの分岐構造は変わりません。変わるのはメッセージの形状だけです。

```diff theme={null}
  ws.onmessage = (message) => {
    const data = JSON.parse(message.data);
-   if (data.type !== "TurnInfo") return;
-   switch (data.event) {
-     case "StartOfTurn":    onTurnStart(); break;
-     case "Update":         onTranscriptUpdate(data.transcript); break;
-     case "EagerEndOfTurn": prepareReply(data.transcript); break;
-     case "TurnResumed":    cancelReply(); break;
-     case "EndOfTurn":      finalizeReply(data.transcript); break;
-   }
+   switch (data.type) {
+     case "turn.start":     onTurnStart(); break;
+     case "turn.update":    onTranscriptUpdate(data.transcript); break;
+     case "turn.eager_end": prepareReply(data.transcript); break;
+     case "turn.resume":    cancelReply(); break;
+     case "turn.end":       finalizeReply(data.transcript); break;
+   }
  };
```

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

  def on_message(message: STTAutoFinalizeWebsocketResponse) -> None:
      if message.type == "turn.start":
          print("StartOfTurn")
      elif message.type == "turn.update":
          print(f"Update: {message.transcript}")
      elif message.type == "turn.eager_end":
          print(f"EagerEndOfTurn: {message.transcript}")
      elif message.type == "turn.resume":
          print("TurnResumed")
      elif message.type == "turn.end":
          print(f"EndOfTurn: {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

  def on_message(message: STTAutoFinalizeWebsocketResponse) -> None:
      if message.type == "turn.start":
          print("StartOfTurn")
      elif message.type == "turn.update":
          print(f"Update: {message.transcript}")
      elif message.type == "turn.eager_end":
          print(f"EagerEndOfTurn: {message.transcript}")
      elif message.type == "turn.resume":
          print("TurnResumed")
      elif message.type == "turn.end":
          print(f"EndOfTurn: {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';

  // Equivalent to
  // deepgramConnection.on("message", (message) => { ... });
  connection.on("event", (message: Cartesia.STT.AutoFinalize.STTAutoFinalizeWebsocketResponse) => {
    switch (message.type) {
      case "turn.start":
        console.log("StartOfTurn");
        break;
      case "turn.update":
        console.log(`Update: ${message.transcript}`);
        break;
      case "turn.eager_end":
        console.log(`EagerEndOfTurn: ${message.transcript}`);
        break;
      case "turn.resume":
        console.log("TurnResumed");
        break;
      case "turn.end":
        console.log(`EndOfTurn: ${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>

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

> Flux のトランスクリプトはスペースで連結されます。Ink のトランスクリプトは連結されません。

| Deepgram Flux                                                                         | Cartesia Realtime STT (Auto)                                                             |
| ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| <Badge>StartOfTurn</Badge>                                                            | <Badge>turn.start</Badge>                                                                |
| <Badge color="orange">Update</Badge> `"Flux's transcripts"`                           | <Badge color="orange">turn.update</Badge> `"Flux's transcripts"`                         |
| <Badge>EagerEndOfTurn</Badge> `"Flux's transcripts"`                                  | <Badge>turn.eager\_end</Badge> `"Flux's transcripts"`                                    |
| <Badge>TurnResumed</Badge>                                                            | <Badge>turn.resume</Badge>                                                               |
| <Badge color="orange">Update</Badge> `"Flux's transcripts are joined with spaces."`   | <Badge color="orange">turn.update</Badge> `"Flux's transcripts are joined with spaces."` |
| <Badge>EagerEndOfTurn</Badge> `"Flux's transcripts are joined with spaces."`          | <Badge>turn.eager\_end</Badge> `"Flux's transcripts are joined with spaces."`            |
| <Badge color="green">EndOfTurn</Badge> `"Flux's transcripts are joined with spaces."` | <Badge color="green">turn.end</Badge> `"Flux's transcripts are joined with spaces."`     |
| <Badge>StartOfTurn</Badge>                                                            | <Badge>turn.start</Badge>                                                                |
| <Badge color="orange">Update</Badge> `"Ink's are not."`                               | <Badge color="orange">turn.update</Badge> `" Ink's are not."`                            |
| <Badge>EagerEndOfTurn</Badge> `"Ink's are not."`                                      | <Badge>turn.eager\_end</Badge> `" Ink's are not."`                                       |
| <Badge color="green">EndOfTurn</Badge> `"Ink's are not."`                             | <Badge color="green">turn.end</Badge> `" Ink's are not."`                                |

## 参照資料

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