Skip to main content

agentmux_srv_core/backend/model_gateway/
chat_adapter.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The adapter between the Anthropic Messages API, which Claude Code speaks, and OpenAI-style Chat Completions, which
5//! Amazon Ergo on Bedrock speaks (`docs/specs/SPEC_BEDROCK_MODEL_ROUTE_2026_12_01.md`, section 4.3). Pure: bytes in, bytes
6//! out, with no network, no async and no server state, so each rule is tested on its own.
7//!
8//! * [`request_to_chat`] turns a Messages request into a Chat Completions request.
9//! * [`StreamTranslator`] turns the upstream SSE answer into Messages SSE events, however the bytes are chunked.
10//! * [`chat_json_to_message`] does the same for an answer that was not streamed.
11
12use serde_json::{json, Map, Value};
13use std::fmt;
14
15/// The least output a request may ask for: Ergo reasons before it answers, so a small limit comes back empty.
16pub const MIN_OUTPUT_TOKENS: u64 = 8_192;
17/// The most output a request may ask for: the account's quota is reserved up front for the whole limit.
18pub const MAX_OUTPUT_TOKENS: u64 = 32_768;
19
20/// A thinking budget under this many tokens asks for low reasoning effort.
21const LOW_EFFORT_BELOW: u64 = 4_000;
22/// A thinking budget under this many tokens (and at least the low bound) asks for medium effort; more asks for high.
23const MEDIUM_EFFORT_BELOW: u64 = 16_000;
24/// The longest stream line held while waiting for its newline; a longer one is dropped rather than grown without end.
25const MAX_LINE: usize = 8 * 1024 * 1024;
26/// The words of the error that ends a stream which stopped before its answer was whole.
27const CUT_OFF_MESSAGE: &str = "the model's answer was cut off before it finished";
28/// The words of the error returned for an answer this module could not read.
29const UNREADABLE_MESSAGE: &str = "the model returned something this gateway could not read";
30/// The id of a message whose upstream chunks carry none.
31const FALLBACK_MESSAGE_ID: &str = "msg_chat";
32
33/// What a model asks of the request beyond Chat Completions itself. The default is Amazon Ergo's (spec 4.3): it reasons before
34/// it answers, so a small output limit comes back empty and reasoning is never off.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct ChatRules {
37    /// The least output a request may ask for, and the most.
38    pub min_output: u64,
39    pub max_output: u64,
40    /// Whether the request carries `reasoning_effort`; a model with no reasoning is not sent one.
41    pub reasoning_effort: bool,
42}
43
44impl Default for ChatRules {
45    fn default() -> Self {
46        ChatRules { min_output: MIN_OUTPUT_TOKENS, max_output: MAX_OUTPUT_TOKENS, reasoning_effort: true }
47    }
48}
49
50/// A Chat Completions request body, and whether the caller asked for a streamed answer.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct ChatRequest {
53    pub body: Vec<u8>,
54    /// What the caller asked for. The upstream is asked for a stream exactly when this is true.
55    pub stream: bool,
56}
57
58/// Why a Messages request cannot be sent to a text-only model.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum RequestError {
61    NotJson,
62    Images { count: usize, label: String },
63}
64
65impl fmt::Display for RequestError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            RequestError::NotJson => write!(f, "the request is not JSON"),
69            RequestError::Images { count, label } => {
70                let images = if *count == 1 { "1 image".to_string() } else { format!("{count} images") };
71                write!(
72                    f,
73                    "{label} reads text only; this conversation has {images}. Pick a model that reads images, or compact the conversation first"
74                )
75            }
76        }
77    }
78}
79
80impl std::error::Error for RequestError {}
81
82// ---------------------------------------------------------------------------------------------------------------------
83// Request half
84// ---------------------------------------------------------------------------------------------------------------------
85
86/// Turn a Messages request body into a Chat Completions body for `upstream_model`. `model_label` is the name a person
87/// reads in the refusal when the conversation holds images.
88pub fn request_to_chat(messages_body: &[u8], upstream_model: &str, model_label: &str) -> Result<ChatRequest, RequestError> {
89    request_to_chat_with(messages_body, upstream_model, model_label, ChatRules::default())
90}
91
92/// [`request_to_chat`] for a model with rules of its own.
93pub fn request_to_chat_with(messages_body: &[u8], upstream_model: &str, model_label: &str, rules: ChatRules) -> Result<ChatRequest, RequestError> {
94    let request: Value = serde_json::from_slice(messages_body).map_err(|_| RequestError::NotJson)?;
95    if !request.is_object() {
96        return Err(RequestError::NotJson);
97    }
98    let count = images_in_request(&request);
99    if count > 0 {
100        return Err(RequestError::Images { count, label: model_label.to_string() });
101    }
102    let stream = request.get("stream").and_then(Value::as_bool).unwrap_or(false);
103    let mut chat = Map::new();
104    chat.insert("model".into(), json!(upstream_model));
105    chat.insert("messages".into(), Value::Array(chat_messages(&request)));
106    chat.insert("stream".into(), json!(stream));
107    if stream {
108        chat.insert("stream_options".into(), json!({"include_usage": true}));
109    }
110    chat.insert("max_completion_tokens".into(), json!(output_limit(&request, rules)));
111    if rules.reasoning_effort {
112        chat.insert("reasoning_effort".into(), json!(reasoning_effort(&request)));
113    }
114    let tools = chat_tools(request.get("tools"));
115    if !tools.is_empty() {
116        chat.insert("tools".into(), Value::Array(tools));
117        if let Some(choice) = chat_tool_choice(request.get("tool_choice")) {
118            chat.insert("tool_choice".into(), choice);
119        }
120    }
121    copy_sampling(&request, &mut chat);
122    let body = serde_json::to_vec(&Value::Object(chat)).map_err(|_| RequestError::NotJson)?;
123    Ok(ChatRequest { body, stream })
124}
125
126/// Every image block in the request, also inside a tool result.
127fn images_in_request(request: &Value) -> usize {
128    let in_messages: usize =
129        request.get("messages").and_then(Value::as_array).map_or(0, |all| all.iter().map(|m| images_in_content(m.get("content"))).sum());
130    in_messages + images_in_content(request.get("system"))
131}
132
133fn images_in_content(content: Option<&Value>) -> usize {
134    let Some(blocks) = content.and_then(Value::as_array) else { return 0 };
135    blocks
136        .iter()
137        .map(|block| match block_type(block) {
138            "image" => 1,
139            "tool_result" => images_in_content(block.get("content")),
140            _ => 0,
141        })
142        .sum()
143}
144
145fn block_type(block: &Value) -> &str {
146    block.get("type").and_then(Value::as_str).unwrap_or("")
147}
148
149/// The chat messages: the system prompt first, then the conversation.
150fn chat_messages(request: &Value) -> Vec<Value> {
151    let mut out = Vec::new();
152    let system = system_text(request.get("system"));
153    if !system.is_empty() {
154        out.push(json!({"role": "system", "content": system}));
155    }
156    for message in request.get("messages").and_then(Value::as_array).into_iter().flatten() {
157        push_message(&mut out, message);
158    }
159    out
160}
161
162/// The system prompt as one string: text blocks are joined with a blank line.
163fn system_text(system: Option<&Value>) -> String {
164    match system {
165        Some(Value::String(text)) => text.clone(),
166        Some(Value::Array(blocks)) => blocks
167            .iter()
168            .filter_map(|block| block.get("text").and_then(Value::as_str))
169            .filter(|text| !text.is_empty())
170            .collect::<Vec<_>>()
171            .join("\n\n"),
172        _ => String::new(),
173    }
174}
175
176/// The text blocks of one message, joined with a newline. `cache_control` and every other field is left behind.
177fn blocks_text(blocks: &[Value]) -> String {
178    blocks
179        .iter()
180        .filter(|block| block_type(block) == "text")
181        .filter_map(|block| block.get("text").and_then(Value::as_str))
182        .collect::<Vec<_>>()
183        .join("\n")
184}
185
186fn push_message(out: &mut Vec<Value>, message: &Value) {
187    let assistant = message.get("role").and_then(Value::as_str) == Some("assistant");
188    match message.get("content") {
189        Some(Value::String(text)) if !text.is_empty() => {
190            out.push(json!({"role": if assistant { "assistant" } else { "user" }, "content": text}));
191        }
192        Some(Value::Array(blocks)) if assistant => push_assistant_blocks(out, blocks),
193        Some(Value::Array(blocks)) => push_user_blocks(out, blocks),
194        _ => {}
195    }
196}
197
198/// An assistant message: its text, and its tool uses as `tool_calls`. Thinking blocks are dropped, because their
199/// signatures mean nothing to another model.
200fn push_assistant_blocks(out: &mut Vec<Value>, blocks: &[Value]) {
201    let text = blocks_text(blocks);
202    let calls: Vec<Value> = blocks.iter().filter(|block| block_type(block) == "tool_use").filter_map(tool_call).collect();
203    if calls.is_empty() {
204        if !text.is_empty() {
205            out.push(json!({"role": "assistant", "content": text}));
206        }
207        return;
208    }
209    let content = if text.is_empty() { Value::Null } else { json!(text) };
210    out.push(json!({"role": "assistant", "content": content, "tool_calls": calls}));
211}
212
213fn tool_call(block: &Value) -> Option<Value> {
214    let id = block.get("id").and_then(Value::as_str)?;
215    let name = block.get("name").and_then(Value::as_str)?;
216    let input = block.get("input").cloned().unwrap_or_else(|| json!({}));
217    let arguments = serde_json::to_string(&input).unwrap_or_else(|_| "{}".to_string());
218    Some(json!({"id": id, "type": "function", "function": {"name": name, "arguments": arguments}}))
219}
220
221/// A user message: each tool result becomes its own `tool` message, in order, and the text that is left follows as a
222/// user message. The order matters: a tool result must come right after the assistant message that asked for it.
223fn push_user_blocks(out: &mut Vec<Value>, blocks: &[Value]) {
224    for block in blocks.iter().filter(|block| block_type(block) == "tool_result") {
225        let Some(id) = block.get("tool_use_id").and_then(Value::as_str) else { continue };
226        out.push(json!({"role": "tool", "tool_call_id": id, "content": tool_result_text(block)}));
227    }
228    let text = blocks_text(blocks);
229    if !text.is_empty() {
230        out.push(json!({"role": "user", "content": text}));
231    }
232}
233
234fn tool_result_text(block: &Value) -> String {
235    let text = match block.get("content") {
236        Some(Value::String(text)) => text.clone(),
237        Some(Value::Array(blocks)) => blocks_text(blocks),
238        _ => String::new(),
239    };
240    if block.get("is_error").and_then(Value::as_bool).unwrap_or(false) {
241        format!("Error: {text}")
242    } else {
243        text
244    }
245}
246
247/// The function tools. A tool with a `type` other than `custom` is one Anthropic runs on its side (web search, bash,
248/// text editor); nobody here can run it, so the model never sees it.
249fn chat_tools(tools: Option<&Value>) -> Vec<Value> {
250    tools.and_then(Value::as_array).map(|all| all.iter().filter_map(chat_tool).collect()).unwrap_or_default()
251}
252
253fn chat_tool(tool: &Value) -> Option<Value> {
254    match tool.get("type") {
255        None | Some(Value::Null) => {}
256        Some(Value::String(kind)) if kind == "custom" => {}
257        Some(_) => return None,
258    }
259    let name = tool.get("name").and_then(Value::as_str)?;
260    let mut function = Map::new();
261    function.insert("name".into(), json!(name));
262    if let Some(description) = tool.get("description").and_then(Value::as_str) {
263        function.insert("description".into(), json!(description));
264    }
265    let parameters = tool.get("input_schema").cloned().unwrap_or_else(|| json!({"type": "object", "properties": {}}));
266    function.insert("parameters".into(), parameters);
267    Some(json!({"type": "function", "function": function}))
268}
269
270fn chat_tool_choice(choice: Option<&Value>) -> Option<Value> {
271    let choice = choice?;
272    match choice.get("type").and_then(Value::as_str)? {
273        "auto" => Some(json!("auto")),
274        "any" => Some(json!("required")),
275        "none" => Some(json!("none")),
276        "tool" => {
277            let name = choice.get("name").and_then(Value::as_str)?;
278            Some(json!({"type": "function", "function": {"name": name}}))
279        }
280        _ => None,
281    }
282}
283
284/// The caller's `max_tokens` held between the least an answer needs and the most the quota may be asked to reserve.
285fn output_limit(request: &Value, rules: ChatRules) -> u64 {
286    match request.get("max_tokens").and_then(Value::as_u64) {
287        Some(asked) => asked.clamp(rules.min_output, rules.max_output),
288        None => rules.max_output,
289    }
290}
291
292/// Never `none`: Ergo answers badly, or not at all, with reasoning off. Thinking off or absent asks for `low`.
293fn reasoning_effort(request: &Value) -> &'static str {
294    let Some(thinking) = request.get("thinking") else { return "low" };
295    if thinking.get("type").and_then(Value::as_str) != Some("enabled") {
296        return "low";
297    }
298    match thinking.get("budget_tokens").and_then(Value::as_u64) {
299        Some(budget) if budget >= MEDIUM_EFFORT_BELOW => "high",
300        Some(budget) if budget >= LOW_EFFORT_BELOW => "medium",
301        _ => "low",
302    }
303}
304
305/// The sampling fields Chat Completions shares with Messages; every other field is dropped.
306fn copy_sampling(request: &Value, chat: &mut Map<String, Value>) {
307    for key in ["temperature", "top_p"] {
308        if let Some(value) = request.get(key).filter(|v| v.is_number()) {
309            chat.insert(key.into(), value.clone());
310        }
311    }
312    let stops: Vec<Value> = request
313        .get("stop_sequences")
314        .and_then(Value::as_array)
315        .map(|all| all.iter().filter(|s| s.is_string()).cloned().collect())
316        .unwrap_or_default();
317    if !stops.is_empty() {
318        chat.insert("stop".into(), Value::Array(stops));
319    }
320}
321
322// ---------------------------------------------------------------------------------------------------------------------
323// Shared by both response paths
324// ---------------------------------------------------------------------------------------------------------------------
325
326/// The stop reason a Chat Completions `finish_reason` becomes.
327fn stop_reason(finish_reason: &str) -> &'static str {
328    match finish_reason {
329        "length" => "max_tokens",
330        "tool_calls" => "tool_use",
331        _ => "end_turn",
332    }
333}
334
335/// What the upstream reports it used.
336#[derive(Debug, Default, Clone, Copy)]
337struct Usage {
338    prompt: u64,
339    completion: u64,
340    cached: u64,
341}
342
343impl Usage {
344    /// Read a `usage` object; `None` for anything else (`null` on most chunks).
345    fn read(usage: Option<&Value>) -> Option<Usage> {
346        let usage = usage.filter(|u| u.is_object())?;
347        let number = |value: Option<&Value>| value.and_then(Value::as_u64).unwrap_or(0);
348        Some(Usage {
349            prompt: number(usage.get("prompt_tokens")),
350            completion: number(usage.get("completion_tokens")),
351            cached: number(usage.get("prompt_tokens_details").and_then(|d| d.get("cached_tokens"))),
352        })
353    }
354
355    /// The Messages usage block: the cached part of the prompt is counted apart from the rest.
356    fn to_messages(self) -> Value {
357        json!({
358            "input_tokens": self.prompt.saturating_sub(self.cached),
359            "output_tokens": self.completion,
360            "cache_read_input_tokens": self.cached,
361        })
362    }
363}
364
365/// Write one Server-Sent Event.
366fn write_event(out: &mut Vec<u8>, name: &str, data: &Value) {
367    out.extend_from_slice(format!("event: {name}\ndata: {}\n\n", serde_json::to_string(data).unwrap_or_default()).as_bytes());
368}
369
370fn error_body(message: &str) -> Value {
371    json!({"type": "error", "error": {"type": "api_error", "message": message}})
372}
373
374/// An error that carries what the upstream says the generation used. The caller is told it failed, and the usage meter still
375/// counts the generation, which was charged for whatever became of its answer.
376fn error_with_usage(message: &str, usage: Usage) -> Value {
377    let mut body = error_body(message);
378    body["usage"] = usage.to_messages();
379    body
380}
381
382fn text_of(value: Option<&Value>) -> &str {
383    value.and_then(Value::as_str).unwrap_or("")
384}
385
386/// The reasoning text of a message or delta: providers call the field `reasoning_content` or `reasoning`.
387fn reasoning_of(part: &Value) -> &str {
388    let content = text_of(part.get("reasoning_content"));
389    if content.is_empty() {
390        text_of(part.get("reasoning"))
391    } else {
392        content
393    }
394}
395
396// ---------------------------------------------------------------------------------------------------------------------
397// Response half, streaming
398// ---------------------------------------------------------------------------------------------------------------------
399
400/// The one reasoning or text block that is open at a time. A tool call is not one of them: it is held until it is whole.
401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
402enum Block {
403    None,
404    Thinking,
405    Text,
406}
407
408/// A tool call as the upstream is sending it. Its pieces may arrive between those of another call, so it is kept until the
409/// upstream says the answer is finished, and is handed on whole.
410#[derive(Debug, Default)]
411struct Call {
412    /// The index the upstream gave it.
413    index: u64,
414    id: String,
415    name: String,
416    arguments: String,
417}
418
419/// Turns the upstream's Chat Completions SSE into Messages SSE. Feed it the bytes as they arrive, in any chunking; what
420/// comes out does not depend on where the chunks were cut.
421pub struct StreamTranslator {
422    model: String,
423    /// Bytes of a line whose newline has not arrived.
424    pending: Vec<u8>,
425    started: bool,
426    /// The message is complete (or ended in an error): nothing more is written.
427    done: bool,
428    open: Block,
429    /// The index the next content block gets.
430    next_index: u64,
431    /// The tool calls so far, in the order they began.
432    calls: Vec<Call>,
433    stop_reason: Option<&'static str>,
434    /// The answer was cut off and is to end in an error, once the usage that follows its finish reason has arrived.
435    cut_off: bool,
436    usage: Usage,
437    /// The upstream has reported usage.
438    usage_seen: bool,
439}
440
441impl StreamTranslator {
442    /// `model` is the name the caller sees in `message_start`.
443    pub fn new(model: &str) -> Self {
444        Self {
445            model: model.to_string(),
446            pending: Vec::new(),
447            started: false,
448            done: false,
449            open: Block::None,
450            next_index: 0,
451            calls: Vec::new(),
452            stop_reason: None,
453            cut_off: false,
454            usage: Usage::default(),
455            usage_seen: false,
456        }
457    }
458
459    /// Upstream bytes in, Messages SSE bytes out. A line is read once its newline has arrived.
460    pub fn push(&mut self, chunk: &[u8]) -> Vec<u8> {
461        let mut out = Vec::new();
462        if self.done {
463            return out;
464        }
465        self.pending.extend_from_slice(chunk);
466        while let Some(end) = self.pending.iter().position(|b| *b == b'\n') {
467            let line: Vec<u8> = self.pending.drain(..=end).collect();
468            self.line(&line, &mut out);
469        }
470        if self.pending.len() > MAX_LINE {
471            self.pending.clear();
472        }
473        out
474    }
475
476    /// The upstream ended, with or without `[DONE]`: close what is open, or say the answer was cut off.
477    pub fn finish(&mut self) -> Vec<u8> {
478        let mut out = Vec::new();
479        let rest = std::mem::take(&mut self.pending);
480        if !rest.is_empty() {
481            self.line(&rest, &mut out);
482        }
483        self.end(&mut out);
484        out
485    }
486
487    fn line(&mut self, raw: &[u8], out: &mut Vec<u8>) {
488        let Ok(text) = std::str::from_utf8(raw) else { return };
489        let Some(data) = text.trim().strip_prefix("data:") else { return };
490        let data = data.trim();
491        if data == "[DONE]" {
492            self.end(out);
493        } else if let Ok(chunk) = serde_json::from_str::<Value>(data) {
494            self.chunk(&chunk, out);
495        }
496    }
497
498    /// The upstream is finished. A message that never started, or a tool call that is still open, cannot be closed into
499    /// something the caller may act on, so those end in an error; anything else is closed with the stop reason it has.
500    fn end(&mut self, out: &mut Vec<u8>) {
501        if self.done {
502            return;
503        }
504        if !self.started || self.cut_off || (!self.calls.is_empty() && self.stop_reason.is_none()) {
505            self.fail(out);
506        } else {
507            self.close_message(out);
508        }
509    }
510
511    /// The answer ends in an error, with the usage the upstream has reported so far.
512    fn fail(&mut self, out: &mut Vec<u8>) {
513        let error = if self.usage_seen { error_with_usage(CUT_OFF_MESSAGE, self.usage) } else { error_body(CUT_OFF_MESSAGE) };
514        write_event(out, "error", &error);
515        self.done = true;
516    }
517
518    /// An error the upstream sent in the stream ends the answer as an error with its own words.
519    fn upstream_error(&mut self, error: &Value, out: &mut Vec<u8>) {
520        self.close_block(out);
521        let said = error.get("message").and_then(Value::as_str).or_else(|| error.as_str()).filter(|m| !m.is_empty());
522        write_event(out, "error", &error_body(said.unwrap_or(UNREADABLE_MESSAGE)));
523        self.done = true;
524    }
525
526    fn chunk(&mut self, chunk: &Value, out: &mut Vec<u8>) {
527        if self.done || !chunk.is_object() {
528            return;
529        }
530        if let Some(error) = chunk.get("error").filter(|e| e.is_object() || e.is_string()) {
531            self.upstream_error(error, out);
532            return;
533        }
534        self.start(chunk, out);
535        let usage = Usage::read(chunk.get("usage"));
536        if let Some(usage) = usage {
537            self.usage = usage;
538            self.usage_seen = true;
539        }
540        if let Some(choice) = chunk.get("choices").and_then(Value::as_array).and_then(|all| all.first()) {
541            self.choice(choice, out);
542        }
543        if !self.done && usage.is_some() {
544            if self.cut_off {
545                self.fail(out);
546            } else if self.stop_reason.is_some() {
547                self.close_message(out);
548            }
549        }
550    }
551
552    /// `message_start`, once, before the first content event.
553    fn start(&mut self, chunk: &Value, out: &mut Vec<u8>) {
554        if self.started {
555            return;
556        }
557        self.started = true;
558        let id = match text_of(chunk.get("id")) {
559            "" => FALLBACK_MESSAGE_ID.to_string(),
560            id => format!("msg_{id}"),
561        };
562        let message = json!({
563            "id": id,
564            "type": "message",
565            "role": "assistant",
566            "model": self.model,
567            "content": [],
568            "stop_reason": null,
569            "stop_sequence": null,
570            "usage": {"input_tokens": 0, "output_tokens": 1},
571        });
572        write_event(out, "message_start", &json!({"type": "message_start", "message": message}));
573    }
574
575    fn choice(&mut self, choice: &Value, out: &mut Vec<u8>) {
576        if let Some(delta) = choice.get("delta") {
577            self.text_delta(Block::Thinking, reasoning_of(delta), out);
578            self.text_delta(Block::Text, text_of(delta.get("content")), out);
579            for call in delta.get("tool_calls").and_then(Value::as_array).into_iter().flatten() {
580                self.tool_delta(call);
581            }
582        }
583        if let Some(reason) = choice.get("finish_reason").and_then(Value::as_str) {
584            self.finish_reason(reason, out);
585        }
586    }
587
588    /// Reasoning or answer text: continue the open block of that kind, or close the open one and begin a new one.
589    fn text_delta(&mut self, kind: Block, text: &str, out: &mut Vec<u8>) {
590        if text.is_empty() {
591            return;
592        }
593        if self.open != kind {
594            let begin = if kind == Block::Thinking {
595                json!({"type": "thinking", "thinking": "", "signature": ""})
596            } else {
597                json!({"type": "text", "text": ""})
598            };
599            self.open_block(kind, begin, out);
600        }
601        let delta = if kind == Block::Thinking {
602            json!({"type": "thinking_delta", "thinking": text})
603        } else {
604            json!({"type": "text_delta", "text": text})
605        };
606        self.block_delta(delta, out);
607    }
608
609    /// A tool call delta: more of the call with this index, or a new call. A call is told from the one before it by its index,
610    /// and by its id when the upstream gives every call the same index.
611    fn tool_delta(&mut self, call: &Value) {
612        let index = call.get("index").and_then(Value::as_u64).unwrap_or(0);
613        let function = call.get("function");
614        let given_id = text_of(call.get("id"));
615        let held = self.calls.iter().rposition(|c| c.index == index).filter(|at| {
616            let held_id = &self.calls[*at].id;
617            given_id.is_empty() || held_id.is_empty() || held_id == given_id
618        });
619        let at = held.unwrap_or_else(|| {
620            self.calls.push(Call { index, ..Call::default() });
621            self.calls.len() - 1
622        });
623        let held = &mut self.calls[at];
624        if held.id.is_empty() {
625            held.id = given_id.to_string();
626        }
627        if held.name.is_empty() {
628            held.name = text_of(function.and_then(|f| f.get("name"))).to_string();
629        }
630        held.arguments.push_str(text_of(function.and_then(|f| f.get("arguments"))));
631    }
632
633    /// A finish reason ends the answer: the open block closes, and the tool calls are handed on, each whole. A call whose
634    /// arguments are not whole JSON was cut off, and is reported as that and not handed on.
635    fn finish_reason(&mut self, reason: &str, out: &mut Vec<u8>) {
636        self.close_block(out);
637        if !self.calls.iter().all(|c| c.arguments.is_empty() || tool_args_whole(&c.arguments)) {
638            // The usage of this generation follows its finish reason: the error waits for it.
639            self.cut_off = true;
640            return;
641        }
642        for (n, call) in std::mem::take(&mut self.calls).into_iter().enumerate() {
643            let id = if call.id.is_empty() { format!("call_{}", n + 1) } else { call.id };
644            let begin = json!({"type": "tool_use", "id": id, "name": call.name, "input": {}});
645            let arguments = if call.arguments.is_empty() { "{}".to_string() } else { call.arguments };
646            let index = self.next_index;
647            self.next_index += 1;
648            write_event(out, "content_block_start", &json!({"type": "content_block_start", "index": index, "content_block": begin}));
649            let delta = json!({"type": "input_json_delta", "partial_json": arguments});
650            write_event(out, "content_block_delta", &json!({"type": "content_block_delta", "index": index, "delta": delta}));
651            write_event(out, "content_block_stop", &json!({"type": "content_block_stop", "index": index}));
652        }
653        self.stop_reason = Some(stop_reason(reason));
654    }
655
656    fn open_block(&mut self, kind: Block, begin: Value, out: &mut Vec<u8>) {
657        self.close_block(out);
658        let event = json!({"type": "content_block_start", "index": self.next_index, "content_block": begin});
659        write_event(out, "content_block_start", &event);
660        self.open = kind;
661        self.next_index += 1;
662    }
663
664    fn block_delta(&mut self, delta: Value, out: &mut Vec<u8>) {
665        let event = json!({"type": "content_block_delta", "index": self.next_index.saturating_sub(1), "delta": delta});
666        write_event(out, "content_block_delta", &event);
667    }
668
669    fn close_block(&mut self, out: &mut Vec<u8>) {
670        if self.open == Block::None {
671            return;
672        }
673        let event = json!({"type": "content_block_stop", "index": self.next_index.saturating_sub(1)});
674        write_event(out, "content_block_stop", &event);
675        self.open = Block::None;
676    }
677
678    /// `message_delta` with the stop reason and usage, then `message_stop`.
679    fn close_message(&mut self, out: &mut Vec<u8>) {
680        self.close_block(out);
681        let delta = json!({"stop_reason": self.stop_reason.unwrap_or("end_turn"), "stop_sequence": null});
682        write_event(out, "message_delta", &json!({"type": "message_delta", "delta": delta, "usage": self.usage.to_messages()}));
683        write_event(out, "message_stop", &json!({"type": "message_stop"}));
684        self.done = true;
685    }
686}
687
688fn tool_args_whole(arguments: &str) -> bool {
689    serde_json::from_str::<Value>(arguments).is_ok()
690}
691
692// ---------------------------------------------------------------------------------------------------------------------
693// Response half, not streamed
694// ---------------------------------------------------------------------------------------------------------------------
695
696/// Turn a Chat Completions answer into one Messages body. An answer that is not JSON, or that is an error, becomes a
697/// Messages error body.
698pub fn chat_json_to_message(body: &[u8], model: &str) -> Vec<u8> {
699    let message = match serde_json::from_slice::<Value>(body) {
700        Ok(chat) => message_from_chat(&chat, model),
701        Err(_) => error_body(UNREADABLE_MESSAGE),
702    };
703    serde_json::to_vec(&message).unwrap_or_default()
704}
705
706fn message_from_chat(chat: &Value, model: &str) -> Value {
707    if let Some(error) = chat.get("error").filter(|e| e.is_object() || e.is_string()) {
708        let message = error.get("message").and_then(Value::as_str).or_else(|| error.as_str());
709        return error_body(message.filter(|m| !m.is_empty()).unwrap_or(UNREADABLE_MESSAGE));
710    }
711    let Some(choice) = chat.get("choices").and_then(Value::as_array).and_then(|all| all.first()) else {
712        return error_body(UNREADABLE_MESSAGE);
713    };
714    let id = match text_of(chat.get("id")) {
715        "" => FALLBACK_MESSAGE_ID.to_string(),
716        id => format!("msg_{id}"),
717    };
718    let usage = Usage::read(chat.get("usage")).unwrap_or_default();
719    let reason = stop_reason(text_of(choice.get("finish_reason")));
720    // A tool call whose arguments are not whole JSON was cut off (the output limit, usually): it is reported, not made up.
721    let Some(blocks) = content_blocks(choice.get("message").unwrap_or(&Value::Null)) else { return error_with_usage(CUT_OFF_MESSAGE, usage) };
722    json!({
723        "id": id,
724        "type": "message",
725        "role": "assistant",
726        "model": model,
727        "content": blocks,
728        "stop_reason": reason,
729        "stop_sequence": null,
730        "usage": usage.to_messages(),
731    })
732}
733
734/// The answer's blocks in the order thinking, text, tool calls; `None` when a tool call's arguments are not whole JSON.
735fn content_blocks(message: &Value) -> Option<Vec<Value>> {
736    let mut blocks = Vec::new();
737    let reasoning = reasoning_of(message);
738    if !reasoning.is_empty() {
739        blocks.push(json!({"type": "thinking", "thinking": reasoning, "signature": ""}));
740    }
741    let text = answer_text(message.get("content"));
742    if !text.is_empty() {
743        blocks.push(json!({"type": "text", "text": text}));
744    }
745    for (n, call) in message.get("tool_calls").and_then(Value::as_array).into_iter().flatten().enumerate() {
746        let id = match text_of(call.get("id")) {
747            "" => format!("call_{}", n + 1),
748            id => id.to_string(),
749        };
750        let function = call.get("function");
751        let arguments = text_of(function.and_then(|f| f.get("arguments")));
752        let input = if arguments.trim().is_empty() { json!({}) } else { serde_json::from_str::<Value>(arguments).ok()? };
753        let name = text_of(function.and_then(|f| f.get("name")));
754        blocks.push(json!({"type": "tool_use", "id": id, "name": name, "input": input}));
755    }
756    Some(blocks)
757}
758
759/// The answer text: a string, or a list of text parts.
760fn answer_text(content: Option<&Value>) -> String {
761    match content {
762        Some(Value::String(text)) => text.clone(),
763        Some(Value::Array(parts)) => parts.iter().filter_map(|part| part.get("text").and_then(Value::as_str)).collect::<Vec<_>>().join(""),
764        _ => String::new(),
765    }
766}
767
768#[cfg(test)]
769#[path = "chat_adapter_tests.rs"]
770mod tests;