ExAgent.Models.ReqLLM (ExAgent v3.0.0)

View Source

Model adapter over ReqLLM's public one-interaction APIs (generate_text/3, stream_text/3 and StreamResponse.process_stream/2), used as published.

Stability — Stable.

Construction

new/1 takes :model (a catalogue string such as "anthropic:claude-sonnet-5-5", an LLMDB.Model or an explicit model spec) and validates every option offline, raising ArgumentError that names the key. It resolves the catalogue locally, without IO, and stores a concrete :profile and :reasoning_mode. Ollama, LM Studio and vLLM deployment IDs without a catalogue entry resolve through stock's inline model spec. The instance stores a resolved LLMDB.Model for these providers.

ExAgent.Models.ReqLLM.new(model: "openai:gpt-5.5", api_key: key,
  reasoning_mode: :enabled, reasoning_effort: "medium", total_timeout: 120_000)

ExAgent.new(model: "provider:id") builds the same instance and, without explicit credentials, reads the provider's key on each request through ReqLLM.Keys (the :api_key option, then config :req_llm, then the provider's environment variable such as ANTHROPIC_API_KEY). The key is never stored in the struct, the continuation binding or a snapshot. An instance built with new/1 takes an explicit :api_key or Anthropic :auth_token (an OAuth bearer that takes precedence over :api_key). A missing required key fails with :missing_credentials before IO. Stock Ollama Chat Completions is credential-free. Azure OpenAI also reads AZURE_OPENAI_API_KEY and AZURE_OPENAI_BASE_URL. Vertex uses stock ADC or the host's provider configuration and accepts an explicit :auth_token. The one-line form for Bedrock InvokeModel reads AWS_BEARER_TOKEN_BEDROCK.

Profiles

profile: :auto (the default) picks the profile from the provider and the wire surface declared by the catalogue or fixed by the stock provider. An explicit profile must equal it, or be :text_v1.

Profile:auto whenTools and streamoutput_mode: :nativeReasoning
:chat_tools_v1:openai with openai_chatyesyes:disabled
:chat_tools_v1Ollama, LM Studio, vLLM, Groq, DeepSeek, Mistral and xAI Chat Completionsyesno:disabled
:chat_tools_v1:azure with OpenAI Chat Completionsyesno:disabled
:openrouter_chat_tools_v1:openrouteryesnoboth
:openai_responses_v1:openai or Azure OpenAI, wire openai_responsesyesyesboth
:anthropic_messages_v1:anthropicyeswith catalogue json.schemaboth
:anthropic_messages_v1:google_vertex Claudeyesnoboth
:anthropic_messages_v1:amazon_bedrock Claude on InvokeModel with catalogue toolsyesnoboth
:gemini_v1:google or :google_vertex Geminiyesnoboth
:text_v1any other provider, or :openai without wirebuffered text onlynocatalogue default

A Bedrock instance with its own :api_key requires provider_options: [region: ...]. The one-line form takes the region from AWS_REGION and defaults to us-east-1. Claude with catalogue tools uses InvokeModel. Bedrock Converse stays on :text_v1 because stock ReqLLM can merge distinct tool calls and discard execution ownership.

Cerebras resolves to :text_v1 because stock rewrites constraints inside the wrapped argument schema.

The wire is the one ReqLLM.model/1 declares: stock itself declares openai_responses for the OpenAI ids it routes to Responses (o-series, gpt-4o, gpt-4.1, gpt-5), so the profile follows the endpoint stock will call. Google models resolve to :gemini_v1; profile: :text_v1 keeps the 2.x buffered text path. An agent's output_mode: :prompted reaches every profile, :text_v1 included, as a text request whose instructions carry the schema. Tools need tools.enabled in the catalogue. Stock Ollama, LM Studio and vLLM also admit tool requests for local model IDs without catalogue capabilities. The host qualifies the deployed model's behavior. Chat Completions rejects a catalogue tools.strict. Tools are sent with strict: false, except on :openai_responses_v1 when the envelope schema stays the same under OpenAI strict mode: every object property required, no other properties, and only type, properties, required, additionalProperties, items, anyOf, enum, minItems/maxItems, numeric bounds, pattern, description and title. In both cases, the arguments must be a complete JSON object containing only the "arguments" object before a call can run. Duplicate keys can be rejected when stock passes through the original argument string, currently on buffered Responses. Stock normalizes arguments on other tool routes before ExAgent can check for duplicates.

Reasoning

