LLM invocation and provider abstraction
The LLM invocation layer gives agent and answer flows one provider-neutral way to call a model. It selects a provider and transport from runtime settings, exposes a small client contract, and converts vendor responses into shared text, tool-call, usage, and error results. This keeps agent behavior independent of the model vendor or account type.
Invocation roles
The invocation layer separates model work by role rather than by vendor. The agent role supports tool calls, while reasoning and decision roles return direct or structured results through the same provider choice.
| Role | Purpose | Result |
|---|---|---|
| Agent | Think, call tools, and observe results | Text plus zero or more typed tool calls |
| Reasoning | Produce a direct or deep answer | Text, with optional streaming |
| Classification | Make a lower-cost decision about input | Text or a validated structured result |
| Tool call | Make a lightweight tool-selection decision | Text or a validated structured result |
AgentLLMClient is the narrow contract used by the ReAct loop. It exposes model identity, tool-schema conversion, and invocation. AgentLLMResponse carries provider-neutral text, tool calls, stop state, raw response data for replay, and usage when available. Non-agent callers use LLMResponse and streaming methods. The harness obtains these clients without selecting a vendor itself. See agent execution and agent harness.
Model selection resolves the active reasoning and tool-call models for the selected provider. Subscription providers use the account's selected model, while API providers can use one shared model or separate role models. The agent loop therefore does not own model selection.
References: core/…/types.py• L40-145 core/…/provider_models.py• L13-43 core/…/factory.py• L38-53 core/…/react_loop.py• L259-303 core/…/llm_resolution.py• L8-33
Provider and transport routing
Provider routing turns runtime settings into one LLMRoute for a turn. The route applies to all model roles, then selects a native SDK, LiteLLM, or CLI-backed path. This prevents agent and answer flows from making different provider decisions.
The route gives account-managed access precedence over the configured provider. API-key providers use stored or environment credentials through provider-aware resolution, which can return provider-specific setup guidance when a credential is missing. Local and ambient-credential providers are checked at request time. Azure OpenAI uses its deployment name, resource endpoint, and API version through the LiteLLM path. The route still exposes one client contract to the agent in every case.
Readiness is a prompt-safe preflight. It repeats the account-first provider choice without building a client. It checks settings and missing API keys, but does not claim that CLI, local, ambient, or subscription access is usable when that fact can only be proved during a request. A missing subscription session produces a login action instead of a generic missing-key message. Credential metadata that is stale or temporarily unreadable is not treated as proof that a key is absent.
The client cache keeps one client per role for the active transport and runtime provider. Account routes include their endpoint and model in the cache identity. Subscription routes include the active model, while tokens resolve for each request. A provider or transport change clears all role clients so later calls use one configuration.
This diagram shows how a role request becomes one provider-neutral client.
flowchart TD
A[Agent or answer role] --> B[Resolve one LLM route]
B --> C{Access path}
C -->|CLI| D[CLI client]
C -->|LiteLLM| E[LiteLLM client]
C -->|Native SDK| F[Vendor SDK client]
C -->|Subscription| G[Provider-owned subscription client]
D --> H[Shared client contract]
E --> H
F --> H
G --> H
H --> I[Agent loop or answer flow]
References: core/…/readiness.py• L26-81 core/…/provider_credentials.py• L6-20 core/…/client_cache_key.py• L6-24 core/…/factory.py• L55-79 core/…/client_builders.py• L31-259 core/…/azure_openai.py• L24-188 core/…/routing.py• L33-210 core/…/registry.py• L10-27
Subscription access
Subscription access is a provider route with its own account session and billing rules. Authentication and inference are separate contracts so a successful login cannot silently become API-billed access.
The subscription adapter owns login, model discovery, request-time credential renewal, verification, and logout. Login activates an account only after its session and model access pass validation. Logout clears active tokens but keeps the account registration for later use. The client factory owns the provider's request format, tool serialization, streaming behavior, and subscription restrictions. Each request resolves the active account and never uses an ordinary API key as a fallback.
ChatGPT uses an OAuth browser flow and a plan-specific Responses request. Grok uses RFC 8628 device authorization and xAI's Responses route. Both discover account-visible models before activation and retain account registration after logout. Authentication or model-list success does not prove plan entitlement for inference.
References: core/…/README.md• L3-20 core/…/types.py• L12-63 core/…/registry.py• L18-27 core/…/chatgpt.py• L148-355 core/…/grok.py• L107-295 core/…/chatgpt_clients.py• L30-90 core/…/grok_clients.py• L13-74
Agent tool-calling exchange
The tool-calling client is the boundary between the shared ReAct loop and provider message formats. The loop supplies conversation messages, a system prompt, and public tool schemas. The client returns text and typed ToolCall values, after which the loop runs tools and appends provider-shaped assistant and tool-result messages.
Native providers can expose tool calls directly. Other adapters translate the public schema into the provider's accepted form and normalize the result back to the shared response. Raw assistant content remains available when a provider needs reasoning or tool state replayed on the next turn. OpenAI-compatible clients select the request form that matches the model family and preserve the provider's raw message fields when the next turn needs them.
LiteLLM agent calls use a completed response rather than streamed tool-call deltas because providers expose different stream shapes. Native SDK clients stream only where the returned tool-call shape and provider state can be preserved. A stream that fails after visible output becomes an interruption rather than a second request.
When an agent request completes, the exchange follows this sequence:
- The loop filters tools and asks the client for provider schemas.
- The loop prepares message history within the context budget.
- The client sends the request through the selected transport.
- The client normalizes text, tool calls, stop state, and usage.
- The loop accepts the answer or executes the requested tools.
- Message adapters prepare the next provider request.
References: core/…/react_loop.py• L84-112 core/…/react_loop.py• L218-309 core/…/provider_adapters.py• L25-166 core/…/clients.py• L48-166 core/…/responses.py• L59-210 core/…/openai_chat_completions.py• L53-192 core/…/chatgpt_clients.py• L30-69 core/…/grok_clients.py• L13-53 core/…/openai_responses.py• L20-160 core/…/agent_clients.py• L961-1215
Context budgeting
Context budgeting keeps a multi-step request below the active model's prompt limit while preserving the information most useful for the next decision. The budget covers the message history, system prompt, and tool schemas, and reserves space for the model's output.
The system uses a conservative token estimate. It first removes low-value non-pinned tool exchanges, with duplicate-only results preferred for removal. If the request still exceeds the limit, it shortens the largest text-bearing message. If no safe change remains, the provider receives the request and any overflow is classified as a prompt-size failure.
Known model families receive their known context ceiling. Unknown models use a conservative default. Internal eviction markers help the budget logic choose history, then disappear before a provider sees the request.
References: core/context_budget.py• L12-54 core/context_budget.py• L164-184 core/context_budget.py• L227-258 core/context_budget.py• L261-437 core/…/react_loop.py• L96-101 core/…/react_loop.py• L259-267 config/llm_models.py• L1-15
Error classification and retry behavior
Error handling converts vendor failures into stable categories that the agent loop and user-facing surfaces can act on. The shared rules distinguish temporary failures from errors that a retry cannot fix.
| Failure class | Normal response |
|---|---|
| Temporary rate limit or service fault | Retry with bounded backoff and honor a provider delay when present |
| Billing, credit, or subscription usage exhaustion | Stop without retrying and show account guidance |
| Hosted route requires a connected GitHub account | Stop without retrying and show the account connection action |
| Authentication or permission failure | Stop and report the credential or access problem |
| Missing or invalid model | Stop, or use the configured tool-call fallback for supported non-agent calls |
| Context overflow | Report a prompt-size error after local trimming cannot make the request fit |
| Network or endpoint failure | Retry only when the transport treats it as transient |
Hosted calls can perform a local credit admission check. A confirmed empty balance stops the call, while an unreadable balance remains unknown and lets the hosted service decide. A hosted refusal that says GitHub is required is a separate fatal access result. It carries an optional connection URL so the user can connect an account or use a workspace connection. Subscription sessions use a separate login-required or plan-limit vocabulary. A stale or invalid session is not treated as a normal rate limit and is never replaced by API-key access.
OpenAI-compatible requests can correct one provider-specific token parameter rejection in the same request. If a compatible endpoint rejects max_tokens and the request has not already used max_completion_tokens, the client retries with the alternate parameter. Non-agent clients can also use a configured tool-call model when the selected reasoning or classification model is unavailable. These corrections stay local to the request or client and do not change the shared route.
Streaming adds one safety rule: retry is allowed before the first visible chunk, but not after output starts because a second request could duplicate text. A partial stream becomes an interruption result instead of an automatic duplicate call. Request timeouts also do not retry when the request may already have run upstream and incurred provider cost.
Readiness uses provider-style wording so setup surfaces and request failures suggest the same next action. The shared failure vocabulary also supports investigation and provider-failure analytics.
References: core/…/llm_retry.py• L15-107 core/…/llm_retry.py• L125-243 core/…/openai_chat_completions.py• L247-481 core/…/openai_token_limits.py• L10-56 core/…/readiness.py• L26-82 core/…/failure_classification.py• L7-82 core/llm_invoke_errors.py• L94-216 core/…/chatgpt.py• L116-145 core/…/chatgpt_clients.py• L14-27 core/…/agent_clients.py• L1020-1083 core/…/llm_clients.py• L857-942 core/…/clients.py• L226-299 core/…/routing.py• L132-205
Usage and structured output
Usage reporting gives hosts one provider-neutral view of input tokens, output tokens, prompt-cache activity, and optional reasoning tokens. Each transport reads its provider's usage shape and sends normalized counts to the shared observer. Missing counts remain unknown rather than becoming false zeroes.
Structured output wraps a client with a validated data-model contract. The normal path asks for JSON that matches a schema and validates the result. Native constrained output is optional, so providers that do not support it keep the same wrapper boundary. This allows classification and other decision flows to use structured results without knowing the provider.
References: core/…/usage.py• L13-180 core/…/structured_output.py• L28-106 core/…/responses.py• L194-210 core/…/types.py• L59-100
Cross-system boundaries
The harness requests agent or reasoning clients through a narrow resolution seam. It does not select a vendor or construct a provider client. The agent loop depends on shared response and tool contracts, while provider message shaping stays behind adapters.
These boundaries give nearby systems clear responsibilities:
- Agent execution owns the turn and tool loop.
- Agent harness owns host-facing construction and session use.
- Tool framework owns tool discovery, schemas, and execution.
- Agent memory owns memory that becomes agent context.
- Skill lifecycle and releases owns skill packaging and release flow.
- Workspace knowledge owns workspace knowledge that may enter prompts.
- This page owns model selection, invocation contracts, provider translation, readiness, context limits, and failure behavior.
References: core/…/llm_resolution.py• L8-33 core/…/types.py• L102-145 core/…/provider_adapters.py• L57-89 core/…/factory.py• L13-24
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the single route decision aligned with readiness and the role client builders.
- Keep provider catalog metadata, model tiers, credential modes, and LiteLLM routing aligned.
- Keep provider-aware credential lookup aligned with the setup action shown for each API-key provider.
- Keep subscription registration, account isolation, model discovery, request-time renewal, and provider-owned inference aligned.
- Keep subscription cache identity model-based. Do not place rotating tokens in cache keys.
- Keep provider-specific Responses fields aligned with raw response replay and tool-result messages.
- Keep model-family context limits aligned with model naming and output headroom.
- Keep billing, GitHub account requirements, subscription exhaustion, and temporary throttling separate in retry rules.
- Keep OpenAI-compatible fallback lookup tied to the provider's settings path.
- Keep OpenAI-compatible token-parameter correction limited to endpoints that support it and to one request-local retry.
- Keep usage extraction aligned with each provider's token and cache field names. Unknown fields must remain unknown.
- Keep streamed completion, cancellation, closure, and partial-output behavior aligned across subscription clients.
- Keep native-streaming model support aligned with Grok subscription request handling.
- Keep ChatGPT-only request extensions out of other subscription providers.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A provider or transport changes while cached clients remain active | A later role can use the old backend or credentials | Include route identity in the cache key and clear all role clients on change |
| Readiness and invocation use different account or subscription rules | Setup reports a route as ready even though the call uses another route | Keep both paths account-first and provider-aligned |
| A subscription session expires or loses entitlement | The call stops with login or plan guidance instead of silently switching billing | Resolve credentials per request and forbid API-key fallback |
| An API-key provider has no usable credential and generic setup text hides the provider action | The user does not know which credential or login action can fix the route | Resolve the provider from its credential environment mapping and include its setup command |
| The hosted route requires GitHub but the error is handled as generic permission denial | The user does not see the connection path and retries cannot help | Classify the hosted error code before generic permission handling and preserve its connection URL |
| A confirmed hosted credit balance is empty | Provider work does not start | Stop only on a verified zero balance; treat read failures as unknown |
| A stream retries after visible output | The user sees duplicate answer text | Retry only before the first emitted chunk |
| A completed Responses payload loses output items or raw assistant state | The next tool turn cannot replay reasoning or calls | Preserve completed output and rebuild the next input through the Responses adapter |
| A compatible endpoint rejects the token parameter and the client retries with the same field | The request fails even though the model supports the alternate field | Detect the explicit unsupported-parameter error and replace the field once per request |
| A reasoning or classification model is unavailable and no valid fallback is resolved | The non-agent step fails before it can use the provider's tool-call tier | Resolve the fallback through the provider's own settings path |
| A known model family is absent from the context catalog | History may trim too early or the provider may reject an oversized prompt | Add model-family coverage and keep the conservative fallback |
| Billing or plan exhaustion matches a broad rate-limit rule | The system retries an error that cannot succeed | Classify account and subscription exhaustion before rate-limit retry handling |
| ChatGPT plan extensions are sent to Grok | The provider rejects or misreads the request | Keep provider-owned subscription serializers separate |
Key files
| File | Why to read it |
|---|---|
| core/…/types.py | Defines the provider-neutral route, client, response, usage, and tool-call contracts. |
| core/…/factory.py | Shows the single provider and transport decision and client cache entrypoint. |
| core/…/readiness.py | Shows the prompt-safe preflight for the selected route. |
| core/…/provider_credentials.py | Shows provider-aware API-key lookup and missing-credential guidance. |
| core/…/azure_openai.py | Shows Azure deployment, endpoint, API-version, and deployment-discovery boundaries. |
| core/…/client_cache_key.py | Shows cache identity for normal, account-managed, and subscription routes. |
| core/…/client_builders.py | Maps one route to agent and reasoning clients. |
| core/…/routing.py | Maps provider settings to LiteLLM model, credential, endpoint, fallback, and ambient-auth data. |
| core/…/clients.py | Shows the shared LiteLLM agent and non-agent client boundary, model fallback, and stream behavior. |
| core/…/responses.py | Defines Responses streaming, completion, cancellation, replay, and usage behavior. |
| core/…/types.py | Separates subscription credential lifecycle from inference client construction. |
| core/…/registry.py | Registers supported subscription authentication and client pairs. |
| core/…/chatgpt.py | Shows ChatGPT login, model discovery, renewal, account retention, and logout. |
| core/…/grok.py | Shows Grok device login, account isolation, renewal, entitlement checks, and logout. |
| core/…/chatgpt_clients.py | Shows the ChatGPT plan request boundary. |
| core/…/grok_clients.py | Shows the Grok subscription Responses boundary and native-streaming guard. |
| core/…/react_loop.py | Shows context preparation, invocation, and tool-turn control. |
| core/…/provider_adapters.py | Shows the boundary between shared messages and provider messages. |
| core/context_budget.py | Defines prompt limits and history reduction order. |
| core/…/llm_retry.py | Defines shared retry, hosted access, and exhaustion behavior. |
| core/…/openai_chat_completions.py | Normalizes OpenAI-compatible messages and applies shared retry, fallback, and error rules. |
| core/…/openai_token_limits.py | Defines request-local compatibility for alternate OpenAI token-limit fields. |
| core/…/agent_clients.py | Shows native SDK agent tool calls, streaming, replay, model-family request fields, and provider error handling. |
| core/…/llm_clients.py | Shows native SDK reasoning, classification, structured output, model fallback, and provider error handling. |
| core/…/usage.py | Normalizes token and prompt-cache usage. |
| core/…/structured_output.py | Defines the validated structured-result boundary. |
| core/llm_invoke_errors.py | Defines stable invocation failures and provider-failure guidance. |