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.
Summary
Functions
Collapses an alias namespace into its primary and deep-merges the two sources.
The provider event to retain on a StreamEvent, or nil.
The provider payload to retain on a response or media response, or nil.
Normalizes a provider's error code to a string or nil.
Decodes a tool call's wire arguments into a map.
Normalizes a provider error envelope.
Decodes a provider's raw argument string into a map, or nil when it is not an
object.
Encodes tool-call arguments with the configured JSON module.
Encodes a tool call's arguments: raw_arguments wins, otherwise the decoded map
is encoded with the configured JSON module.
Validates then encodes a completion request as a POST with no query.
Builds a :validation error prefixed with the codec name.
Builds a LlmCall.StreamEvent, applying the capture_raw policy.
Returns the first {:error, _} a fun produces, or :ok.
Normalizes a provider-supplied resource id.
Normalizes a provider-supplied stream index.
Runs fun over items, stopping at the first error.
Puts a key unless the value is nil.
Reads a nested map field, or nil when any level is missing or not a map.
Builds a POST encoded request with no query parameters.
Returns :ok for nil and a validation error otherwise.
Reports whether a provider_options key would replace a canonical field.
The retry hint: true when the provider code is in the codec's retryable set.
Normalizes a provider-supplied token count.
Validates a reasoning effort against the protocol's supported levels.
Validates a media reference image source.
Runs a media adapter's validation pipeline.
Validates canonical messages: a non-empty list of user/assistant turns, each with a non-empty content list.
Validates the requested output modalities.
Validates a media request's modality.
Validates that a model id is a non-empty string.
Validates a Gemini-style bare model id.
Validates params.n against the codec's declared maximum.
Validates the types of known native provider options.
Validates that a provider-options namespace only contains keys a codec can forward without replacing a canonical field.
Validates a provider-options container against the namespaces a codec consumes.
Checks that a provider_options namespace is a map.
Validates the response format shared by OpenAI-style protocols.
Validates that a params map only contains supported keys.
Validates that params is a map and only contains supported keys.
Validates every content part in every message, applying the shared role rules
before the codec's shape_fun.
Validates that a media prompt is a non-empty string.
Validates that a content part may appear in that role.
Validates the system field: nil, a string, or a list of text parts.
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.
Validates the tool choices whose native shapes match across OpenAI-style
protocols: :auto, :none, :required, and {:tool, name}.
Validates tool-result content: a string or a list of text parts.
Validates a tool spec.
Validates the tool list and delegates the tool-choice rules to the codec.
Types
@type codec() :: atom()
Functions
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.
@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.
@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.
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.
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.
@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.
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.
@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.
@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.
@spec encode_completion( LlmCall.Request.t(), LlmCall.Config.t(), String.t(), [{String.t(), String.t()}], (LlmCall.Request.t(), LlmCall.Config.t() -> :ok | {:error, LlmCall.Error.t()}), (LlmCall.Request.t(), LlmCall.Config.t() -> {: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.
@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.
@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.
@spec first_error([term()], (term() -> :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.
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.
@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.
@spec map_ok([term()], (term() -> {: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, _}.
Puts a key unless the value is nil.
Dialect bodies omit absent fields rather than sending JSON nulls.
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.
@spec post(String.t(), [{String.t(), String.t()}], map()) :: LlmCall.EncodedRequest.t()
Builds a POST encoded request with no query parameters.
@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.
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"}.
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.
@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.
@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.
@spec validate_media_reference(term(), codec()) :: :ok | {:error, LlmCall.Error.t()}
Validates a media reference image source.
@spec validate_media_request( LlmCall.Media.Request.t(), LlmCall.Config.t(), codec(), :image | :video, (LlmCall.model() | nil, codec() -> :ok | {:error, LlmCall.Error.t()}), (map() -> :ok | {:error, LlmCall.Error.t()}), (term() -> :ok | {:error, LlmCall.Error.t()}), (LlmCall.Media.Request.t(), LlmCall.Config.t() -> :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.
@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.
@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.
@spec validate_modality(term(), :image | :video, codec()) :: :ok | {:error, LlmCall.Error.t()}
Validates a media request's modality.
@spec validate_model(LlmCall.model() | nil, codec()) :: :ok | {:error, LlmCall.Error.t()}
Validates that a model id is a non-empty string.
@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.
@spec validate_n(pos_integer() | nil, pos_integer() | :unsupported, codec()) :: :ok | {:error, LlmCall.Error.t()}
Validates params.n against the codec's declared maximum.
@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.
@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.
@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?: trueone 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/2is 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.
@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.
@spec validate_output(LlmCall.Request.output(), codec()) :: :ok | {:error, LlmCall.Error.t()}
Validates the response format shared by OpenAI-style protocols.
@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.
@spec validate_params(term(), [atom()], codec()) :: :ok | {:error, LlmCall.Error.t()}
Validates that params is a map and only contains supported keys.
@spec validate_parts([LlmCall.Message.t()], codec(), (LlmCall.Message.role(), LlmCall.Content.part() -> :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.
@spec validate_prompt(String.t() | nil, codec()) :: :ok | {:error, LlmCall.Error.t()}
Validates that a media prompt is a non-empty string.
@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.
@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.
@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.
@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}.
@spec validate_tool_result_content(term(), codec()) :: :ok | {:error, LlmCall.Error.t()}
Validates tool-result content: a string or a list of text parts.
@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.
@spec validate_tools( [LlmCall.ToolSpec.t()], LlmCall.Request.tool_choice(), codec(), (LlmCall.ToolSpec.t() -> :ok | {:error, LlmCall.Error.t()}), (term(), [LlmCall.ToolSpec.t()] -> :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.