reasoning_mode is :disabled or :enabled. When omitted it resolves to :disabled if the model can turn reasoning off (reasoning.enabled is not true, or the catalogue declares how to disable it) and to :enabled otherwise, for example gpt-5.5 or Claude Opus 5.5. An explicit :disabled the model cannot honour, or :enabled on a profile that cannot replay reasoning, raises. :disabled sends the catalogue's off control (reasoning_effort: none, Anthropic's off thinking type) when supported. A provider may still return reasoning. reasoning_effort is a string from the catalogue's effort.values (one of minimal, low, medium, high, xhigh, max) and requires :enabled.

  • Anthropic. Signed thinking and redacted_thinking blocks are stored in the response continuation and replayed byte for byte with the same tool_use.input. With :enabled, a forced tool choice becomes auto (stock would silently drop thinking), and the loop's output retries enforce required output. A fixed thinking budget that does not fit max_tokens rejects with {:unsupported, :thinking_budget} instead of stock's silent enlargement. Native output, when the catalogue declares json.schema, sends output_config.format with a copy of the schema reduced to what constrained decoding accepts (closed objects, no numeric or length bounds, pattern, maxItems or minItems above 1); the full schema is still checked locally. Dynamic or free-form object keys, tuples and untyped values cannot be expressed and raise in ExAgent.new/1.
  • OpenAI Responses. Always store: false with include: ["reasoning.encrypted_content"]; previous_response_id is never sent. Encrypted reasoning items are replayed from the continuation. Native output uses text.format with strict: false. max_tokens is sent as max_completion_tokens and must be at least 16. Stock reads every status but incomplete as a stop; here only completed can authorize tools or output. failed is :error, cancelled is :cancelled and other non-completed statuses with a success finish become :incomplete. Responses has no sampling controls in stock, so temperature, top_p and penalties reject.
  • OpenRouter. :enabled replays stock reasoning_details unchanged and never forces a tool choice. Bounded openrouter_provider routing and app_title/app_referer attribution are bound to the continuation.
  • Chat Completions. :chat_tools_v1 keeps plain, unsigned thinking in Part.Thinking and emits :thinking_delta when stock emits thinking chunks. It omits these parts when sending history. Provider reasoning_details and opaque or signed thinking reject. OpenAI Chat on a reasoning model sends reasoning_effort: none and max_completion_tokens; it requires a nil temperature and max_tokens in 1..4096 (default 4096).
  • Gemini. Thought signatures on thought, text and function-call parts are stored in the continuation by part and replayed byte for byte on their own part; a part whose signature differs from the continuation, or a lost one, fails :invalid_history before IO. With :enabled, a response whose first function call is unsigned rejects before any effect, because Gemini requires that signature back. Gemini signs only the first of parallel calls: stock sends its documented placeholder signature on the others and on portable foreign calls. Call ids are not replayed. reasoning_effort becomes thinkingLevel on Gemini 3 and a thinking budget on 2.5. Only finishReason: STOP can authorize tools or output: stock reads a missing reason, or a blocked prompt without candidates, as a stop; here they are :incomplete. A named tool choice is sent as ANY with allowedFunctionNames (stock would silently send AUTO for any other form), and presence_penalty/frequency_penalty reject (stock drops them). Stock removes additionalProperties from declared schemas, so the local envelope check is the only guard against extra keys. There is no native output: stock sends a response schema only from its :object operation, whose decoding joins thought text into the JSON and reads a blocked prompt as a stop.

Tools, envelope and history

Each tool is declared under a mandatory {"arguments": {...}} envelope with additionalProperties: false, and one backend-only system message explains it. A complete, unique-key object with the wrong envelope shape blocks the entire batch. The run can return a correction using its existing tool or output retry budget. Unparseable JSON, non-object JSON, observable duplicate keys and explicit stock argument errors fail immediately. The core validates the logical schema and tool name after envelope admission.

History replays an enveloped call as exagent.arguments/1. A call rejected for its envelope shape uses exagent.raw_arguments/1 in its metadata and replays the original object as received. Both call codecs work with the v5 continuation. Persisted Composition and Flow leaves fail immediately on an invalid envelope.

Each response stores a closed, versioned continuation (v5: profile, target, mode, effort, routing, codec, metadata and provider reasoning). A response is native when its continuation is valid and matches this instance. The profile controls which parts are sent back. Otherwise it is foreign, including a response without continuation (from ExAgent.Models.Test or a custom model), except a text-only response without continuation, which loses nothing. With foreign_history: :reject (the default) a foreign response fails with {:continuation_mismatch, :target | :routing | :mode} before IO; with :portable it is sent as text and tool calls without reasoning or signatures. Continuations written by 2.x (v1-v4) are still read.

On models with reasoning_binding: :prefix, the adapter replays native reasoning only after checking the earlier input and consecutive reasoning blocks. If a projected request changes that input, it retires the invalid blocks and their predecessors. The canonical history retains the provider response. A reset emits [:exagent, :model, :reasoning_prefix, :reset].

Time, streaming and limits

total_timeout bounds one operation, buffered or streamed: 120,000 ms by default, 1..300,000. A host guardian applies the earlier of the run and operation deadlines and owns one linked worker; ReqLLM's own total timeout is disabled to avoid orphaned work. The receive timeout (inactivity) is ModelSettings.timeout, then http_options[:receive_timeout], then 60 s, capped by the run deadline.

