Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 8 additions & 7 deletions docs/architecture/cache-friendly-message-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -302,13 +302,14 @@ Important exceptions:
context and older persisted context snapshots
- context compression intentionally rewrites conversation history into a shorter
summary form, then invalidates prompt cache and starts a new stable prefix
- image payloads are elided from older image-bearing messages at send time.
The latest two image-bearing messages always keep pixels; older ones are
elided four at a time (`MIN_RETAINED_IMAGE_MESSAGES`,
`IMAGE_ELISION_BATCH` in `execution_engine.rs`). Each elision rewrites an
already-sent message and invalidates the provider cache from that message
onward, so it must stay batched rather than sliding by one message per new
image. Model-pool image requirements use the same retained window.
- Each request sends pixels from pending user uploads and new tool observations,
including parallel tool results. After an assistant response, those messages
carry text and available image references on later requests. A vision route
without `view_image` keeps the most recent user upload within the request
budget. Reopening a reference supplies a new observation and changes the
provider cache prefix at the first replaced image. Session-scoped tool image
snapshots follow session deletion. A fork copies the snapshots referenced by
the history it retains.

## Session Storage Layout

Expand Down
7 changes: 7 additions & 0 deletions scripts/core-boundaries/cargo-dependency-boundaries.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,13 @@ const THIRD_PARTY_CAPABILITY_PROFILES = new Map([
['image', {
label: 'Image',
packages: new Map([
['openbitfun-ai-adapters', dependencyProfile([], {
optional: true,
useDefaultFeatures: false,
ownerFeatureCapabilities: new Map([
['vision-input', ['bmp', 'gif', 'jpeg', 'png', 'webp']],
]),
})],
['openbitfun-computer-use', dependencyProfile(['jpeg', 'png'], { useDefaultFeatures: false })],
['openbitfun-services-core', dependencyProfile([], {
optional: true,
Expand Down
1 change: 1 addition & 0 deletions scripts/core-boundaries/rules/feature-rules.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -896,6 +896,7 @@ export const coreClosedFeatureProfileRules = [
requiredFeatureRefs: [
'ai-adapter-runtime',
'openbitfun-ai-adapters/local-tokenizer',
'openbitfun-ai-adapters/vision-input',
'dep:openbitfun-agent-runtime',
'openbitfun-agent-runtime/agent-runtime',
'dep:openbitfun-agent-content',
Expand Down
17 changes: 11 additions & 6 deletions src/crates/adapters/ai-adapters/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,17 @@ provider-neutral contracts owned by `openbitfun-agent-stream`.
`cargo test --locked -p openbitfun-ai-adapters --lib providers::openai::chat::tests`.
- Do not move provider-neutral stream DTOs, replay policy, or tool-call
accumulation ownership back into this crate.
- Optional model image-input ceilings are applied to outgoing message copies at
the shared AIClient send boundary, including single-attempt Responses calls.
Count user image parts and tool attachments together; preserve durable history,
tool-result identities, opaque tool text and non-image media. Newer messages
keep their pixels first, with explicit omission text for older pixels. Verify
with `cargo test --locked -p openbitfun-ai-adapters --lib client::image_budget::tests`.
- Project images on the outgoing message copy at the shared AIClient send
boundary, including single-attempt Responses calls. Once the assistant has
answered, historical uploads and tool images carry text and available
references. Preserve tool-result identities, opaque tool text, non-image
media and durable attachments. New uploads, parallel tool results and images
produced by an explicit reread share the selected model's optional image count
limit. With `vision-input`, fit these pending images to the context remaining
after text, tools, reserved output and the safety margin.
A gateway HTTP 413 stops retries of the same body. An explicit model context
error keeps its token-overflow classification.
Verify with `cargo test --locked -p openbitfun-ai-adapters --features vision-input --lib -- client::image_budget vision_tokens oversized_http_body`.
- Normalize explicitly reported response models into the typed stream
`response_model` observation. Responses/Codex lifecycle metadata is emitted
before an associated error, and Chat Completions model identifiers remain
Expand Down
2 changes: 2 additions & 0 deletions src/crates/adapters/ai-adapters/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true }
image = { workspace = true, optional = true }
tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] }
tokio-stream = { workspace = true }
tokio-tungstenite = { workspace = true, features = ["handshake"] }
Expand All @@ -61,6 +62,7 @@ zbus-secret-service-keyring-store = { workspace = true, optional = true }
[features]
local-tokenizer = ["dep:tokenizers"]

vision-input = ["dep:base64", "dep:image", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/webp"]
image-generation = ["dep:base64"]
subscription-auth = [
"dep:apple-native-keyring-store",
Expand Down
214 changes: 194 additions & 20 deletions src/crates/adapters/ai-adapters/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::types::*;
use anyhow::Result;
use format::ApiFormat;
use log::warn;
use openbitfun_core_types::errors::AiProviderError;
use openbitfun_core_types::errors::{AiProviderError, ErrorCategory};
use reqwest::Client;
use std::time::Duration;
use std::{fmt, future::Future, pin::Pin, sync::Arc};
Expand Down Expand Up @@ -379,7 +379,10 @@ impl AIClient {
extra_body: Option<serde_json::Value>,
trace: Option<ModelExchangeTraceConfig>,
) -> Result<StreamResponse> {
self.send_message_stream_with_extra_body_and_max_attempts(
let messages = self
.prepare_message_inputs(messages, tools.as_deref(), None, extra_body.as_ref())
.await?;
self.send_prepared_message_stream(
messages,
tools,
extra_body,
Expand Down Expand Up @@ -415,15 +418,16 @@ impl AIClient {
trace: Option<ModelExchangeTraceConfig>,
) -> Result<StreamResponse> {
let custom_body = self.config.custom_request_body.clone();
self.send_message_stream_with_extra_body_and_max_attempts(
messages,
tools,
custom_body,
1,
trace,
request_context,
)
.await
let messages = self
.prepare_message_inputs(
messages,
tools.as_deref(),
request_context.as_ref(),
custom_body.as_ref(),
)
.await?;
self.send_prepared_message_stream(messages, tools, custom_body, 1, trace, request_context)
.await
}

pub async fn send_message(
Expand Down Expand Up @@ -537,9 +541,17 @@ impl AIClient {
) -> Result<GeminiResponse> {
let request_context =
crate::providers::shared::prepare_request_context(self, request_context);
let messages = self
.prepare_message_inputs(
messages,
tools.as_deref(),
request_context.as_ref(),
extra_body.as_ref(),
)
.await?;
for attempt in 0..max_attempts {
let stream_response = match self
.send_message_stream_with_extra_body_and_max_attempts(
.send_prepared_message_stream(
messages.clone(),
tools.clone(),
extra_body.clone(),
Expand All @@ -554,7 +566,9 @@ impl AIClient {
if attempt == max_attempts - 1
|| error
.downcast_ref::<AiProviderError>()
.is_some_and(|error| error.delivery_uncertain)
.is_some_and(|error| {
error.delivery_uncertain || error.http_status == Some(413)
})
{
return Err(error);
}
Expand Down Expand Up @@ -588,7 +602,9 @@ impl AIClient {
if attempt == max_attempts - 1
|| error
.downcast_ref::<AiProviderError>()
.is_some_and(|error| error.delivery_uncertain)
.is_some_and(|error| {
error.delivery_uncertain || error.http_status == Some(413)
})
{
return Err(error);
}
Expand All @@ -608,7 +624,120 @@ impl AIClient {
unreachable!("send_message retry loop always returns")
}

async fn send_message_stream_with_extra_body_and_max_attempts(
async fn prepare_message_inputs(
&self,
messages: Vec<Message>,
tools: Option<&[ToolDefinition]>,
request_context: Option<&ModelRequestContext>,
extra_body: Option<&serde_json::Value>,
) -> Result<Vec<Message>> {
// Project only the outgoing copy, against the actual selected client.
responses_websocket::validate(self)?;
// Account/channel failover and direct analysis calls share this boundary.
let messages = image_budget::project(
messages,
self.config.max_images_per_request,
request_context.and_then(|context| context.image_turn_start),
ApiFormat::parse(&self.config.format)?,
request_context.map_or_else(
|| tools.is_none_or(<[_]>::is_empty),
|context| context.retain_latest_user_image,
),
)?;
image_budget::validate_extra_body(self.config.max_images_per_request, extra_body)?;
#[cfg(feature = "vision-input")]
let replaced = image_budget::context::validate_override(
self,
&messages,
tools,
request_context,
extra_body,
)?;
#[cfg(feature = "vision-input")]
let messages = if !replaced
&& messages
.iter()
.any(image_budget::context::may_contain_images)
{
let budget = image_budget::context::Budget::for_request(
self,
tools,
request_context,
extra_body,
)?;
// Decoding and resampling a large screenshot can occupy a CPU for
// a full scheduling slice. Keep it off the async transport worker.
tokio::task::spawn_blocking(move || -> Result<_> {
let mut messages = messages;
image_budget::context::apply(&mut messages, budget)?;
Ok(messages)
})
.await??
} else {
messages
};
Ok(messages)
}

async fn send_prepared_message_stream(
&self,
messages: Vec<Message>,
tools: Option<Vec<ToolDefinition>>,
extra_body: Option<serde_json::Value>,
max_tries: usize,
trace: Option<ModelExchangeTraceConfig>,
request_context: Option<ModelRequestContext>,
) -> Result<StreamResponse> {
let can_reduce_batch = extra_body.as_ref().is_none_or(|body| {
["messages", "input", "contents"]
.iter()
.all(|key| body.get(key).is_none())
});
let Some(smaller) = can_reduce_batch
.then(|| image_budget::smaller_tool_batch(&messages))
.flatten()
else {
return self
.send_wire_message_stream(
messages,
tools,
extra_body,
max_tries,
trace,
request_context,
)
.await;
};
let outcome = self
.send_wire_message_stream(
messages,
tools.clone(),
extra_body.clone(),
max_tries,
trace.clone(),
request_context.clone(),
)
.await;
if let Err(error) = &outcome {
if error
.downcast_ref::<AiProviderError>()
.is_some_and(|error| {
error.http_status == Some(413)
&& error.category == ErrorCategory::InvalidRequest
&& !error.delivery_uncertain
})
{
// Only a confirmed byte-limit rejection is safe to resend. This
// retry changes the body and retains the tool-call protocol.
return self
.send_wire_message_stream(smaller, tools, extra_body, 1, trace, request_context)
.await;
}
}
outcome
}

async fn send_wire_message_stream(
&self,
messages: Vec<Message>,
tools: Option<Vec<ToolDefinition>>,
Expand All @@ -617,11 +746,6 @@ impl AIClient {
trace: Option<ModelExchangeTraceConfig>,
request_context: Option<ModelRequestContext>,
) -> Result<StreamResponse> {
// Project only the outgoing copy, against the actual selected client.
responses_websocket::validate(self)?;
// Account/channel failover and direct analysis calls share this boundary.
let messages = image_budget::project(messages, self.config.max_images_per_request)?;
image_budget::validate_extra_body(self.config.max_images_per_request, extra_body.as_ref())?;
match ApiFormat::parse(&self.config.format)? {
ApiFormat::OpenAIChat => {
openai::chat::send_stream(
Expand Down Expand Up @@ -953,6 +1077,7 @@ mod tests {
"type": "object",
"properties": { "summary": { "type": "string" } }
})),
..Default::default()
}
}

Expand All @@ -962,6 +1087,7 @@ mod tests {
conversation_scope: None,
prompt_cache_route_key: Some("lineage-1".to_string()),
output_schema: None,
..Default::default()
};
let official = openai::chat::build_request_body_with_context(
&make_test_client("openai", None),
Expand Down Expand Up @@ -2956,6 +3082,54 @@ mod tests {
assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn oversized_http_body_reaches_the_caller_without_a_retry() {
use axum::http::StatusCode;
use openbitfun_core_types::errors::{AiProviderError, ErrorCategory};
let attempts = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&attempts);
let app = Router::new().route(
"/chat/completions",
post(move || {
observed.fetch_add(1, Ordering::SeqCst);
async {
(
StatusCode::PAYLOAD_TOO_LARGE,
"<html><title>413 Request Entity Too Large</title></html>",
)
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let mut client = make_test_client("openai", None);
client.config.request_url =
format!("http://{}/chat/completions", listener.local_addr().unwrap());
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let messages = vec![crate::types::Message::user(
"Inspect the attachment.".into(),
)];

let streamed = client
.send_message_stream(messages.clone(), None, None)
.await
.err()
.unwrap();
let aggregated = client.send_message(messages, None).await.err().unwrap();
server.abort();

for error in [streamed, aggregated] {
let detail = error.downcast_ref::<AiProviderError>().unwrap();
assert_eq!(detail.http_status, Some(413));
assert_eq!(detail.category, ErrorCategory::InvalidRequest);
assert!(detail.message.contains("Crop images"));
}
assert_eq!(
attempts.load(Ordering::SeqCst),
2,
"one HTTP request per call"
);
}

#[test]
fn aggregated_retry_delay_grows_beyond_previous_four_second_cap() {
assert_eq!(send_message_retry_delay_ms(0, "connection reset"), 500);
Expand Down
Loading
Loading