diff --git a/CLAUDE.md b/CLAUDE.md
index f739d6f..fbe0112 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -50,7 +50,7 @@ aai.settings.api_key = "your-key"
- `aai.SyncTranscriptResponse` — Sync result: `.text`, `.words` (`SyncWord` with `confidence` always, `start`/`end` only when `timestamps=True`), `.confidence`, `.audio_duration_ms`, `.session_id`, `.request_time_ms`
- `aai.DictationTranscriber` — Dictation API: audio uploaded as it is spoken over one live request, transcript (and optional LLM pass) out. Methods: `open_live()` (push-style `DictationLiveSession`: `write()`/`close()`/`result()`/`abort()`), `transcribe_live()` (iterable, file object, bytes or path), `warm()`. There is no buffered `transcribe()`: every entry point posts to `/v1/transcribe/live`
- `aai.AsyncDictationTranscriber` — Asyncio counterpart of `DictationTranscriber`; `open_live()` returns an `AsyncDictationLiveSession`. Owns an HTTP pool: use `async with` or `await aclose()`
-- `aai.DictationConfig` — Dictation options: `sample_rate`, `channels`, `language_codes`, `keyterms_prompt`, `llm_instruction`, `rewrite_mode` (`aai.DictationRewriteMode.fast` default | `smart`). Rejects unknown fields
+- `aai.DictationConfig` — Dictation options: `sample_rate`, `channels`, `language_codes`, `keyterms_prompt`, `llm_instruction`, `llm` (`aai.DictationLLMRequest`: an LLM Gateway request of your own with `{{turn}}`, or a saved prompt by `aai_prompt`; never with `llm_instruction`), `rewrite_mode` (`aai.DictationRewriteMode.fast` default | `smart`). Rejects unknown fields
- `aai.DictationResponse` — Dictation result: `.text`, `.words` (`DictationWord` with `text` + `confidence`), `.confidence`, `.llm_response`, `.llm_error`, `.audio_duration_ms`, `.session_id`, `.request_time_ms`, `.sync_time_ms`, `.auth_time_ms`, and `.final_text` (the LLM rewrite, falling back to `.text`)
- `aai.TextToSpeech` — Text-to-Speech HTTP API: one text per request, audio out. Methods: `synthesize()` (complete audio as a `TTSResponse`), `stream()` (a `TTSStream` context manager yielding bytes as the API generates them), `close()` / `with` for a client built from `api_key=`. Host from `aai.settings.tts_base_url` (`https://tts.us.assemblyai.com`; set `https://tts.eu.assemblyai.com` for the EU zone). Requests use the client's own TTS pool (`client.tts_http_client`, built when the `TextToSpeech` is), which keeps idle connections 120 s by default (`aai.settings.tts_keepalive_expiry`; unset, a shorter `keepalive_expiry` applies), so consecutive sentences reuse one connection. Every TTS pool shares one process-wide TLS context. A passed `client=` stays the caller's: `client.close()` closes both pools
- `aai.AsyncTextToSpeech` — Asyncio counterpart of `TextToSpeech`; `synthesize()` is a coroutine and `stream()` returns an `AsyncTTSStream`. Owns an HTTP pool: use `async with` or `await aclose()`
diff --git a/README.md b/README.md
index 105d5c5..f919b5d 100644
--- a/README.md
+++ b/README.md
@@ -798,6 +798,43 @@ config = aai.DictationConfig(
+
+ Send your own LLM request
+
+Set `llm` instead of `llm_instruction` to send an LLM Gateway chat completions request of your own for the rewrite. Write `messages` or `prompt` yourself and put `{{turn}}` where the transcript goes. The model's output comes back in `llm_response`, like any other rewrite:
+
+```python
+import assemblyai as aai
+
+aai.settings.api_key = ""
+
+config = aai.DictationConfig(
+ llm={
+ "model": "gemma-4-31b",
+ "messages": [
+ {"role": "system", "content": "Rewrite the dictated note as a short, formal email."},
+ {"role": "user", "content": "{{turn}}"},
+ ],
+ "max_tokens": 1024,
+ }
+)
+
+result = aai.DictationTranscriber().transcribe_live("./note.wav", config=config)
+print(result.final_text)
+```
+
+To keep the prompt off the device, save it in your account and send only its name in `aai_prompt`. Dictation passes the transcript as `{{ text }}`, and `prompt_replacements` fills your own tags:
+
+```python
+config = aai.DictationConfig(
+ llm={"aai_prompt": "dictation-email", "prompt_replacements": {"signoff": "Best, Sam"}}
+)
+```
+
+`llm` takes a dict or an `aai.DictationLLMRequest`, and rejects fields Dictation does not accept, such as `tools` or `stream`. The config is rejected before anything is sent when you set both `llm` and `llm_instruction`, set `max_tokens` or `max_completion_tokens` above 8192, or add any field or `rewrite_mode` to a saved prompt (only `prompt_replacements` may go with `aai_prompt`, and it can't set `text` or `transcript`).
+
+
+
Configure the dictation
@@ -817,7 +854,7 @@ config = aai.DictationConfig(
result = aai.DictationTranscriber().transcribe_live("./note.wav", config=config)
```
-`stt_prompt` describes the situation the audio was recorded in and steers the decoder as it writes the transcript; `llm_instruction` reshapes that transcript afterwards. `sample_rate` and `channels` are required only for raw PCM; WAV carries them in its own header. A config passed to `transcribe_live()` or `open_live()` overrides the transcriber's default config for that call. `DictationConfig` rejects unknown fields, so a typo or a sync-only option surfaces as a validation error instead of a setting that quietly does nothing.
+`stt_prompt` describes the situation the audio was recorded in and steers the decoder as it writes the transcript; `llm_instruction` (or your own `llm` request, never both) reshapes that transcript afterwards. `sample_rate` and `channels` are required only for raw PCM; WAV carries them in its own header. A config passed to `transcribe_live()` or `open_live()` overrides the transcriber's default config for that call. `DictationConfig` rejects unknown fields, so a typo or a sync-only option surfaces as a validation error instead of a setting that quietly does nothing.
diff --git a/assemblyai/__init__.py b/assemblyai/__init__.py
index d36a862..2f5162b 100644
--- a/assemblyai/__init__.py
+++ b/assemblyai/__init__.py
@@ -5,6 +5,7 @@
AsyncDictationTranscriber,
DictationConfig,
DictationError,
+ DictationLLMRequest,
DictationResponse,
DictationRewriteMode,
DictationTranscriber,
@@ -176,6 +177,7 @@ def __getattr__(name: str):
"CustomFormattingResponse",
"DictationConfig",
"DictationError",
+ "DictationLLMRequest",
"DictationResponse",
"DictationRewriteMode",
"DictationTranscriber",
diff --git a/assemblyai/__version__.py b/assemblyai/__version__.py
index d6a282f..fbe4793 100644
--- a/assemblyai/__version__.py
+++ b/assemblyai/__version__.py
@@ -1 +1 @@
-__version__ = "1.10.12"
+__version__ = "1.10.17"
diff --git a/assemblyai/dictation/__init__.py b/assemblyai/dictation/__init__.py
index edee556..c09caca 100644
--- a/assemblyai/dictation/__init__.py
+++ b/assemblyai/dictation/__init__.py
@@ -15,6 +15,7 @@
DictationConfig,
DictationError,
DictationLiveSession,
+ DictationLLMRequest,
DictationResponse,
DictationRewriteMode,
DictationTranscriber,
@@ -28,6 +29,7 @@
"AudioSource",
"DictationConfig",
"DictationError",
+ "DictationLLMRequest",
"DictationLiveSession",
"DictationResponse",
"DictationRewriteMode",
diff --git a/assemblyai/dictation/v1/__init__.py b/assemblyai/dictation/v1/__init__.py
index 219646d..e09f690 100644
--- a/assemblyai/dictation/v1/__init__.py
+++ b/assemblyai/dictation/v1/__init__.py
@@ -4,6 +4,7 @@
from .models import (
DictationConfig,
DictationError,
+ DictationLLMRequest,
DictationResponse,
DictationRewriteMode,
DictationWord,
@@ -16,6 +17,7 @@
"AudioSource",
"DictationConfig",
"DictationError",
+ "DictationLLMRequest",
"DictationLiveSession",
"DictationResponse",
"DictationRewriteMode",
diff --git a/assemblyai/dictation/v1/models.py b/assemblyai/dictation/v1/models.py
index 273f4bd..ab268af 100644
--- a/assemblyai/dictation/v1/models.py
+++ b/assemblyai/dictation/v1/models.py
@@ -5,16 +5,23 @@
"""
from enum import Enum
-from typing import List, Optional
+from typing import Any, Dict, List, Optional
try:
- # pydantic v2 import
- from pydantic import BaseModel, ConfigDict, Field, field_validator
+ # pydantic v2 import (`model_validator` exists only in v2; pydantic 1.10
+ # also exports `ConfigDict`, so it is not the probe)
+ from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ field_validator,
+ model_validator,
+ )
pydantic_v2 = True
except ImportError:
# pydantic v1 import (fallback for Python < 3.14)
- from pydantic import BaseModel, Field, validator
+ from pydantic import BaseModel, Field, root_validator, validator
pydantic_v2 = False
@@ -23,6 +30,7 @@
__all__ = [
"DictationConfig",
"DictationError",
+ "DictationLLMRequest",
"DictationResponse",
"DictationRewriteMode",
"DictationWord",
@@ -56,6 +64,8 @@ def __init__(
_DICTATION_MAX_KEYTERMS_COUNT = 100
_DICTATION_MAX_LLM_INSTRUCTION_LEN = 2048
_DICTATION_MAX_STT_PROMPT_LEN = 6000
+_DICTATION_MAX_LLM_OUTPUT_TOKENS = 8192
+_DICTATION_RESERVED_PROMPT_REPLACEMENTS = ("text", "transcript")
class DictationRewriteMode(str, Enum):
@@ -72,13 +82,148 @@ def __str__(self):
return self.value
+def _check_llm_request(values: Dict[str, Any]) -> Dict[str, Any]:
+ """
+ Raises on the `llm` combinations the Dictation API rejects with a 400.
+
+ A saved prompt runs as saved, so only `prompt_replacements` may come with
+ `aai_prompt`, and a replacement cannot take a name Dictation or LLM
+ Gateway fills itself.
+ """
+
+ replacements = values.get("prompt_replacements")
+ if values.get("aai_prompt") is None:
+ if replacements is not None:
+ raise ValueError("prompt_replacements requires aai_prompt")
+ return values
+
+ extra = sorted(
+ name
+ for name, value in values.items()
+ if value is not None and name not in ("aai_prompt", "prompt_replacements")
+ )
+ if extra:
+ raise ValueError(
+ f"a saved prompt runs as saved; drop {', '.join(extra)} or aai_prompt"
+ )
+
+ for key in _DICTATION_RESERVED_PROMPT_REPLACEMENTS:
+ if replacements and key in replacements:
+ raise ValueError(
+ f"prompt_replacements cannot set {key}: Dictation fills `text` "
+ "with the transcript and LLM Gateway reserves `transcript`"
+ )
+ return values
+
+
+class DictationLLMRequest(BaseModel):
+ """
+ An LLM Gateway request Dictation runs over the transcript, in place of
+ `llm_instruction`.
+
+ Either write the prompt yourself in `messages` or `prompt`, with
+ `{{turn}}` where the transcript goes, or name a saved prompt in
+ `aai_prompt` (it gets the transcript as `{{ text }}`). Every field is
+ optional, and unset fields are not sent. The rewrite comes back in
+ `DictationResponse.llm_response`.
+
+ Unknown fields are rejected: Dictation accepts this exact set and returns
+ a 400 for any other field, such as `fallbacks`, `tools`, `stream` or
+ `transcript_id`.
+ """
+
+ model: Optional[str] = None
+ """The LLM Gateway model. It must be one the Dictation rewrite runs on;
+ without it, `rewrite_mode` picks one. Not allowed with `aai_prompt`."""
+
+ messages: Optional[List[Dict[str, Any]]] = None
+ """Chat messages, as in an LLM Gateway chat completions request. Put
+ `{{turn}}` where the transcript goes."""
+
+ prompt: Optional[str] = None
+ "A single prompt, in place of `messages`. Put `{{turn}}` where the transcript goes."
+
+ temperature: Optional[float] = None
+ "Sampling temperature. Dictation uses 0 unless this is set."
+
+ top_p: Optional[float] = None
+ "Nucleus sampling cutoff."
+
+ top_k: Optional[int] = None
+ "Top-k sampling cutoff."
+
+ max_tokens: Optional[int] = Field(default=None, le=_DICTATION_MAX_LLM_OUTPUT_TOKENS)
+ """Output token limit, at most 8192. Unset, Dictation sizes it from the
+ transcript, so a prompt that expands the text may need a larger one. A
+ rewrite that runs out comes back with `llm_error` "truncated"."""
+
+ max_completion_tokens: Optional[int] = Field(
+ default=None, le=_DICTATION_MAX_LLM_OUTPUT_TOKENS
+ )
+ "Output token limit, at most 8192. The same limit under its other name."
+
+ response_format: Optional[Dict[str, Any]] = None
+ "The LLM Gateway `response_format`, e.g. a JSON schema for the output."
+
+ reasoning_effort: Optional[str] = None
+ "How much the model reasons before it answers, for models that support it."
+
+ aai_prompt: Optional[str] = None
+ """The name of a prompt saved in your account. The saved prompt's model
+ and settings apply, so only `prompt_replacements` may accompany it, and
+ `rewrite_mode` may not be set. An unknown name comes back as `llm_error`
+ "prompt_not_found"."""
+
+ prompt_replacements: Optional[Dict[str, Any]] = None
+ """Values for the `{{ tag }}` placeholders of the saved prompt. Requires
+ `aai_prompt`. `text` (the transcript) and `transcript` are reserved."""
+
+ zero_data_retention: Optional[bool] = None
+ """Accepted for parity with LLM Gateway. Dictation sets zero data
+ retention on every rewrite request regardless."""
+
+ if pydantic_v2:
+ model_config = ConfigDict(extra="forbid")
+
+ @model_validator(mode="after")
+ def _check_rules(self) -> "DictationLLMRequest":
+ _check_llm_request(dict(self))
+ return self
+
+ else:
+
+ class Config:
+ extra = "forbid"
+
+ @root_validator(skip_on_failure=True, allow_reuse=True)
+ def _check_rules(cls, values: Dict[str, Any]) -> Dict[str, Any]:
+ return _check_llm_request(values)
+
+
+def _check_rewrite_source(values: Dict[str, Any]) -> Dict[str, Any]:
+ """Raises when the config asks for the rewrite two ways at once."""
+
+ llm = values.get("llm")
+ if llm is None:
+ return values
+ if values.get("llm_instruction") is not None:
+ raise ValueError("set either llm_instruction or llm, not both")
+ if llm.aai_prompt is not None and values.get("rewrite_mode") is not None:
+ raise ValueError(
+ "rewrite_mode does not apply to a saved prompt (aai_prompt): "
+ "the saved prompt picks its own model"
+ )
+ return values
+
+
class DictationConfig(BaseModel):
"""
Options for a Dictation API request.
`language_codes`, `stt_prompt` and `keyterms_prompt` shape the
transcript; `llm_instruction` asks the server to run a follow-up LLM pass over it
- (the rewrite lands in `DictationResponse.llm_response`). `sample_rate`
+ (the rewrite lands in `DictationResponse.llm_response`), and `llm` sends
+ an LLM Gateway request of your own for that pass instead. `sample_rate`
and `channels` are required only for raw PCM audio — container formats
carry them in their own headers.
@@ -124,6 +269,13 @@ class DictationConfig(BaseModel):
"Format this as a SOAP note." The rewritten text comes back as
`llm_response`; the raw transcript stays in `text`. Max 2048 characters."""
+ llm: Optional[DictationLLMRequest] = None
+ """An LLM Gateway request of your own for the rewrite, in place of
+ `llm_instruction`: your own `messages` or `prompt` with `{{turn}}` where
+ the transcript goes, or a saved prompt by `aai_prompt`. A plain dict is
+ accepted. Set either this or `llm_instruction`, not both. The rewrite
+ comes back as `llm_response`."""
+
rewrite_mode: Optional[DictationRewriteMode] = None
"""Model tier that runs the rewrite: `fast` or `smart`. `smart` follows
detailed formatting instructions more reliably at higher latency. Defaults
@@ -132,6 +284,11 @@ class DictationConfig(BaseModel):
if pydantic_v2:
model_config = ConfigDict(extra="forbid")
+ @model_validator(mode="after")
+ def _check_rewrite(self) -> "DictationConfig":
+ _check_rewrite_source(dict(self))
+ return self
+
@field_validator("keyterms_prompt")
@classmethod
def _normalize_keyterms_prompt(cls, v):
@@ -154,6 +311,10 @@ def _normalize_keyterms_prompt(cls, v):
class Config:
extra = "forbid"
+ @root_validator(skip_on_failure=True, allow_reuse=True)
+ def _check_rewrite(cls, values: Dict[str, Any]) -> Dict[str, Any]:
+ return _check_rewrite_source(values)
+
@validator("keyterms_prompt")
def _normalize_keyterms_prompt(cls, v):
if not v:
@@ -194,8 +355,8 @@ class DictationResponse(BaseModel):
"Overall transcript confidence in the range 0-1."
llm_response: Optional[str] = None
- """The transcript rewritten by the LLM pass `llm_instruction` asked for.
- `None` when no instruction was sent or the pass failed."""
+ """The transcript rewritten by the LLM pass `llm_instruction` or `llm`
+ asked for. `None` when neither was sent or the pass failed."""
llm_error: Optional[str] = None
"Why the LLM pass failed, when it did. `None` otherwise."
@@ -222,8 +383,8 @@ def final_text(self) -> str:
"""
The text to show the user: the LLM rewrite when there is one.
- Falls back to the raw transcript when no `llm_instruction` was sent
- or the LLM pass failed, so reading it is safe either way.
+ Falls back to the raw transcript when neither `llm_instruction` nor
+ `llm` was sent or the LLM pass failed, so reading it is safe either way.
"""
return self.llm_response if self.llm_response is not None else self.text
diff --git a/tests/unit/test_dictation.py b/tests/unit/test_dictation.py
index f873fdf..632327c 100644
--- a/tests/unit/test_dictation.py
+++ b/tests/unit/test_dictation.py
@@ -8,6 +8,7 @@
import email
import io
+import json
import threading
from typing import List, Optional
@@ -671,6 +672,182 @@ def test_rewrite_mode_rejects_an_unknown_tier():
aai.DictationConfig(rewrite_mode="gemma")
+# --- own LLM request (`llm`) -------------------------------------------------
+
+
+def _config_json(httpx_mock: HTTPXMock) -> dict:
+ """The JSON `config` part of the one recorded request."""
+
+ request = httpx_mock.get_requests()[0]
+ request.read()
+ return json.loads(dict(_parts(request))["config"].get_payload(decode=True))
+
+
+def test_transcribe_live_sends_an_own_llm_request(httpx_mock: HTTPXMock):
+ # Given an LLM Gateway request of the caller's own, with {{turn}} where
+ # the transcript goes
+ _mock_ok(httpx_mock)
+ llm = {
+ "model": "gemma-4-31b",
+ "messages": [
+ {
+ "role": "system",
+ "content": "Rewrite the dictated note as a short, formal email.",
+ },
+ {"role": "user", "content": "{{turn}}"},
+ ],
+ }
+
+ # When streaming
+ aai.DictationTranscriber().transcribe_live(
+ _chunks(b"RIFF"), config=aai.DictationConfig(llm=llm)
+ )
+
+ # Then the config part carries it unchanged under `llm`
+ config = _config_json(httpx_mock)
+ assert config["llm"] == llm
+ assert "llm_instruction" not in config
+
+
+def test_transcribe_live_sends_a_saved_prompt(httpx_mock: HTTPXMock):
+ # Given a saved prompt with a replacement of the caller's own
+ _mock_ok(httpx_mock)
+ llm = {
+ "aai_prompt": "dictation-email",
+ "prompt_replacements": {"signoff": "Best, Sam"},
+ }
+
+ # When streaming
+ aai.DictationTranscriber().transcribe_live(
+ _chunks(b"RIFF"), config=aai.DictationConfig(llm=llm)
+ )
+
+ # Then the config part carries the saved-prompt request as given
+ assert _config_json(httpx_mock)["llm"] == llm
+
+
+def test_config_json_sends_only_set_llm_fields(httpx_mock: HTTPXMock):
+ # Given an llm request that sets only `prompt`
+ _mock_ok(httpx_mock)
+ config = aai.DictationConfig(llm={"prompt": "Fix punctuation: {{turn}}"})
+
+ # When streaming
+ aai.DictationTranscriber().transcribe_live(_chunks(b"RIFF"), config=config)
+
+ # Then no unset field leaks as null, and {{turn}} reaches the wire as
+ # written: the server fills it, not the SDK
+ assert _config_json(httpx_mock)["llm"] == {"prompt": "Fix punctuation: {{turn}}"}
+
+
+def test_empty_llm_is_sent_as_an_empty_object(httpx_mock: HTTPXMock):
+ # Given an llm request with nothing in it
+ _mock_ok(httpx_mock)
+
+ # When streaming
+ aai.DictationTranscriber().transcribe_live(
+ _chunks(b"RIFF"), config=aai.DictationConfig(llm={})
+ )
+
+ # Then it is sent as given: the docs name no rule for it, so the server
+ # decides
+ assert _config_json(httpx_mock)["llm"] == {}
+
+
+def test_llm_dict_is_coerced_to_the_typed_model():
+ # Given a plain dict
+ config = aai.DictationConfig(llm={"prompt": "{{turn}}"})
+
+ # Then it becomes the typed request
+ assert isinstance(config.llm, aai.DictationLLMRequest)
+ assert config.llm.prompt == "{{turn}}"
+
+
+@pytest.mark.parametrize(
+ "field", ["fallbacks", "tools", "stream", "transcript_id", "Model"]
+)
+def test_llm_rejects_undocumented_fields(field):
+ # Given a field Dictation's `llm` does not accept (names are
+ # case-sensitive)
+ # When building the request, then it is rejected rather than dropped
+ with pytest.raises(ValueError):
+ aai.DictationLLMRequest(**{"prompt": "{{turn}}", field: True})
+
+
+def test_llm_and_llm_instruction_together_raise():
+ # Given both ways of asking for a rewrite
+ # Then the config is rejected, as the API rejects it with a 400
+ with pytest.raises(ValueError, match="not both"):
+ aai.DictationConfig(
+ llm={"prompt": "{{turn}}"}, llm_instruction="Fix punctuation."
+ )
+
+
+@pytest.mark.parametrize("field", ["max_tokens", "max_completion_tokens"])
+def test_llm_output_token_cap(field):
+ # Given an output cap at the documented maximum, then it is accepted
+ aai.DictationConfig(llm={"prompt": "{{turn}}", field: 8192})
+
+ # And one over it is rejected
+ with pytest.raises(ValueError):
+ aai.DictationConfig(llm={"prompt": "{{turn}}", field: 8193})
+
+
+@pytest.mark.parametrize("field", ["max_tokens", "max_completion_tokens"])
+def test_llm_output_token_cap_has_no_floor(field):
+ # Given a value the docs do not forbid, below any useful size
+ config = aai.DictationConfig(llm={"prompt": "{{turn}}", field: 0})
+
+ # Then it is kept for the server to judge: the docs set only a maximum
+ assert getattr(config.llm, field) == 0
+
+
+def test_aai_prompt_rejects_other_llm_fields():
+ # Given a saved prompt with a setting the saved prompt already owns
+ # Then the config is rejected and names the field to drop
+ with pytest.raises(ValueError, match="saved prompt runs as saved; drop model"):
+ aai.DictationConfig(
+ llm={"aai_prompt": "dictation-email", "model": "gemma-4-31b"}
+ )
+
+
+def test_aai_prompt_rejects_rewrite_mode():
+ # Given a saved prompt and a rewrite tier
+ # Then the config is rejected: the saved prompt picks its own model
+ with pytest.raises(
+ ValueError, match="rewrite_mode does not apply to a saved prompt"
+ ):
+ aai.DictationConfig(llm={"aai_prompt": "dictation-email"}, rewrite_mode="smart")
+
+
+@pytest.mark.parametrize("key", ["text", "transcript"])
+def test_prompt_replacements_rejects_reserved_keys(key):
+ # Given a replacement Dictation or LLM Gateway fills itself
+ with pytest.raises(ValueError, match=f"prompt_replacements cannot set {key}"):
+ aai.DictationConfig(
+ llm={"aai_prompt": "dictation-email", "prompt_replacements": {key: "x"}}
+ )
+
+
+def test_prompt_replacements_requires_aai_prompt():
+ # Given replacements with no saved prompt to fill
+ with pytest.raises(ValueError, match="prompt_replacements requires aai_prompt"):
+ aai.DictationConfig(
+ llm={"prompt": "{{turn}}", "prompt_replacements": {"signoff": "Best, Sam"}}
+ )
+
+
+def test_rewrite_mode_with_an_own_llm_request_is_accepted():
+ # Given an own request without a model, and a rewrite tier
+ config = aai.DictationConfig(
+ llm={"messages": [{"role": "user", "content": "{{turn}}"}]},
+ rewrite_mode="smart",
+ )
+
+ # Then both stay: rewrite_mode picks the model when `llm` has none
+ assert config.rewrite_mode == aai.DictationRewriteMode.smart
+ assert config.llm.messages == [{"role": "user", "content": "{{turn}}"}]
+
+
def test_error_envelope_maps_to_dictation_error(httpx_mock: HTTPXMock):
# Given a server rejecting the audio with an {error, error_code} body
httpx_mock.add_response(
diff --git a/tests/unit/test_dictation_async.py b/tests/unit/test_dictation_async.py
index a47c1df..ee95e08 100644
--- a/tests/unit/test_dictation_async.py
+++ b/tests/unit/test_dictation_async.py
@@ -299,6 +299,25 @@ async def test_transcribe_live_uses_default_config_and_per_call_override(monkeyp
assert second["config"] == {"llm_instruction": "override instruction"}
+async def test_transcribe_live_sends_llm(monkeypatch):
+ # Given a config with an own LLM request
+ seen = _capture(monkeypatch)
+ llm = {
+ "model": "gemma-4-31b",
+ "messages": [{"role": "user", "content": "{{turn}}"}],
+ }
+
+ # When streaming
+ async with aai.AsyncDictationTranscriber() as transcriber:
+ await transcriber.transcribe_live(
+ _achunks(b"RIFF"), config=aai.DictationConfig(llm=llm)
+ )
+
+ # Then the config handed to the transport carries it under `llm`
+ (call,) = seen["calls"]
+ assert call["config"] == {"llm": llm}
+
+
async def test_transcribe_live_marks_pcm_from_config(monkeypatch):
# Given a config carrying the fields only raw PCM needs
seen = _capture(monkeypatch)