6. Talking to the Model
Codex treats the model as a stateless function. Every sampling
request carries the whole conversation, rebuilt from local history, with
store: false, so the server never has to remember anything.
Two types share the work: ModelClient lives for a session
and builds requests, and ModelClientSession lives for one
turn and owns the transport, which can shrink a WebSocket request to a
suffix when the new input extends the last one.
Chapter 5 showed the turn loop deciding when to call the model. This chapter covers the call itself: what goes on the wire, which transport carries it, how the streamed reply becomes typed events, and what happens when the stream breaks. It ends with the two registries that feed every request, the providers and the model catalog.
One constraint shapes the rest. Codex asks the server not to store responses, so the client carries the conversation itself. That choice explains why requests grow with history, why prompt caching matters, and why the WebSocket transport works to send only what is new.
The picture
Read the diagram top to bottom. The turn loop builds a
Prompt from normalized history and the visible tools, and
passes it to the turn’s ModelClientSession. The session
asks the long-lived ModelClient to turn the prompt into a
ResponsesApiRequest. If the provider supports WebSockets,
the session sends a response.create frame, often carrying
only the new items and a previous_response_id; otherwise it
sends a full POST /responses and reads server-sent events
(SSE). Either way, codex-api parses each wire event into
one ResponseEvent and hands it to the turn loop. The last
arrow is the failure path: handle_response_stream_error
decides between a retry, a switch to HTTP, and giving up.
Two clients, two lifetimes
ModelClient in codex-rs/core/src/client.rs
is session-scoped. Its doc comment says it holds “auth, provider
selection, thread id, and transport fallback state”. The shared parts
live behind an Arc<ModelClientState>, so clones are
cheap and share one provider, one disable_websockets flag,
and one cached WebSocket connection.
ModelClientSession is turn-scoped.
ModelClient::new_session creates one per turn without any
network I/O; the socket opens lazily on the first request. The session
caches the last full request, a receiver for the last response, and the
x-codex-turn-state sticky-routing token that the server
returns on the first response of a turn. The doc comment is explicit
about the contract: reusing a session across turns “would replay the
previous turn’s sticky-routing token into the next turn, which violates
the client/server contract and can cause routing bugs.”
This split is a scoped-state pattern. Per-turn settings, such as the
model and reasoning effort, are arguments to stream, not
stored state, so the turn lifetime stays visible at each call site.
The input to both is Prompt, defined in
codex-rs/core/src/client_common.rs:
pub struct Prompt {
/// Conversation context input items.
pub input: Vec<ResponseItem>,
/// Tool definitions to inject into this request, empty when supplied by history.
pub(crate) tools: Arc<[ToolSpec]>,
/// Whether parallel tool calls are permitted for this prompt.
pub(crate) parallel_tool_calls: bool,
pub base_instructions: BaseInstructions,
pub output_schema: Option<Value>,
pub output_schema_strict: bool,
pub(crate) prompt_cache_ttl: Option<crate::PromptCacheTtl>,
pub(crate) cyber_access_program: Option<codex_protocol::turn_input::CyberAccessProgram>,
}The excerpt drops serde attributes and two doc comments.
build_prompt in core/src/session/turn.rs fills
it: input comes from
ContextManager::for_prompt (Chapter 7) and
tools from the tool router (Chapter 9).
The shape of a request
ModelClient::build_responses_request turns a
Prompt plus per-turn settings into a
ResponsesApiRequest. Several fields are fixed.
tool_choice is always "auto",
store is always false, and stream
is always true. The table lists the rest.
| Field | What Codex sends | Rule in build_responses_request |
|---|---|---|
input |
Prompt items, base instructions first | Spliced at index 0 as a developer message |
tools |
Tool JSON, or omitted | Omitted for Responses Lite models |
parallel_tool_calls |
true or false |
Prompt allows it and model is not Lite |
reasoning |
effort, summary, context | See below |
include |
reasoning.encrypted_content |
Always; one more entry on OpenAI with replay |
text |
verbosity, output schema | Verbosity only if the model supports it |
service_tier |
tier ID or omitted | Model must list it; Bedrock must advertise it |
prompt_cache_key |
session-derived key | Policy PromptCacheKey |
Base instructions travel as a message
The request struct has no instructions field. When
prompt.base_instructions.text is not empty, the builder
wraps it in BaseInstructionsFragment, which renders with
role "developer" and content kind
model.base_instructions, and splices it in front of
input. The model therefore sees the base prompt as the
first developer message of every request.
Most models in the bundled catalog set
use_responses_lite. For those models the builder does not
send a tools array; it wraps the tool list in a
ResponseItem::AdditionalTools item with role
developer, placed ahead of the base instructions. When the
incremental_tools feature is on (STABLE, on by default), a
new context window goes further: it records the base instructions and
the tool declarations in history as prefix items, and
build_prompt sends empty base instructions. The wire result
is the same leading developer content, but now it lives in history and
only changes by diff (Chapter 7).
Reasoning, verbosity, and tiers
build_reasoning fills three fields. The effort is the
configured value, or else the model’s
default_reasoning_level, passed through
ModelInfo::resolve_reasoning_effort. That resolver maps
Ultra to the model’s
multi_agent_reasoning_effort, else Max, else
the highest other supported level, else Medium; it sends
Persistent as the string "disabled". The
summary is sent only when the provider capability
reasoning_summaries is true, the model sets
supports_reasoning_summary_parameter, and the configured
summary is not none. The context field is
all_turns for Responses Lite models and omitted otherwise;
the code comment says the server default is
current_turn.
Verbosity goes into text only when the model sets
support_verbosity. A configured
model_verbosity on any other model logs a warning and is
dropped. service_tier_for_request drops the default tier
and any tier the model does not list, and
provider_allows_service_tier also requires Amazon Bedrock
models to advertise the tier.
Two rules protect non-OpenAI providers. The builder strips encrypted
content from every item except Reasoning,
Compaction, and ContextCompaction, and clears
encrypted function arguments. The second include entry,
output.encrypted_content, is added only when the
output_token_replay feature is on and the provider is
OpenAI.
ResponsesApiRequest in
codex-rs/codex-api/src/common.rs declares
model, stream, and service_tier
first. Its comment gives the reason: serde writes fields in declaration
order, and “gateways may inspect request bodies incrementally before
potentially multi-megabyte input.” Field order is part of the
contract.
A first request, reconstructed
The body below is reconstructed from the builder and from assertions
in core/tests/suite/client.rs, which check the path
/v1/responses, store: false, and a
prompt_cache_key equal to the session ID. It assumes the
bundled gpt-5.5 entry, which is not a Responses Lite model,
so it shows a tools array. Text is shortened.
{
"model": "gpt-5.5",
"stream": true,
"input": [
{"type": "message", "role": "developer",
"content": [{"type": "input_text", "text": "You are Codex, ..."}]},
{"type": "message", "role": "developer",
"content": [{"type": "input_text", "text": "<permissions instructions>..."}]},
{"type": "message", "role": "user",
"content": [{"type": "input_text", "text": "<environment_context>..."}]},
{"type": "message", "role": "user",
"content": [{"type": "input_text", "text": "hello"}]}
],
"tools": [ ... ],
"tool_choice": "auto",
"parallel_tool_calls": true,
"reasoning": {"effort": "medium"},
"store": false,
"include": ["reasoning.encrypted_content"],
"prompt_cache_key": "<session id>",
"text": {"verbosity": "low"},
"client_metadata": {"session_id": "...", "thread_id": "...", "turn_id": "..."}
}The catalog gives gpt-5.5 default effort
medium, verbosity low, and summary
none, so reasoning has no
summary. The test helper
assert_codex_client_metadata also checks
x-codex-installation-id and
x-codex-turn-metadata in client_metadata.
Why Codex resends everything
With store false, the request asks the server not to
keep the response for later reference. The HTTP request struct has no
previous_response_id field at all; only the WebSocket frame
has one, and the client uses it only to continue from the last response
on the same socket session. Codex therefore keeps the full conversation
in its own ContextManager. The reasoning items it replays
come back as reasoning.encrypted_content, which is why that
include entry is unconditional: the model can see its
earlier reasoning without the client being able to read it. This design
also suits accounts with zero data retention (ZDR); the code never names
ZDR, so that benefit is an inference.
Resending is affordable because of prompt caching.
PromptCacheKey in core/src/thread_manager.rs
has three variants: SessionDerived (the default),
Custom(String), and Omit. The session-derived
key is a configured override, or
"{source}:{parent_thread_id}" for internal sessions with a
parent, or else the session ID. The test
overrides_turn_context_but_keeps_cached_prefix_and_key_constant
in core/tests/suite/prompt_caching.rs asserts that the key
stays the same across turn overrides and that the first request is an
exact prefix of the second. That prefix property is the reason Chapter 7’s context machinery
appends diffs instead of editing earlier items. Usage reports show the
payoff: TokenUsage carries
cached_input_tokens, and blended_total counts
only non-cached input plus output.
Two transports
ModelClientSession::open_model_response matches on the
provider’s wire_api, which has one variant,
Responses. If responses_websocket_enabled
returns true, it tries the WebSocket path first. That function requires
the provider flag supports_websockets and an unset session
flag disable_websockets. The built-in OpenAI provider sets
the flag; the cloud and local providers do not.
HTTP with server-sent events
The HTTP path sends POST /responses with
Accept: text/event-stream.
responses_request_compression turns on zstd body
compression only when the enable_request_compression
feature is on, the auth uses the Codex backend, and the provider is
OpenAI. Below the stream layer, codex-client retries the
HTTP request itself: to_api_provider sets
max_attempts to request_max_retries() (default
4), a 200 ms base delay, retries for 5xx responses and transport errors,
and no retry for HTTP 429.
WebSocket and incremental requests
The WebSocket URL is the same path with http mapped to
ws and https to wss, and the
handshake carries the beta header value
responses_websockets=2026-02-06. The point of the socket is
continuation. Before each send, prepare_websocket_request
calls get_incremental_items, in
core/src/client.rs:
let response_items = &last_response.items_added;
let previous_items = previous_request.input.iter().chain(response_items);
let mut current_items = request.input.iter();
for previous in previous_items {
let Some(current) = current_items.next() else {
return Err(NonIncrementalReason::InputShortened {
previous: previous.item_type(),
});
};
if !response_items_equal_ignoring_internal_metadata(previous, current) {
return Err(NonIncrementalReason::InputMismatch {
previous: previous.item_type(),
current: current.item_type(),
});
}
}
Ok(current_items.cloned().collect())The rule is simple. The previous request’s input plus the items the
server returned must be an exact prefix of the new input, and every
non-input field must match. If so, the frame carries
previous_response_id and only the remaining items. If not,
the frame carries the full input. Each outcome is counted with a bounded
reason label, such as no_previous_request,
input_shortened, or input_mismatch, never with
request contents. A turn can also prewarm the socket with a
response.create that sets generate=false, so
the first real request can continue from it.
The fallback rule
The downgrade to HTTP is one-way per session.
ModelClient::force_http_fallback sets
disable_websockets with an atomic swap, logs the reason,
and counts codex.transport.fallback_to_http. Three things
trigger it: a handshake answered with HTTP 426 Upgrade Required, an
error whose retry policy is FallBackToHttp (today only
WebsocketMessageTooLarge), and a stream that has used up
its retry budget on WebSocket. After a switch caused by a stream error,
the user sees the warning “Falling back from WebSockets to HTTPS
transport.” and the retry counter starts again at zero; a 426 handshake
switches without that warning.
From stream to items
Both transports feed the same parser.
process_responses_event in
codex-rs/codex-api/src/sse/responses.rs maps each wire
event type to at most one ResponseEvent.
| Wire event | ResponseEvent |
|---|---|
response.created |
Created |
response.output_item.added / .done |
OutputItemAdded / OutputItemDone |
response.output_text.delta |
OutputTextDelta |
response.reasoning_summary_text.delta |
ReasoningSummaryDelta |
response.completed |
Completed with usage and end_turn |
response.failed |
an ApiError |
Some events, such as response.in_progress, are ignored
on purpose. A response.incomplete event with reason
interrupted becomes a completion with
end_turn: Some(false), reason content_filter
becomes ApiError::ContentFilter, and any other reason
becomes ResponseIncomplete with the partial output.
Response headers produce events too: OpenAI-Model becomes
ServerModel, rate-limit headers become
RateLimits, X-Models-Etag becomes
ModelsEtag, and x-reasoning-included becomes
ServerReasoningIncluded.
The SSE loop wraps every read in the provider’s idle timeout, 300,000
ms by default, and reports “idle timeout waiting for SSE” when it
expires. A stream that ends before response.completed is an
error too. A line that is not valid JSON is logged and skipped. Events
reach the turn loop through a 1,600-slot channel.
In the turn loop, try_run_sampling_request consumes the
events. OutputItemDone goes to
handle_output_item_done, which records the item in history
and, if the tool router recognizes a tool call, queues the tool future
and sets needs_follow_up. Completed records
token usage with record_token_usage_info. Chapter 5 follows what the loop does
next.
Errors and retries
Mapping provider errors
Terminal provider codes are classified once, in
parse_terminal_provider_error in
codex-rs/codex-api/src/error.rs, and retryable failures in
parse_failed_response. The table shows the main codes.
| Provider code | Error | Retried? |
|---|---|---|
context_length_exceeded |
ContextWindowExceeded |
Never |
insufficient_quota |
QuotaExceeded |
Never |
server_is_overloaded |
ServerOverloaded |
Only with server delay |
rate_limit_exceeded, slow_down |
RateLimitExceeded |
Backoff |
| any other failed code | Retryable |
Backoff |
For rate limits without a Retry-After header,
try_parse_retry_delay reads the delay out of the message
with the case-insensitive pattern
(?i)try again in\s*(\d+(?:\.\d+)?)\s*(s|ms|seconds?). A
test fixture with “Please try again in 11.054s.” yields an 11.054-second
delay.
The retry policy table
CodexErr::retry_policy in
codex-rs/protocol/src/error.rs is a policy table: one match
assigns every error variant one of four policies. Never
covers context-window, quota, usage-limit, invalid-request, and
content-policy errors, among others. ServerDirected covers
ServerOverloaded, PolicyCapacityUnavailable,
and RetryLimit, which retry only when the server gives a
delay. FallBackToHttp covers
WebsocketMessageTooLarge. Backoff covers
stream, timeout, connection, internal-server, and unexpected-status
errors. A new error variant cannot compile without a policy.
Backoff
CodexErr::retry_delay returns the server’s delay when
there is one, and otherwise calls backoff from
codex-rs/async-utils/src/backoff.rs:
where
INITIAL_DELAY_MS, 2
is BACKOFF_FACTOR, and
handle_response_stream_error in
core/src/responses_retry.rs sleeps until the server’s
retry-after deadline if present, else until now plus
One feature changes this for lost connections. With
unbounded_connection_retries on, a
ConnectionFailed error during a sampling request retries
forever, except for internal sessions and Bedrock, with the message
“Reconnecting… waiting for network”:
where
INITIAL_CONNECTION_RETRY_DELAY,
and 60 s is MAX_CONNECTION_RETRY_DELAY. A content-filter
error takes a different first step: the handler records a
ContentFilterGuidance message into history, then retries
with backoff.
Providers and the model catalog
Providers
A provider is a ModelProviderInfo value from
codex-rs/model-provider-info/src/lib.rs: a name, a base
URL, a wire API, auth settings, extra headers, retry and timeout
overrides, and flags such as requires_openai_auth and
supports_websockets. WireApi has one variant,
Responses, documented as the API “exposed by OpenAI at
/v1/responses”. A config that still says
wire_api = "chat" fails with an error that tells you to set
wire_api = "responses".
built_in_model_providers registers six providers. They
differ mainly in how they authenticate.
| ID | Auth | WebSocket |
|---|---|---|
openai |
ChatGPT sign-in or API key | Yes |
amazon-bedrock |
AWS credentials (aws block) |
No |
amazon-bedrock-runtime |
AWS credentials | No |
gcp |
Command auth supplied at config load | No |
ollama |
None; localhost:11434 |
No |
lmstudio |
None; localhost:1234 |
No |
The OpenAI provider sets requires_openai_auth, reads
OPENAI_ORGANIZATION and OPENAI_PROJECT into
headers, and picks its base URL from the auth mode:
https://chatgpt.com/backend-api/codex for ChatGPT-style
sign-in and https://api.openai.com/v1 otherwise. The local
providers honor CODEX_OSS_PORT and
CODEX_OSS_BASE_URL. A custom provider names an environment
variable for its key:
[model_providers.local]
name = "local"
base_url = "http://localhost:8080/v1"
env_key = "LOCAL_API_KEY"
wire_api = "responses"
stream_idle_timeout_ms = 300000
stream_max_retries = 5
request_max_retries = 4The defaults in that block are the code’s own: 300,000 ms idle
timeout, 5 stream retries, and 4 request retries, with both retry counts
capped at 100. Provider capabilities live in
ProviderCapabilities in
codex-rs/model-provider/src/capabilities.rs; the one that
matters most later is remote_compaction, which defaults to
V2 only for OpenAI and Azure Responses providers (Chapter
8). Chapter 25 covers how provider
tables merge across config layers.
The model catalog
codex-rs/models-manager/models.json is the bundled
catalog. At this commit it lists 14 models. Each entry is a
ModelInfo with the window sizes, reasoning levels, tool
flags, and model-owned messages that the request builder reads. The
table shows representative entries.
| Slug | context_window |
max_context_window |
Default effort |
|---|---|---|---|
gpt-6.2-sol |
500,000 | 872,000 | low |
gpt-6-sol |
272,000 | 872,000 | medium |
gpt-5.6-terra |
272,000 | 872,000 | medium |
gpt-5.5 |
272,000 | 272,000 | medium |
Most entries offer efforts from low to
ultra; gpt-5.5 stops at xhigh and
the luna models at max. Every entry except
gpt-5.5 sets use_responses_lite. The window
fields feed Chapter 8’s budget.
The default model is chosen at runtime.
build_available_models sorts presets by
priority, drops entries with supported_in_api
false unless the user signed in with ChatGPT, and marks the first
picker-visible preset as the default. With the bundled catalog that is
gpt-6.2-sol; the book derived this from the file, and a
fetched catalog, cached for 300 seconds, can change it.
Base instructions also come from the catalog. Each entry carries
model_messages.instructions_template, which the code
comment calls “literal text”. The 20,903-byte prompt.md,
compiled in as BASE_INSTRUCTIONS, is the fallback that
model_info_from_slug uses for unknown models; it opens “You
are a coding agent running in the Codex CLI”. A configured
base_instructions or model_instructions_file
overrides both.
Status at commit 081295be9d.
incremental_tools: STABLE, on by default.
reasoning_effort_override: STABLE, on.
concurrent_reasoning_summaries: STABLE, on.
enable_request_compression: STABLE, on.
unbounded_connection_retries: STABLE, on.
output_token_replay: UNDER DEVELOPMENT, off.
responses_websockets and
responses_websockets_v2: REMOVED; the provider flag
supports_websockets now decides. Chat Completions
(wire_api = "chat"): REMOVED. Read in code, not run.
What breaks
| Symptom | Cause | Check |
|---|---|---|
| “Reconnecting… 1/5” after a long silence | No event within the idle timeout | stream_idle_timeout_ms; “idle timeout waiting for
SSE” |
| Warning “Falling back from WebSockets to HTTPS transport.” | Retries exhausted or message too large (a 426 switches silently) | Counter codex.transport.fallback_to_http and its
reason |
| Turn ends with a context-window error | ContextWindowExceeded is never retried |
Chapter 8 trigger;
model_auto_compact_token_limit |
Config error mentioning wire_api = "chat" |
Chat Completions support removed | Set wire_api = "responses" |
model_verbosity has no effect |
Model lacks support_verbosity |
Warning “model_verbosity is set but ignored” |
| Low cached-token share | Cache key changed or prefix edited | prompt_cache_key in two requests; prefix test |
Code map
| What it is | Source | Identifier |
|---|---|---|
| Session and turn clients | codex:codex-rs/core/src/client.rs |
ModelClientSession |
| Request builder | codex:codex-rs/core/src/client.rs |
build_responses_request |
| WebSocket continuation | codex:codex-rs/core/src/client.rs |
get_incremental_items |
| Wire request struct | codex:codex-rs/codex-api/src/common.rs |
ResponsesApiRequest |
| Event mapping | codex:codex-rs/codex-api/src/sse/responses.rs |
process_responses_event |
| Retry policy table | codex:codex-rs/protocol/src/error.rs |
fn retry_policy |
| Stream retry handler | codex:codex-rs/core/src/responses_retry.rs |
handle_response_stream_error |
| Built-in providers | codex:codex-rs/model-provider-info/src/lib.rs |
built_in_model_providers |
Recall check
Why does the request have no instructions
field?
build_responses_request splices the base instructions into
input as a leading developer message.
What makes a WebSocket request incremental?
The previous input plus the server’s output items must be an exact
prefix of the new input, with all other fields unchanged.
Which errors fall back from WebSocket to HTTP?
A 426 handshake, WebsocketMessageTooLarge, or a stream that
exhausted its retries; the switch lasts for the session.
How long does the third stream retry wait without server
advice?
About 800 ms, from equation (6.1) with
Where do base instructions come from for a catalog
model?
From its model_messages.instructions_template;
prompt.md is the fallback for unknown slugs.