Skip to content
Open
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.

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
6 changes: 4 additions & 2 deletions src/crates/adapters/ai-adapters/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,10 @@ provider-neutral contracts owned by `openbitfun-agent-stream`.
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`.
keep their pixels first, with explicit omission text for older pixels.
With `vision-input`, the selected client's context window also determines
whether older pixels must be omitted or current screenshots resized.
Verify with `cargo test --locked -p openbitfun-ai-adapters --features vision-input --lib -- client::image_budget vision_tokens`.
- 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
91 changes: 74 additions & 17 deletions src/crates/adapters/ai-adapters/src/client.rs
Original file line number Diff line number Diff line change
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 Down Expand Up @@ -608,7 +620,55 @@ 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>> {
#[cfg(not(feature = "vision-input"))]
let _ = (tools, request_context);
// 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)?;
#[cfg(feature = "vision-input")]
let replaced = image_budget::context::validate_override(
&self.config,
&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.config,
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>>,
Expand All @@ -617,11 +677,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 +1008,7 @@ mod tests {
"type": "object",
"properties": { "summary": { "type": "string" } }
})),
..Default::default()
}
}

Expand All @@ -962,6 +1018,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
9 changes: 9 additions & 0 deletions src/crates/adapters/ai-adapters/src/client/image_budget.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
//! Model-specific image input budgets for an outgoing request copy.

#[cfg(feature = "vision-input")]
pub(super) mod context;
#[cfg(all(test, feature = "vision-input"))]
mod context_tests;

use crate::types::Message;
use anyhow::Result;
use openbitfun_core_types::errors::{AiProviderError, ErrorCategory};
Expand Down Expand Up @@ -480,6 +485,10 @@ mod tests {
let mut selected = initial.clone();
selected.config.max_images_per_request = Some(3);
let mut history = vec![tool_images("batch", 4)];
// Use actual one-pixel images so the 4K window exercises the count limit.
for image in history[0].tool_image_attachments.as_mut().unwrap() {
image.data_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII=".into();
}
tokio::time::timeout(std::time::Duration::from_secs(5), async {
initial
.send_message_once_with_trace_and_request_context(history.clone(), None, None, None)
Expand Down
Loading
Loading