diff --git a/Cargo.lock b/Cargo.lock index e706a54a74..479fe6a5fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -74,17 +74,17 @@ dependencies = [ [[package]] name = "aimux-core" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa641cecf2a70d9cd1e96eaf0aae4c7af4da15dbd7fb0b58f0c9f52379d0aa5" +checksum = "0460e414dd98abf5a4f6883e313d907d8c8bb4cd36826ce0565a392b1cd62cdc" dependencies = [ "async-stream", "async-trait", "base64 0.22.1", - "chrono", "futures", "httpdate", "indexmap 2.14.1", + "jiff", "jsonschema", "rand 0.8.8", "regex", @@ -101,9 +101,9 @@ dependencies = [ [[package]] name = "aimux-provider-utils" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "902e4842e25b4e6b07dcd7ba5fe9a7e5a8caee52edc7512e3e6032e88b6d1441" +checksum = "3dfc9f79e7792a011b7fdf8e273089c685a48f3eeee7f8a29152668bc9323817" dependencies = [ "aimux-core", "aimux-stream", @@ -111,12 +111,12 @@ dependencies = [ "async-trait", "base64 0.22.1", "bytes", - "chrono", "futures", "hex", "hmac", "http", "indexmap 2.14.1", + "jiff", "reqwest 0.12.28", "rustls", "schemars 1.2.2", @@ -134,9 +134,9 @@ dependencies = [ [[package]] name = "aimux-providers" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e83a12b55088392e9963dcd7410ae129e54be0369fef0e89e371f30efed771e" +checksum = "0f7fcb84629b94c6c035297a6e163f85d1bad46cdf6bed2a7f481f8418437fbc" dependencies = [ "aimux-core", "aimux-provider-utils", @@ -145,9 +145,9 @@ dependencies = [ "async-trait", "base64 0.22.1", "bytes", - "chrono", "futures", "indexmap 2.14.1", + "jiff", "percent-encoding", "regex", "reqwest 0.12.28", @@ -162,9 +162,9 @@ dependencies = [ [[package]] name = "aimux-stream" -version = "0.6.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70177c3581792eec565226f4275b808f569c663884d8cc02d777ef077386e593" +checksum = "7949cba0110ac681c285658a1e1648550b9cc1db75fc249e7f4586a492f4a4d4" dependencies = [ "bytes", "futures", diff --git a/Cargo.toml b/Cargo.toml index cf41805fd1..464ee566cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,9 +24,9 @@ dim-agent-capabilities = { path = "crates/dim-agent-capabilities" } dim-agent-aimux = { path = "crates/dim-agent-aimux" } dim-agent-attachments = { path = "crates/dim-agent-attachments" } dim-agent-questions = { path = "crates/dim-agent-questions" } -aimux-core = { version = "=0.6.1" } -aimux-provider-utils = { version = "=0.6.1", features = ["ws"] } -aimux-providers = { version = "=0.6.1", default-features = false } +aimux-core = { version = "=0.7.0" } +aimux-provider-utils = { version = "=0.7.0", features = ["ws"] } +aimux-providers = { version = "=0.7.0", default-features = false } dim-app-server = { path = "crates/dim-app-server" } dim-session-title = { path = "crates/dim-session-title" } dim-event-hub = { path = "crates/dim-event-hub" } diff --git a/crates/dim-agent-aimux/src/request.rs b/crates/dim-agent-aimux/src/request.rs index c6ec08d0c5..eea77bb8f9 100644 --- a/crates/dim-agent-aimux/src/request.rs +++ b/crates/dim-agent-aimux/src/request.rs @@ -286,7 +286,7 @@ pub(crate) fn convert( } else { LanguageModelV4ToolChoice::None }), - tools, + tools: tools.map(Arc::from), strict_stream: Some(true), ..CallOptions::new(prompt) }; diff --git a/crates/dim-agent-aimux/tests/model_flow/native.rs b/crates/dim-agent-aimux/tests/model_flow/native.rs index e4c8f683cc..429be05344 100644 --- a/crates/dim-agent-aimux/tests/model_flow/native.rs +++ b/crates/dim-agent-aimux/tests/model_flow/native.rs @@ -5999,3 +5999,522 @@ async fn chatgpt_plan_replays_namespaced_tool_calls_without_stored_responses() { root.shutdown().await.unwrap(); server.close().await; } + +/// Every chunk of one reply, read through dim's model host at `protocol`, so +/// the assertions cover dim's own mapping of what the provider streams. +async fn host_reply( + protocol: ModelProtocol, + base_url: String, +) -> Vec> { + let root = rutis::Ctx::root().unwrap(); + root.plugin(AimuxPlugin::default()).await.unwrap(); + let host = root.get::().unwrap(); + let mut stream = host + .0 + .invoke( + Arc::new(ModelRequest::new( + "local", + "test-model", + vec![Message::text(Role::User, "question")], + )), + ModelConnection::Http(HttpModelConnection { + protocol, + base_url, + network: Default::default(), + headers: Default::default(), + bearer: None, + api_key: Some("test-key".into()), + preset: None, + }), + CancellationToken::new(), + ) + .await + .unwrap(); + let mut chunks = Vec::new(); + while let Some(chunk) = stream.next().await { + chunks.push(chunk); + } + root.shutdown().await.unwrap(); + chunks +} + +/// The reply text `chunks` carry, or the first failure as its text. +fn reply_text( + chunks: Vec>, +) -> std::result::Result { + let mut text = String::new(); + for chunk in chunks { + match chunk { + Ok(ModelChunk::Text(delta)) => text.push_str(&delta), + Ok(_) => {} + Err(error) => return Err(error.to_string()), + } + } + Ok(text) +} + +/// A signed Gemini text part closes its block, so the next part opens a new +/// one and the signature is replayed on the part that carried it +/// (arcships/aimux@b7479351, #467). The chunk is the one the provider's own +/// test reads (`aimux-providers/src/google/tests/language_model.rs`, case +/// `a_signed_part_closes_its_text_block`). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn gemini_a_signed_part_closes_its_text_block_and_replays_the_split() { + use std::sync::Mutex; + + #[derive(Clone, Default)] + struct Endpoint { + requests: Arc>>, + } + async fn respond( + State(endpoint): State, + uri: Uri, + Json(request): Json, + ) -> Response { + let turn = { + let mut requests = endpoint.requests.lock().unwrap(); + requests.push((uri, request)); + requests.len() + }; + let chunks = if turn == 1 { + vec![json!({"candidates":[{"content":{"role":"model","parts":[ + {"text":"first"}, + {"text":" block","thoughtSignature":"sig-1"}, + {"text":"second"} + ]},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":2,"totalTokenCount":3}})] + } else { + vec![ + json!({"candidates":[{"content":{"role":"model","parts":[{"text":"finished"}]},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1,"totalTokenCount":2}}), + ] + }; + Response::builder() + .status(200) + .header("content-type", "text/event-stream") + .body(Body::from(sse(chunks))) + .unwrap() + } + + let endpoint = Endpoint::default(); + let router = Router::new() + .route("/v1beta/{*path}", post(respond)) + .with_state(endpoint.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/v1beta", listener.local_addr().unwrap()); + let cancel = CancellationToken::new(); + let stop = cancel.clone(); + let join = tokio::spawn(async move { + axum::serve(listener, router) + .with_graceful_shutdown(stop.cancelled_owned()) + .await + .unwrap(); + }); + let models = Arc::new( + AimuxModels::from_config( + serde_json::from_value(json!({ + "defaultModel":{"providerId":"local","modelId":"test-model"}, + "providers":[{"id":"local","kind":"gemini","baseUrl":url,"headers":{"x-goog-api-key":"test-key"},"models":[{"id":"test-model","contextWindow":128000,"maxOutputTokens":4096,"config":{"maxTokens":4096}}]}] + })) + .unwrap(), + ) + .unwrap(), + ); + let agent = model_agent(models, None).await; + let session = agent.create_session(session_config()).await.unwrap(); + session + .submit("first".into(), InputMode::Queue, "main") + .await + .unwrap(); + session.idle("main").await.unwrap(); + let events = chain_events(&session, "main", ..).await.unwrap(); + let content = events + .iter() + .find_map(|event| match &event.kind { + EventKind::ModelContent(data) => Some(data.content.clone()), + _ => None, + }) + .unwrap_or_default(); + assert_eq!(content.len(), 2, "{content:?}"); + assert!( + matches!( + &content[0], + MessagePart::Text { + text, + provider_metadata: Some(ContentMetadata::Gemini { thought_signature }), + .. + } if text == "first block" && thought_signature == "sig-1" + ), + "{content:?}" + ); + assert!( + matches!(&content[1], MessagePart::Text { text, .. } if text == "second"), + "{content:?}" + ); + session + .submit("second".into(), InputMode::Queue, "main") + .await + .unwrap(); + session.idle("main").await.unwrap(); + let requests = endpoint.requests.lock().unwrap().clone(); + assert_eq!(requests.len(), 2, "{}", requests.len()); + let parts = requests[1].1["contents"] + .as_array() + .unwrap() + .iter() + .find(|message| message["role"] == "model") + .unwrap()["parts"] + .as_array() + .unwrap() + .clone(); + assert_eq!( + parts, + vec![ + json!({"text":"first block","thoughtSignature":"sig-1"}), + json!({"text":"second"}), + ], + "{}", + requests[1].1 + ); + drop(session); + cancel.cancel(); + join.await.unwrap(); +} + +/// A real Gemini stream signs the last part of each text block with an empty +/// part, so two signed blocks in one round keep their own text and signature +/// (arcships/aimux@b7479351, #467; the same chunk shape the provider's +/// `a_signed_part_closes_its_text_block` case carries). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn gemini_two_signed_blocks_keep_their_own_text_and_signature() { + use std::sync::Mutex; + + #[derive(Clone, Default)] + struct Endpoint { + requests: Arc>>, + } + async fn respond( + State(endpoint): State, + uri: Uri, + Json(request): Json, + ) -> Response { + let turn = { + let mut requests = endpoint.requests.lock().unwrap(); + requests.push((uri, request)); + requests.len() + }; + let chunks = if turn == 1 { + vec![json!({"candidates":[{"content":{"role":"model","parts":[ + {"text":"first"}, + {"text":"","thoughtSignature":"sig-1"}, + {"text":"second"}, + {"text":"","thoughtSignature":"sig-2"} + ]},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":2,"totalTokenCount":3}})] + } else { + vec![ + json!({"candidates":[{"content":{"role":"model","parts":[{"text":"finished"}]},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1,"totalTokenCount":2}}), + ] + }; + Response::builder() + .status(200) + .header("content-type", "text/event-stream") + .body(Body::from(sse(chunks))) + .unwrap() + } + + let endpoint = Endpoint::default(); + let router = Router::new() + .route("/v1beta/{*path}", post(respond)) + .with_state(endpoint.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/v1beta", listener.local_addr().unwrap()); + let cancel = CancellationToken::new(); + let stop = cancel.clone(); + let join = tokio::spawn(async move { + axum::serve(listener, router) + .with_graceful_shutdown(stop.cancelled_owned()) + .await + .unwrap(); + }); + let models = Arc::new( + AimuxModels::from_config( + serde_json::from_value(json!({ + "defaultModel":{"providerId":"local","modelId":"test-model"}, + "providers":[{"id":"local","kind":"gemini","baseUrl":url,"headers":{"x-goog-api-key":"test-key"},"models":[{"id":"test-model","contextWindow":128000,"maxOutputTokens":4096,"config":{"maxTokens":4096}}]}] + })) + .unwrap(), + ) + .unwrap(), + ); + let agent = model_agent(models, None).await; + let session = agent.create_session(session_config()).await.unwrap(); + session + .submit("first".into(), InputMode::Queue, "main") + .await + .unwrap(); + session.idle("main").await.unwrap(); + let events = chain_events(&session, "main", ..).await.unwrap(); + let content = events + .iter() + .find_map(|event| match &event.kind { + EventKind::ModelContent(data) => Some(data.content.clone()), + _ => None, + }) + .unwrap_or_default(); + assert_eq!(content.len(), 2, "{content:?}"); + assert!( + matches!( + &content[0], + MessagePart::Text { + text, + provider_metadata: Some(ContentMetadata::Gemini { thought_signature }), + .. + } if text == "first" && thought_signature == "sig-1" + ), + "{content:?}" + ); + assert!( + matches!( + &content[1], + MessagePart::Text { + text, + provider_metadata: Some(ContentMetadata::Gemini { thought_signature }), + .. + } if text == "second" && thought_signature == "sig-2" + ), + "{content:?}" + ); + session + .submit("second".into(), InputMode::Queue, "main") + .await + .unwrap(); + session.idle("main").await.unwrap(); + let requests = endpoint.requests.lock().unwrap().clone(); + assert_eq!(requests.len(), 2, "{}", requests.len()); + let parts = requests[1].1["contents"] + .as_array() + .unwrap() + .iter() + .find(|message| message["role"] == "model") + .unwrap()["parts"] + .as_array() + .unwrap() + .clone(); + assert_eq!( + parts, + vec![ + json!({"text":"first","thoughtSignature":"sig-1"}), + json!({"text":"second","thoughtSignature":"sig-2"}), + ], + "{}", + requests[1].1 + ); + drop(session); + cancel.cancel(); + join.await.unwrap(); +} + +/// A Gemini stream finishes once it has seen both a finish reason and usage, +/// in either order: a usage chunk followed by the finish reason ends the turn, +/// and a text chunk behind the finish reason is not read (arcships/aimux@b7479351, +/// #469; the provider pins the same shape in +/// `the_stream_ends_at_the_finish_reason_after_the_usage`). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn gemini_usage_before_the_finish_reason_finishes_the_stream() { + use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method}; + + let server = MockServer::start().await; + let body = sse(vec![ + json!({"candidates":[{"content":{"role":"model","parts":[{"text":"done"}]},"index":0}],"usageMetadata":{"promptTokenCount":1,"candidatesTokenCount":1,"totalTokenCount":2}}), + json!({"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"STOP","index":0}]}), + json!({"candidates":[{"content":{"role":"model","parts":[{"text":"late"}]},"index":0}]}), + ]); + Mock::given(method("POST")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-type", "text/event-stream") + .set_body_string(body), + ) + .mount(&server) + .await; + let chunks = host_reply(ModelProtocol::Gemini, format!("{}/v1beta", server.uri())).await; + assert_eq!( + reply_text(chunks), + Ok("done".to_owned()), + "the stream must end at the finish reason after the usage, before the trailing text" + ); +} + +/// A `usageMetadata` the schema cannot read is ignored instead of failing the +/// chunk (arcships/aimux#469 follow-up, `lenient_stream_usage`). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn gemini_a_malformed_usage_metadata_does_not_fail_the_chunk() { + use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method}; + + let server = MockServer::start().await; + let body = sse(vec![json!({ + "candidates":[{"content":{"role":"model","parts":[{"text":"done"}]},"finishReason":"STOP","index":0}], + "usageMetadata":{"promptTokenCount":"many","candidatesTokenCount":1,"totalTokenCount":2} + })]); + Mock::given(method("POST")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-type", "text/event-stream") + .set_body_string(body), + ) + .mount(&server) + .await; + let chunks = host_reply(ModelProtocol::Gemini, format!("{}/v1beta", server.uri())).await; + assert_eq!(reply_text(chunks), Ok("done".to_owned())); +} + +/// A Chat Completions `usage` the schema cannot read is ignored instead of +/// failing the chunk that carries it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn openai_chat_a_malformed_usage_does_not_fail_the_chunk() { + use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method}; + + let server = MockServer::start().await; + let body = sse(vec![json!({ + "id":"chat-1", + "choices":[{"index":0,"delta":{"content":"done"},"finish_reason":"stop"}], + "usage":{"prompt_tokens":"many","completion_tokens":1,"total_tokens":2} + })]); + Mock::given(method("POST")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-type", "text/event-stream") + .set_body_string(body), + ) + .mount(&server) + .await; + let chunks = host_reply(ModelProtocol::OpenaiChat, format!("{}/v1", server.uri())).await; + assert_eq!(reply_text(chunks), Ok("done".to_owned())); +} + +/// A refusal content part opens its own text block beside an `output_text` +/// part (arcships/aimux#466, #468). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn responses_a_refusal_beside_output_text_keeps_its_own_block() { + use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method}; + + let server = MockServer::start().await; + let body = sse(vec![ + json!({"type":"response.created","response":{"id":"resp-1","created_at":1,"model":"test-model"}}), + json!({"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg-1","role":"assistant","phase":"final_answer","content":[]}}), + json!({"type":"response.content_part.added","item_id":"msg-1","output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}), + json!({"type":"response.output_text.delta","item_id":"msg-1","output_index":0,"content_index":0,"delta":"before"}), + json!({"type":"response.content_part.added","item_id":"msg-1","output_index":0,"content_index":1,"part":{"type":"refusal","refusal":""}}), + json!({"type":"response.refusal.delta","item_id":"msg-1","output_index":0,"content_index":1,"delta":"denied"}), + json!({"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg-1","role":"assistant","phase":"final_answer","content":[]}}), + json!({"type":"response.completed","response":{"id":"resp-1","created_at":1,"model":"test-model","usage":{"input_tokens":1,"output_tokens":2}}}), + ]); + Mock::given(method("POST")) + .respond_with( + ResponseTemplate::new(200) + .insert_header("content-type", "text/event-stream") + .set_body_string(body), + ) + .mount(&server) + .await; + let root = rutis::Ctx::root().unwrap(); + root.plugin(AimuxPlugin::default()).await.unwrap(); + let host = root.get::().unwrap(); + let mut stream = host + .0 + .invoke( + Arc::new(ModelRequest::new( + "local", + "test-model", + vec![Message::text(Role::User, "question")], + )), + ModelConnection::Http(HttpModelConnection { + protocol: ModelProtocol::OpenaiResponses, + base_url: format!("{}/v1", server.uri()), + network: Default::default(), + headers: Default::default(), + bearer: None, + api_key: Some("test-key".into()), + preset: None, + }), + CancellationToken::new(), + ) + .await + .unwrap(); + let mut content = Vec::new(); + let mut text = String::new(); + while let Some(chunk) = stream.next().await { + match chunk.unwrap() { + ModelChunk::Text(delta) => text.push_str(&delta), + ModelChunk::Content(parts) => content = parts, + _ => {} + } + } + assert_eq!(text, "beforedenied"); + assert_eq!(content.len(), 2, "{content:?}"); + assert!( + matches!(&content[0], MessagePart::Text { text, .. } if text == "before"), + "{content:?}" + ); + assert!( + matches!(&content[1], MessagePart::Text { text, .. } if text == "denied"), + "{content:?}" + ); + root.shutdown().await.unwrap(); +} + +/// A Responses provider option outside the namespace schema fails before the +/// request is sent: the whole `openai` namespace is parsed against the +/// provider's own schema (arcships/aimux#328, RFC-0046 R1). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn responses_a_service_tier_outside_the_schema_fails_before_sending() { + use wiremock::MockServer; + + let server = MockServer::start().await; + let root = rutis::Ctx::root().unwrap(); + root.plugin(AimuxPlugin::default()).await.unwrap(); + let host = root.get::().unwrap(); + let mut request = ModelRequest::new( + "local", + "test-model", + vec![Message::text(Role::User, "question")], + ); + request.config = Some( + serde_json::from_value(json!({ + "providerOptions": {"openai": {"serviceTier": "turbo"}} + })) + .unwrap(), + ); + let outcome = host + .0 + .invoke( + Arc::new(request), + ModelConnection::Http(HttpModelConnection { + protocol: ModelProtocol::OpenaiResponses, + base_url: format!("{}/v1", server.uri()), + network: Default::default(), + headers: Default::default(), + bearer: None, + api_key: Some("test-key".into()), + preset: None, + }), + CancellationToken::new(), + ) + .await; + let mut failure = None; + match outcome { + Err(error) => failure = Some(error.to_string()), + Ok(mut stream) => { + while let Some(chunk) = stream.next().await { + if let Err(error) = chunk { + failure = Some(error.to_string()); + } + } + } + } + root.shutdown().await.unwrap(); + let failure = failure.unwrap_or_else(|| "the request was not refused".into()); + assert!(failure.contains("provider options"), "{failure}"); + assert!( + server.received_requests().await.unwrap().is_empty(), + "the request must not be sent" + ); +} diff --git a/crates/dim-agent-aimux/tests/vendor_contract.rs b/crates/dim-agent-aimux/tests/vendor_contract.rs index 3debd12f69..7db948fd04 100644 --- a/crates/dim-agent-aimux/tests/vendor_contract.rs +++ b/crates/dim-agent-aimux/tests/vendor_contract.rs @@ -105,6 +105,17 @@ async fn collect(model: &M, options: CallOptions) -> parts } +/// The text the reply streamed, concatenated. +fn text_of(parts: &[Outcome]) -> String { + parts + .iter() + .filter_map(|part| match part { + Ok(StreamPart::TextDelta { delta, .. }) => Some(delta.as_str()), + _ => None, + }) + .collect() +} + fn chat_model(base: &str, name: &str) -> impl LanguageModel { create_openai_compatible(OpenAICompatibleProviderSettings { name: name.into(), @@ -469,3 +480,69 @@ async fn malformed_converse_frames_never_finish_successfully() { ); } } + +/// A `refusal` that is not a text is no refusal: a compatible server that +/// sends `false` or `{}` there no longer fails the chunk or the reply +/// (arcships/aimux#461, #468). +#[tokio::test] +async fn chat_a_refusal_that_is_not_text_is_no_refusal() { + for name in ["openai", "xai"] { + let body = sse(&[ + json!({"choices":[{"index":0,"delta":{"refusal":false},"finish_reason":null}]}), + json!({"choices":[{"index":0,"delta":{"refusal":{}},"finish_reason":null}]}), + json!({"choices":[{"index":0,"delta":{"content":"answer"},"finish_reason":"stop"}]}), + ]); + let (base, _) = serve(body, "text/event-stream").await; + let parts = collect(&chat_model(&base, name), CallOptions::new(vec![])).await; + let text: String = text_of(&parts); + assert_eq!(text, "answer", "{name}: {parts:?}"); + assert!( + !parts + .iter() + .any(|part| matches!(part, Err(_) | Ok(StreamPart::Error { .. }))), + "{name}: {parts:?}" + ); + assert!( + matches!(parts.last(), Some(Ok(StreamPart::Finish { finish_reason, .. })) + if finish_reason.unified == FinishReasonUnified::Stop), + "{name}: {parts:?}" + ); + } +} + +/// A `contentBlockDelta` that names more than one known member takes the +/// first one instead of failing the frame (arcships/aimux#476, #489). +#[tokio::test] +async fn converse_a_delta_with_two_known_members_takes_the_first() { + let body = [ + frame("messageStart", json!({"role":"assistant"})), + frame( + "contentBlockDelta", + json!({"contentBlockIndex":0,"delta":{"text":"answer","citation":{"generatedContent":{}}}}), + ), + frame("contentBlockStop", json!({"contentBlockIndex":0})), + frame("messageStop", json!({"stopReason":"end_turn"})), + ] + .concat(); + let (base, _) = serve(body, "application/vnd.amazon.eventstream").await; + let provider = create_amazon_bedrock(AmazonBedrockProviderSettings { + api_key: Some(Resolvable::Value("test-key".into())), + region: Some("us-east-1".into()), + base_url: Some(base), + ..Default::default() + }) + .unwrap(); + let parts = collect(&provider.chat("anthropic.test"), CallOptions::new(vec![])).await; + assert_eq!(text_of(&parts), "answer", "{parts:?}"); + assert!( + !parts + .iter() + .any(|part| matches!(part, Err(_) | Ok(StreamPart::Error { .. }))), + "{parts:?}" + ); + assert!( + matches!(parts.last(), Some(Ok(StreamPart::Finish { finish_reason, .. })) + if finish_reason.unified != FinishReasonUnified::Error), + "{parts:?}" + ); +} diff --git a/crates/dim-modality-aimux/tests/adapter.rs b/crates/dim-modality-aimux/tests/adapter.rs index a404d03d66..09f1f0b18f 100644 --- a/crates/dim-modality-aimux/tests/adapter.rs +++ b/crates/dim-modality-aimux/tests/adapter.rs @@ -1608,3 +1608,103 @@ async fn video_server(body: Vec) -> (String, Arc>, + } + #[async_trait] + impl Fetch for BrokenBody { + async fn fetch(&self, request: FetchRequest) -> Result { + *self.requests.lock().unwrap() += 1; + let body: BoxStream<'static, Result> = + futures_util::stream::once(async { + Err(FetchError::Other( + "the connection closed while the body was read" + .to_string() + .into(), + )) + }) + .boxed(); + Ok(FetchResponse { + status: StatusCode::OK, + headers: HeaderMap::new(), + url: request.url, + body, + }) + } + } + + let dir = work_dir("image-not-replayed"); + let requests = Arc::new(Mutex::new(0)); + let fetch: FetchFunction = Arc::new(BrokenBody { + requests: requests.clone(), + }); + let adapter = Arc::new(MediaAdapter::scripted(fetch)); + let error = run( + &adapter, + job( + "openai", + "gpt-image-1", + "image", + "generate", + json!({"prompt": "a cat"}), + Vec::new(), + &dir, + ), + "https://api.openai.com/v1", + "gpt-image-1", + ) + .await + .unwrap_err(); + assert_eq!(error.code, AdapterErrorCode::ProviderError); + assert_eq!( + *requests.lock().unwrap(), + 1, + "a generation that may have reached the server must not be sent again" + ); +}