Streaming needs a tool profile and no http_options[:adapter]. It defaults to max_tokens: 4096 and rejects values outside 1..4096. Deltas, including {:thinking_delta, text} and {:commentary_delta, text}, are provisional: only the validated terminal authorizes tools or output. The stream admits at most 4096 public chunks, 65,536 bytes per chunk and 1,048,576 bytes in total, measured after decode with :erlang.external_size/1; this is not a predecode RAM limit or end-to-end backpressure. Halt, exception, deadline and owner death close the backend response and terminate owned work.

Accounting

Usage is Usage.accounting quality "normalized"; metrics stock does not report stay nil, and a report of zero input and zero output alongside output is unknown, not zero. Stock fills omitted counters with zero, so a dimension is "available" only with evidence: stock's usage_reported flag where it exists (input and output on every built-in wire, cache read and write on Anthropic), else a positive cache count. Reasoning needs the provider's own detail (Responses output_tokens_details.reasoning_tokens, a Chat completion_tokens_details count other than the whole completion); Anthropic reports no thinking count, so it is never available there. A zero without evidence is "unavailable" and nil.

The tool profiles state their semantics: Chat, OpenRouter, Responses and Gemini input includes cached tokens ("inclusive"), Anthropic input excludes them ("exclusive_cache"), and output includes reasoning. :text_v1 keeps stock's, unknown when absent. USD totals are estimates converted once to cents. A total computed while a billed dimension is unavailable is a "partial" cost (cents nil, subtotal_cents kept), and with no billed dimension available the cost is "unavailable"; cache counts are billed unless input is inclusive and the catalogue has no cache rate. A provider-reported charge (OpenRouter cost) stays available. Strict metric limits reject this contract before IO.

Other options

:base_url selects an instance or gateway. :http_options accepts :adapter (trusted transport injection, buffered only) and :receive_timeout. :provider_options accepts Anthropic :anthropic_version ("2023-06-01") and :stop_sequences, and OpenRouter routing and attribution. The Responses profile accepts candidate :reasoning_summary (:auto, :concise, :detailed or the corresponding strings) with reasoning_mode: :enabled. It requests provider summaries without changing the continuation binding. Non-empty provider-option defaults from application configuration or model extra reject before IO. :service_tier is an OpenAI request preference. It accepts "auto", "default", "flex", "priority", "fast", "ultrafast" and "scale" or the corresponding atoms. Flex requires a matching OpenAI request mapping in the resolved LLMDB model. A model or API without that eligibility raises ArgumentError in new/1. Request preflight returns a %ExAgent.RequestError{reason: {:invalid_option, :service_tier}} before IO if the adapter reaches it with an ineligible tier. Only the provider's returned tier is used for pricing.

:service_tier and :prompt_cache are outside the continuation binding. OpenRouter and Anthropic take true or [ttl: "5m" | "1h"]. OpenAI takes true or [key: key]. Models supporting prompt_cache_options may add ttl: "30m" for implicit caching, or ttl: "12h" on Responses. Cache writes with a "12h" policy leave a partial cost when the catalogue lacks that rate. OpenRouter marks the last system message and the newest message. Anthropic uses stock ReqLLM's breakpoints on the last tool, the last system block and the newest message, so each request reads the prefix the previous one wrote; cache reads and writes are reported as exact usage. Gemini caches implicitly: cached prompt tokens are reported as cache_read without configuration, and :prompt_cache rejects.

Summary

Functions

Stateless continuation codec. Credentials and client configuration come from the host's freshly constructed adapter on restore.

Build an adapter instance; :model is required.

Types

profile()

@type profile() ::
  :chat_tools_v1
  | :openrouter_chat_tools_v1
  | :openai_responses_v1
  | :anthropic_messages_v1
  | :gemini_v1
  | :text_v1

t()

@type t() :: %ExAgent.Models.ReqLLM{
  api_key: String.t() | nil,
  auth_token: String.t() | nil,
  base_url: String.t() | nil,
  credentials: :instance | :environment,
  foreign_history: :reject | :portable,
  http_options: keyword(),
  model: String.t() | map() | tuple(),
  profile: :auto | profile(),
  prompt_cache: boolean() | keyword() | nil,
  provider_options: keyword(),
  reasoning_effort: String.t() | nil,
  reasoning_mode: :disabled | :enabled | nil,
  service_tier: String.t() | atom() | nil,
  total_timeout: 1..300_000
}

Functions

codec()

Stateless continuation codec. Credentials and client configuration come from the host's freshly constructed adapter on restore.

new(opts)

@spec new(keyword()) :: t()

Build an adapter instance; :model is required.

Options: :model, :profile (:auto or a profile atom), :api_key, :auth_token, :base_url, :reasoning_mode (:disabled or :enabled), :reasoning_effort (a string), :total_timeout (1..300,000 ms, default 120,000), :foreign_history (:reject or :portable), :prompt_cache, :service_tier, :provider_options and :http_options. Unknown, duplicate or missing options, values of the wrong type, a model the catalogue cannot resolve, a profile that contradicts the catalogue, an unsupported reasoning mode or effort and a :prompt_cache or :service_tier the provider cannot honour raise ArgumentError, offline and without reading credentials. The result stores the resolved profile and reasoning mode.