# `LlmCall.Dialect.Helpers`
[🔗](https://github.com/gilbertwong96/llm_call/blob/main/lib/llm_call/dialect/helpers.ex#L1)

Validation and encoding primitives shared by dialect adapters.

This is the public adapter-authoring surface: core's reference adapters and the
vendored media adapters call it, so a change to the error shape, the
reserved-key rule, or the `capture_raw` policy lands in one place.
Reimplementing these in a package would produce adapters that
`LlmCall.Codec.Conformance` cannot check consistently.

The composite entry points — `encode_completion/6`, `validate_media_request/8`,
and `validate_parts/3` — are what most adapters call. The individual checks
(`validate_model/2`, `validate_modalities/3`, `validate_option_map/4`,
`validate_tool_call_arguments/3`, ...) are public so a codec with an unusual
pipeline can compose them instead of copying them; only some of them are used
by every adapter. Four exist for a codec that reimplements a pipeline step:
`capture_event/2`, `reserved_key?/2`, `validate_modality/3`, and
`validate_prompt/2`.

A codec's own name is injected as `@codec` by the adapter macros; pass it to
`error/2`, `reject/3`, and `validate_options/3`, so every validation message is
prefixed with the codec that rejected the request.

# `codec`

```elixir
@type codec() :: atom()
```

# `alias_options`

```elixir
@spec alias_options(map(), map(), atom(), atom()) :: map()
```

Collapses an alias namespace into its primary and deep-merges the two sources.

Gemini accepts both `:gemini` and its `:google` alias, and each source may use
either spelling. Collapsing per source before merging keeps the documented
rule — a request value wins over a config default — even when the two disagree
on the name, and deep-merging lets a request extend a defaulted native object
instead of replacing it.

# `capture_event`

```elixir
@spec capture_event(LlmCall.Config.t(), term()) :: map() | nil
```

The provider event to retain on a `StreamEvent`, or `nil`.

`capture_raw: :all` keeps every chunk; `:none` and `:response` keep none.

# `capture_response`

```elixir
@spec capture_response(LlmCall.Config.t(), term()) :: map() | nil
```

The provider payload to retain on a response or media response, or `nil`.

`:response` and `:all` keep it; `:none` does not.

# `code`

```elixir
@spec code(term()) :: String.t() | nil
```

Normalizes a provider's error code to a string or `nil`.

Providers type this field inconsistently (a string for OpenAI and Google, an
integer for MiniMax); `LlmCall.Error.code` is always a string so callers can
compare it without type juggling.

# `decode_arguments`

```elixir
@spec decode_arguments(term(), module()) ::
  {map() | nil, nil | {:invalid_json, String.t()}}
```

Decodes a tool call's wire arguments into a map.

Returns `{arguments, nil}` or `{nil, {:invalid_json, reason}}`; `reason` is a
message, not the payload, and the caller keeps the payload it passed in.

# `decode_provider_error`

```elixir
@spec decode_provider_error(term(), LlmCall.Config.t(), codec(), [String.t()], [
  String.t()
]) ::
  LlmCall.Error.t()
```

Normalizes a provider error envelope.

`code_keys` names the fields that may carry the provider's machine code, in
priority order (OpenAI and Seedance use `code` then `type`, Anthropic `type`,
Google `status`). `retryable_codes` is the codec's own retryable set, and
`Error.raw` follows `capture_raw`.

# `decode_raw_arguments`

```elixir
@spec decode_raw_arguments(String.t() | nil, module()) :: map() | nil
```

Decodes a provider's raw argument string into a map, or `nil` when it is not an
object.

Providers that hand arguments over as a JSON string (Anthropic, some Gemini
shapes) share this so a malformed fragment never becomes `%{}`. `json` is the
module from `LlmCall.Config.json`, threaded so a caller's implementation is
used here too.

# `encode_arguments`

```elixir
@spec encode_arguments(map(), codec(), module()) ::
  {:ok, String.t()} | {:error, LlmCall.Error.t()}
```

Encodes tool-call arguments with the configured JSON module.

`validate_request/2` has already proven this succeeds; the error tuple exists so
a codec never raises on a custom implementation that behaves differently.

# `encode_call_arguments`

```elixir
@spec encode_call_arguments(LlmCall.ToolCall.t(), codec(), module()) ::
  {:ok, String.t()} | {:error, LlmCall.Error.t()}
```

Encodes a tool call's arguments: `raw_arguments` wins, otherwise the decoded map
is encoded with the configured JSON module.

# `encode_completion`

```elixir
@spec encode_completion(
  LlmCall.Request.t(),
  LlmCall.Config.t(),
  String.t(),
  [{String.t(), String.t()}],
  (LlmCall.Request.t(), LlmCall.Config.t() -&gt;
     :ok | {:error, LlmCall.Error.t()}),
  (LlmCall.Request.t(), LlmCall.Config.t() -&gt;
     {:ok, map()} | {:error, LlmCall.Error.t()})
) :: {:ok, LlmCall.EncodedRequest.t()} | {:error, LlmCall.Error.t()}
```

Validates then encodes a completion request as a `POST` with no query.

# `error`

```elixir
@spec error(codec(), String.t()) :: {:error, LlmCall.Error.t()}
```

Builds a `:validation` error prefixed with the codec name.

The single constructor for validation errors, so a package cannot drift on the
`kind` or the message shape the conformance suite expects.

# `event`

```elixir
@spec event(
  LlmCall.StreamEvent.type(),
  LlmCall.StreamEvent.index(),
  LlmCall.StreamEvent.delta(),
  term(),
  LlmCall.Config.t()
) :: LlmCall.StreamEvent.t()
```

Builds a `LlmCall.StreamEvent`, applying the `capture_raw` policy.

`term` is the provider payload the event came from; it is kept only when
`capture_raw: :all`.

# `first_error`

```elixir
@spec first_error([term()], (term() -&gt; :ok | {:error, LlmCall.Error.t()})) ::
  :ok | {:error, LlmCall.Error.t()}
```

Returns the first `{:error, _}` a `fun` produces, or `:ok`.

Validation is written as a pipeline of checks; this preserves the first failure
instead of reporting the last.

# `id`

```elixir
@spec id(term()) :: String.t() | nil
```

Normalizes a provider-supplied resource id.

Providers mix string and numeric ids (MiniMax returns `file_id` as either). A
non-empty string is kept, an integer is stringified, and anything else becomes
`nil`, so an `Operation.id` or `Error.code` never violates its declared type.

# `index`

```elixir
@spec index(term()) :: non_neg_integer() | nil
```

Normalizes a provider-supplied stream index.

A non-negative integer is kept; anything else (a string, a float, a negative
number) becomes `nil`, so a malformed index cannot violate
`LlmCall.StreamEvent.index` or crash `LlmCall.StreamAssembler`.

# `map_ok`

```elixir
@spec map_ok([term()], (term() -&gt; {:ok, term()} | {:error, LlmCall.Error.t()})) ::
  {:ok, [term()]} | {:error, LlmCall.Error.t()}
```

Runs `fun` over `items`, stopping at the first error.

Used where a body builds a list of encoded parts and any part can fail: the
result is `{:ok, values}` in input order, or the first `{:error, _}`.

# `maybe_put`

```elixir
@spec maybe_put(map(), term(), term()) :: map()
```

Puts a key unless the value is `nil`.

Dialect bodies omit absent fields rather than sending JSON nulls.

# `nested`

```elixir
@spec nested(term(), [String.t()]) :: term()
```

Reads a nested map field, or `nil` when any level is missing or not a map.

`get_in/2` raises when an intermediate value is not an `Access` container; a
provider can send `"prompt_tokens_details": "10"`, so usage decoding reads
through this instead.

# `post`

```elixir
@spec post(String.t(), [{String.t(), String.t()}], map()) ::
  LlmCall.EncodedRequest.t()
```

Builds a `POST` encoded request with no query parameters.

# `reject`

```elixir
@spec reject(term(), codec(), String.t()) :: :ok | {:error, LlmCall.Error.t()}
```

Returns `:ok` for `nil` and a validation error otherwise.

For canonical fields a protocol has no equivalent for: absent is fine, present
is refused.

# `reserved_key?`

```elixir
@spec reserved_key?(term(), [String.t()]) :: boolean()
```

Reports whether a `provider_options` key would replace a canonical field.

Keys are normalised to strings and downcased, so `%{prompt: "x"}` is caught as
well as `%{"prompt" => "x"}`.

# `retryable?`

```elixir
@spec retryable?(term(), [String.t()]) :: boolean()
```

The retry hint: true when the provider code is in the codec's retryable set.

Adapters keep their own set — providers name their codes differently — but
share this rule and its `nil` handling, so the hint means the same thing
everywhere.

# `token`

```elixir
@spec token(term()) :: non_neg_integer() | nil
```

Normalizes a provider-supplied token count.

A non-negative integer is kept; anything else (a stringified count, a float, an
object) becomes `nil`, so a malformed usage field cannot violate
`LlmCall.Usage.tokens` or break arithmetic on it.

# `validate_effort`

```elixir
@spec validate_effort(
  LlmCall.Reasoning.effort(),
  [LlmCall.Reasoning.level()],
  codec()
) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates a reasoning effort against the protocol's supported levels.

# `validate_media_reference`

```elixir
@spec validate_media_reference(term(), codec()) :: :ok | {:error, LlmCall.Error.t()}
```

Validates a media reference image source.

# `validate_media_request`

```elixir
@spec validate_media_request(
  LlmCall.Media.Request.t(),
  LlmCall.Config.t(),
  codec(),
  :image | :video,
  (LlmCall.model() | nil, codec() -&gt; :ok | {:error, LlmCall.Error.t()}),
  (map() -&gt; :ok | {:error, LlmCall.Error.t()}),
  (term() -&gt; :ok | {:error, LlmCall.Error.t()}),
  (LlmCall.Media.Request.t(), LlmCall.Config.t() -&gt;
     :ok | {:error, LlmCall.Error.t()})
) :: :ok | {:error, LlmCall.Error.t()}
```

Runs a media adapter's validation pipeline.

The shared steps are modality, model, prompt, and the codec's own param,
reference, and provider-option checks, passed as functions so each codec keeps
its protocol-specific rules.

# `validate_messages`

```elixir
@spec validate_messages([LlmCall.Message.t()], codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates canonical messages: a non-empty list of user/assistant turns, each
with a non-empty content list.

# `validate_modalities`

```elixir
@spec validate_modalities([LlmCall.modality()], [LlmCall.modality()], codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates the requested output modalities.

`allowed` is the protocol's output surface: OpenAI Chat and Anthropic accept
text only, Gemini also accepts images. Anything outside `[:text, :image,
:video]` or duplicated is a structural error.

# `validate_modality`

```elixir
@spec validate_modality(term(), :image | :video, codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates a media request's modality.

# `validate_model`

```elixir
@spec validate_model(LlmCall.model() | nil, codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates that a model id is a non-empty string.

# `validate_model_id`

```elixir
@spec validate_model_id(LlmCall.model() | nil, codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates a Gemini-style bare model id.

The model is interpolated into a request path, so only characters that are
safe in one path segment are accepted. A `/`, `:`, `?`, `#`, whitespace, or
percent-encoded separator would build a different endpoint than the caller
asked for.

# `validate_n`

```elixir
@spec validate_n(pos_integer() | nil, pos_integer() | :unsupported, codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates `params.n` against the codec's declared maximum.

# `validate_native_options`

```elixir
@spec validate_native_options(map(), map(), codec(), String.t()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates the types of known native provider options.

`schema` maps a native key (string or atom) to `:boolean`, `:string`, `:map`,
`:list`, `:number`, `:integer`, or `{:enum, values}`. Unknown keys pass: a
provider may add a field before the codec learns about it.

# `validate_option_keys`

```elixir
@spec validate_option_keys(map(), [String.t()], codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates that a provider-options namespace only contains keys a codec can
forward without replacing a canonical field.

# `validate_option_map`

```elixir
@spec validate_option_map(term(), codec(), String.t(), [atom()], keyword()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates a provider-options container against the namespaces a codec consumes.

Three things must hold, or the caller would get a valid-looking request whose
options are silently ignored or would raise later:

  * the container is a map;
  * every key is an atom, and with `strict?: true` one the codec reads
    (`:openai`, `[:gemini, :google]`, ...) — a typo or a string key is an error,
    not a drop;
  * every present declared namespace holds a map, so
    `LlmCall.Config.deep_merge/2` is never handed a non-map.

Pass `strict?: false` for `Config.default_provider_options`: a default map is
application-wide and legitimately carries namespaces for other providers, so
only the namespaces this codec reads are checked.

# `validate_options`

```elixir
@spec validate_options(term(), codec(), String.t()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Checks that a `provider_options` namespace is a map.

Adapters reject a malformed namespace rather than ignoring it.

# `validate_output`

```elixir
@spec validate_output(LlmCall.Request.output(), codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates the response format shared by OpenAI-style protocols.

# `validate_param_keys`

```elixir
@spec validate_param_keys(map(), [atom()], codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates that a `params` map only contains supported keys.

A `nil` value means "provider default" and is ignored; an unsupported key with
a value is a validation error, never a silent drop.

# `validate_params`

```elixir
@spec validate_params(term(), [atom()], codec()) :: :ok | {:error, LlmCall.Error.t()}
```

Validates that `params` is a map and only contains supported keys.

# `validate_parts`

```elixir
@spec validate_parts([LlmCall.Message.t()], codec(), (LlmCall.Message.role(),
                                                LlmCall.Content.part() -&gt;
                                                  :ok
                                                  | {:error, LlmCall.Error.t()})) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates every content part in every message, applying the shared role rules
before the codec's `shape_fun`.

Dialect-specific role rules (for example OpenAI rejecting images in assistant
turns) stay in the codec's own `validate_part/2`.

# `validate_prompt`

```elixir
@spec validate_prompt(String.t() | nil, codec()) :: :ok | {:error, LlmCall.Error.t()}
```

Validates that a media prompt is a non-empty string.

# `validate_role`

```elixir
@spec validate_role(LlmCall.Message.role(), LlmCall.Content.part(), codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates that a content part may appear in that role.

Tool calls and thinking belong to assistant turns, tool results to user turns;
everything else is the protocol's business.

# `validate_system`

```elixir
@spec validate_system(LlmCall.Request.system(), codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates the system field: `nil`, a string, or a list of text parts.

# `validate_tool_call_arguments`

```elixir
@spec validate_tool_call_arguments(LlmCall.ToolCall.t(), codec(), module()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates a tool call's arguments: a decoded map, or a raw string that decodes
to an object. A malformed fragment is an error, never `%{}`. A map that the
configured JSON module cannot encode is an error too, because the codec has to
emit it as a string.

# `validate_tool_choice`

```elixir
@spec validate_tool_choice(
  LlmCall.Request.tool_choice(),
  [LlmCall.ToolSpec.t()],
  codec()
) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates the tool choices whose native shapes match across OpenAI-style
protocols: `:auto`, `:none`, `:required`, and `{:tool, name}`.

# `validate_tool_result_content`

```elixir
@spec validate_tool_result_content(term(), codec()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates tool-result content: a string or a list of text parts.

# `validate_tool_spec`

```elixir
@spec validate_tool_spec(LlmCall.ToolSpec.t(), codec(), keyword()) ::
  :ok | {:error, LlmCall.Error.t()}
```

Validates a tool spec.

`strict: true` lets the protocol forward `strict`; otherwise a non-nil value is
rejected. `options: true` lets the protocol forward `provider_options`.

# `validate_tools`

```elixir
@spec validate_tools(
  [LlmCall.ToolSpec.t()],
  LlmCall.Request.tool_choice(),
  codec(),
  (LlmCall.ToolSpec.t() -&gt; :ok | {:error, LlmCall.Error.t()}),
  (term(), [LlmCall.ToolSpec.t()] -&gt; :ok | {:error, LlmCall.Error.t()})
) :: :ok | {:error, LlmCall.Error.t()}
```

Validates the tool list and delegates the tool-choice rules to the codec.

`spec_validator` is the codec's `validate_tool_spec/1`; `choice_validator` is
its `validate_tool_choice/2`, which owns the per-protocol choice union.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
