Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

send the json content type on provider requests (#3360)

kt09d398720c1e
diff --git a/crates/pa-ai/src/providers/anthropic/stream_tests.rs b/crates/pa-ai/src/providers/anthropic/stream_tests.rs
index 85b6a7cbc2..122e04e4b1 100644
--- a/crates/pa-ai/src/providers/anthropic/stream_tests.rs
+++ b/crates/pa-ai/src/providers/anthropic/stream_tests.rs
@@ -142,3 +142,142 @@ data: {"type":"message_stop"}"#,
StopReason::ToolUse
);
}
+
+/// Serve one SSE script for the provider's messages POST and hand the
+/// captured request head back to the caller (the one-request mock-server
+/// harness above, plus the capture).
+async fn serve_sse_capturing_head(
+ sse: String,
+) -> (std::net::SocketAddr, tokio::sync::oneshot::Receiver<String>) {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let (head_tx, head_rx) = tokio::sync::oneshot::channel::<String>();
+ tokio::spawn(async move {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut captured = String::new();
+ let mut buffer = [0u8; 4096];
+ loop {
+ let read = socket.read(&mut buffer).await.unwrap();
+ if read == 0 {
+ break;
+ }
+ captured.push_str(&String::from_utf8_lossy(&buffer[..read]));
+ if captured.contains("\r\n\r\n") {
+ break;
+ }
+ }
+ let _ = head_tx.send(captured);
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\n\r\n{sse}",
+ sse.len()
+ );
+ socket.write_all(response.as_bytes()).await.unwrap();
+ });
+ (addr, head_rx)
+}
+
+/// The values of one wire header, case-insensitive on the name (HTTP/1.1
+/// headers are case-insensitive; a duplicated header shows up twice).
+fn wire_header_values(head: &str, name: &str) -> Vec<String> {
+ head.lines()
+ .skip(1) // the request line: POST /v1/messages HTTP/1.1
+ .filter_map(|line| line.split_once(':'))
+ .filter(|(key, _)| key.trim().eq_ignore_ascii_case(name))
+ .map(|(_, value)| value.trim().to_string())
+ .collect()
+}
+
+/// Stream the provider against the mock to completion and return the
+/// request head it put on the wire.
+async fn stream_capture_head(
+ options_headers: Option<std::collections::HashMap<String, String>>,
+) -> String {
+ // The known-green SSE script from the snapshot pin above: a thinking
+ // block, a tool call, the delta and stop events.
+ let mut sse = [
+ r#"event: message_start
+data: {"type":"message_start","message":{"id":"msg_1","usage":{"input_tokens":1,"output_tokens":2}}}"#,
+ r#"event: content_block_start
+data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}"#,
+ r#"event: content_block_delta
+data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"think"}}"#,
+ r#"event: content_block_delta
+data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig"}}"#,
+ r#"event: content_block_stop
+data: {"type":"content_block_stop","index":0}"#,
+ r#"event: content_block_start
+data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"t1","name":"lookup","input":{}}}"#,
+ r#"event: content_block_delta
+data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"a\":1}"}}"#,
+ r#"event: content_block_stop
+data: {"type":"content_block_stop","index":1}"#,
+ r#"event: message_delta
+data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":5}}"#,
+ r#"event: message_stop
+data: {"type":"message_stop"}"#,
+ ]
+ .join("\n\n");
+ sse.push_str("\n\n");
+
+ let (addr, head_rx) = serve_sse_capturing_head(sse).await;
+ let model: Model = serde_json::from_value(json!({
+ "id": "claude-test", "name": "Claude Test", "api": "anthropic-messages",
+ "provider": "anthropic", "baseUrl": format!("http://{addr}"), "reasoning": false,
+ "input": ["text"],
+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},
+ "contextWindow": 128_000, "maxTokens": 8192
+ }))
+ .unwrap();
+ let options = AnthropicOptions::from_base(StreamOptions {
+ api_key: Some("sk-ant-api-test".into()),
+ headers: options_headers,
+ ..Default::default()
+ });
+ let mut reader = stream_anthropic(
+ &model,
+ &Context {
+ system_prompt: None,
+ messages: vec![],
+ tools: None,
+ },
+ Some(&options),
+ );
+ while (reader.next_event().await).is_some() {}
+
+ let captured = head_rx.await.unwrap();
+ captured
+ .split("\r\n\r\n")
+ .next()
+ .unwrap_or(&captured)
+ .to_string()
+}
+
+/// The messages POST carries exactly one `content-type: application/json`
+/// label; a strict anthropic-compatible frontend 400s without it.
+#[tokio::test]
+async fn wire_carries_one_content_type_application_json() {
+ let head = stream_capture_head(None).await;
+ assert_eq!(
+ wire_header_values(&head, "content-type"),
+ vec!["application/json"],
+ "the wire head: {head}"
+ );
+}
+
+/// A caller-configured content-type (stream-options headers) still wins:
+/// the transport stamps its label only when the caller did not provide
+/// one, and it never duplicates the header.
+#[tokio::test]
+async fn wire_caller_content_type_override_wins() {
+ let headers = std::collections::HashMap::from([(
+ "Content-Type".to_string(),
+ "application/vnd.anthropic+json".to_string(),
+ )]);
+ let head = stream_capture_head(Some(headers)).await;
+ assert_eq!(
+ wire_header_values(&head, "content-type"),
+ vec!["application/vnd.anthropic+json"],
+ "the wire head: {head}"
+ );
+}
diff --git a/crates/pa-ai/src/providers/openai_completions/stream.rs b/crates/pa-ai/src/providers/openai_completions/stream.rs
index 03fd96a615..52b6684398 100644
--- a/crates/pa-ai/src/providers/openai_completions/stream.rs
+++ b/crates/pa-ai/src/providers/openai_completions/stream.rs
@@ -773,6 +773,11 @@ mod tests {
#[path = "stream_pins.rs"]
mod stream_pins;
+ // The wire-level pins (the request head on the wire) live in their
+ // own child module with this file's test harness.
+ #[path = "stream_wire.rs"]
+ mod stream_wire;
+
/// Serve one SSE response body for the provider's POST and return the
/// bound address.
async fn serve_sse(body: String) -> SocketAddr {
diff --git a/crates/pa-ai/src/providers/openai_completions/stream/tests/stream_wire.rs b/crates/pa-ai/src/providers/openai_completions/stream/tests/stream_wire.rs
new file mode 100644
index 0000000000..b778214848
--- /dev/null
+++ b/crates/pa-ai/src/providers/openai_completions/stream/tests/stream_wire.rs
@@ -0,0 +1,135 @@
+//! The wire-level pins: the request head the shared transport puts on
+//! the wire for a chat/completions POST. The JSON body carries exactly
+//! one `content-type: application/json` label, and a caller-configured
+//! content-type (`model.headers` or stream-options headers) still wins.
+
+use super::*;
+
+use std::net::SocketAddr;
+
+/// The known-green SSE script from the tier pins (a content chunk, a
+/// usage chunk, `[DONE]`): the stream completes so the head capture and
+/// the response both land in one test.
+fn tier_sse() -> String {
+ format!("{TIERED_CONTENT_CHUNK}{USAGE_CHUNK}{DONE}")
+}
+
+/// Serve one SSE response for the provider's POST and hand the captured
+/// request head back to the caller (the same one-request mock-server
+/// harness as [`serve_sse`], plus the capture).
+async fn serve_sse_capturing_head(
+ body: String,
+) -> (SocketAddr, tokio::sync::oneshot::Receiver<String>) {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let (head_tx, head_rx) = tokio::sync::oneshot::channel::<String>();
+ tokio::spawn(async move {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut captured = String::new();
+ let mut buffer = [0u8; 4096];
+ loop {
+ let read = socket.read(&mut buffer).await.unwrap();
+ if read == 0 {
+ break;
+ }
+ captured.push_str(&String::from_utf8_lossy(&buffer[..read]));
+ if captured.contains("\r\n\r\n") {
+ break;
+ }
+ }
+ let _ = head_tx.send(captured);
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ socket.write_all(response.as_bytes()).await.unwrap();
+ });
+ (addr, head_rx)
+}
+
+/// Stream the provider against the mock to completion and return the
+/// request head it put on the wire.
+async fn stream_capture_head(
+ model: Value,
+ headers: Option<std::collections::HashMap<String, String>>,
+) -> String {
+ let (addr, head_rx) = serve_sse_capturing_head(tier_sse()).await;
+ let mut model = model;
+ model["baseUrl"] = json!(format!("http://{addr}"));
+ let model: Model = serde_json::from_value(model).unwrap();
+ let options = OpenAICompletionsOptions::from_base(crate::types::StreamOptions {
+ api_key: Some("test".into()),
+ headers,
+ ..Default::default()
+ });
+ let mut reader = stream_openai_completions(
+ &model,
+ &Context {
+ system_prompt: None,
+ messages: vec![],
+ tools: None,
+ },
+ Some(&options),
+ );
+ loop {
+ let event = reader.next_event().await.unwrap();
+ if let AssistantMessageEvent::Done { .. } = event {
+ break;
+ }
+ if let AssistantMessageEvent::Error { error, .. } = event {
+ panic!("stream failed: {:?}", error.error_message);
+ }
+ }
+ let captured = head_rx.await.unwrap();
+ captured
+ .split("\r\n\r\n")
+ .next()
+ .unwrap_or(&captured)
+ .to_string()
+}
+
+/// The values of one wire header, case-insensitive on the name (HTTP/1.1
+/// headers are case-insensitive; a duplicated header shows up twice).
+fn header_values(head: &str, name: &str) -> Vec<String> {
+ head.lines()
+ .skip(1) // the request line: POST /chat/completions HTTP/1.1
+ .filter_map(|line| line.split_once(':'))
+ .filter(|(key, _)| key.trim().eq_ignore_ascii_case(name))
+ .map(|(_, value)| value.trim().to_string())
+ .collect()
+}
+
+/// The chat/completions POST carries exactly one
+/// `content-type: application/json` label; a strict OpenAI-compatible
+/// frontend 400s without it.
+#[tokio::test]
+async fn wire_carries_one_content_type_application_json() {
+ let head = stream_capture_head(completions_model("gpt-5.5", "openai", 1.0, 1.0), None).await;
+ assert_eq!(
+ header_values(&head, "content-type"),
+ vec!["application/json"],
+ "the wire head: {head}"
+ );
+}
+
+/// A caller-configured content-type (stream-options headers) still wins:
+/// the transport stamps its label only when the caller did not provide
+/// one, and it never duplicates the header.
+#[tokio::test]
+async fn wire_caller_content_type_override_wins() {
+ let headers = std::collections::HashMap::from([(
+ "Content-Type".to_string(),
+ "application/vnd.api+json".to_string(),
+ )]);
+ let head = stream_capture_head(
+ completions_model("gpt-5.5", "openai", 1.0, 1.0),
+ Some(headers),
+ )
+ .await;
+ assert_eq!(
+ header_values(&head, "content-type"),
+ vec!["application/vnd.api+json"],
+ "the wire head: {head}"
+ );
+}
diff --git a/crates/pa-ai/src/utils_inner/http.rs b/crates/pa-ai/src/utils_inner/http.rs
index f895860a9b..5dae3e0bd9 100644
--- a/crates/pa-ai/src/utils_inner/http.rs
+++ b/crates/pa-ai/src/utils_inner/http.rs
@@ -208,6 +208,19 @@ pub async fn send(request: RequestOptions) -> Result<HttpResponse, ProviderError
for (name, value) in &request.headers {
builder = builder.header(name, value);
}
+ // A JSON request body carries `content-type: application/json` —
+ // strict OpenAI-compatible frontends (self-hosted vLLM) validate the
+ // media type and 400 a label-less body. A caller-supplied label
+ // (bedrock's signed set, mistral's, a user's `model.headers`/
+ // options override) always wins.
+ if request.body.is_some()
+ && !request
+ .headers
+ .iter()
+ .any(|(name, _)| name.eq_ignore_ascii_case("content-type"))
+ {
+ builder = builder.header("content-type", "application/json");
+ }
if let Some(body) = &request.body {
builder = builder.body(body.clone());
}