Skip to main content

graphrt_llm/
anthropic.rs

1//! Anthropic Messages API provider (streaming, tool use, extended thinking).
2//!
3//! Extended thinking is enabled through [`ChatRequest::extra`], e.g.
4//! `{"thinking": {"type": "enabled", "budget_tokens": 2048}}`. Signed thinking
5//! blocks are returned as provider state and replayed on the next turn, which
6//! the API requires when thinking is combined with tool use.
7
8use std::collections::HashMap;
9use std::fmt;
10use std::sync::Arc;
11use std::time::Duration;
12
13use futures::future::BoxFuture;
14use graphrt_core::event::Usage;
15use serde_json::{Map, Value as Json, json};
16
17use crate::credentials::{Credential, CredentialSource};
18use crate::error::LlmError;
19use crate::http::{Decoded, SseDecoder, send_sse};
20use crate::sse::SseEvent;
21use crate::types::{
22    ChatDelta, ChatModel, ChatRequest, ChatStream, ContentPart, FinishReason, Message, ResponseFormat, Role,
23    ToolChoice, check_extra,
24};
25
26/// API version header value.
27pub const ANTHROPIC_VERSION: &str = "2023-06-01";
28/// `max_tokens` used when the request does not set one (the API requires it).
29pub const DEFAULT_MAX_TOKENS: u32 = 4096;
30
31/// Configuration of the Anthropic endpoint.
32#[derive(Clone)]
33pub struct AnthropicConfig {
34    /// Base URL without `/v1/messages`.
35    pub base_url: String,
36    pub api_key: Option<String>,
37    /// Extra headers (e.g. `anthropic-beta`).
38    pub headers: Vec<(String, String)>,
39    pub connect_timeout: Duration,
40    /// Per-request credential source. When set it replaces `api_key`; its headers are
41    /// appended and its `base_url`, if any, overrides `base_url`. A 401/403 response
42    /// invalidates the credential and the request is retried once.
43    pub credentials: Option<Arc<dyn CredentialSource>>,
44    /// Provider name passed to the credential source (default `anthropic`).
45    pub credential_name: String,
46}
47
48impl fmt::Debug for AnthropicConfig {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        f.debug_struct("AnthropicConfig")
51            .field("base_url", &self.base_url)
52            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
53            .field("headers", &self.headers.iter().map(|(k, _)| k).collect::<Vec<_>>())
54            .field("credentials", &self.credentials.as_ref().map(|_| "<source>"))
55            .field("credential_name", &self.credential_name)
56            .finish_non_exhaustive()
57    }
58}
59
60impl Default for AnthropicConfig {
61    fn default() -> Self {
62        Self {
63            base_url: "https://api.anthropic.com".to_owned(),
64            api_key: None,
65            headers: Vec::new(),
66            connect_timeout: Duration::from_secs(10),
67            credentials: None,
68            credential_name: "anthropic".to_owned(),
69        }
70    }
71}
72
73impl AnthropicConfig {
74    pub fn new(api_key: impl Into<String>) -> Self {
75        Self { api_key: Some(api_key.into()), ..Self::default() }
76    }
77
78    /// Ask `source` for a credential before every request (see [`crate::credentials`]).
79    pub fn with_credentials(mut self, source: Arc<dyn CredentialSource>) -> Self {
80        self.credentials = Some(source);
81        self
82    }
83
84    /// Provider name passed to the credential source.
85    pub fn credential_name(mut self, name: impl Into<String>) -> Self {
86        self.credential_name = name.into();
87        self
88    }
89}
90
91/// Anthropic chat model endpoint.
92#[derive(Clone)]
93pub struct AnthropicModel {
94    config: AnthropicConfig,
95    client: crate::http::LazyClient,
96}
97
98impl fmt::Debug for AnthropicModel {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.debug_struct("AnthropicModel").field("config", &self.config).finish_non_exhaustive()
101    }
102}
103
104impl AnthropicModel {
105    pub fn new(config: AnthropicConfig) -> Result<Self, LlmError> {
106        let client = crate::http::LazyClient::new(config.connect_timeout);
107        Ok(Self { config, client })
108    }
109}
110
111impl AnthropicModel {
112    fn request(&self, body: &Json, credential: Option<&Credential>) -> Result<reqwest::RequestBuilder, LlmError> {
113        let endpoint =
114            crate::http::resolve_endpoint(&self.config.base_url, credential.and_then(|c| c.base_url.as_deref()))?;
115        let url = format!("{}/v1/messages", endpoint.base_url.trim_end_matches('/'));
116        let mut builder = self.client.get()?.post(url).json(body).header("anthropic-version", ANTHROPIC_VERSION);
117        let key = credential.map(|c| c.secret.as_str()).or(self.config.api_key.as_deref());
118        if let Some(key) = key {
119            builder = builder.header("x-api-key", key);
120        }
121        if endpoint.send_static {
122            for (k, v) in &self.config.headers {
123                builder = builder.header(k.as_str(), v.as_str());
124            }
125        }
126        if let Some(credential) = credential {
127            for (k, v) in &credential.headers {
128                builder = builder.header(k.as_str(), v.as_str());
129            }
130        }
131        Ok(builder)
132    }
133}
134
135impl ChatModel for AnthropicModel {
136    fn chat(&self, request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
137        Box::pin(async move {
138            let body = build_body(&request)?;
139            let name = self.config.credential_name.as_str();
140            let mut retried = false;
141            loop {
142                let credential = match &self.config.credentials {
143                    Some(source) => Some(source.credential(name).await?),
144                    None => None,
145                };
146                let result = send_sse(self.request(&body, credential.as_ref())?, AnthropicDecoder::default()).await;
147                match (result, &self.config.credentials) {
148                    // The credential was rejected: drop it and retry once with a fresh one.
149                    (Err(LlmError::Auth(_)), Some(source)) if !retried => {
150                        source.invalidate(name);
151                        retried = true;
152                    }
153                    (result, _) => return result,
154                }
155            }
156        })
157    }
158}
159
160/// Convert an image URL into an Anthropic image source (`url` or inline `base64`).
161fn image_source(url: &str) -> Json {
162    if let Some(rest) = url.strip_prefix("data:")
163        && let Some((meta, data)) = rest.split_once(',')
164        && let Some(media_type) = meta.strip_suffix(";base64")
165    {
166        return json!({"type": "base64", "media_type": media_type, "data": data});
167    }
168    json!({"type": "url", "url": url})
169}
170
171fn content_blocks(parts: &[ContentPart]) -> Vec<Json> {
172    parts
173        .iter()
174        .filter_map(|p| match p {
175            ContentPart::Text { text } if text.is_empty() => None,
176            ContentPart::Text { text } => Some(json!({"type": "text", "text": text})),
177            ContentPart::Image { url, .. } => Some(json!({"type": "image", "source": image_source(url)})),
178        })
179        .collect()
180}
181
182/// `tool_result.content`: the text, or text and image blocks when the tool
183/// returned images (Anthropic accepts images inside tool results).
184fn tool_result_content(m: &Message) -> Json {
185    if m.images().next().is_none() {
186        return Json::String(m.text());
187    }
188    Json::Array(content_blocks(&m.content))
189}
190
191/// Build the JSON request body.
192pub(crate) fn build_body(req: &ChatRequest) -> Result<Json, LlmError> {
193    check_extra(req)?;
194    let mut system_parts: Vec<String> = Vec::new();
195    // (role, blocks); consecutive messages with the same role are merged, as the API requires alternation.
196    let mut turns: Vec<(&'static str, Vec<Json>)> = Vec::new();
197    let mut push = |role: &'static str, blocks: Vec<Json>| {
198        if blocks.is_empty() {
199            return;
200        }
201        match turns.last_mut() {
202            Some((last_role, last_blocks)) if *last_role == role => last_blocks.extend(blocks),
203            _ => turns.push((role, blocks)),
204        }
205    };
206    for m in &req.messages {
207        match m.role {
208            Role::System => system_parts.push(m.text()),
209            Role::User => push("user", content_blocks(&m.content)),
210            Role::Tool => {
211                let id = m
212                    .tool_call_id
213                    .as_deref()
214                    .filter(|id| !id.is_empty())
215                    .ok_or_else(|| LlmError::Config("tool message without tool_call_id".into()))?;
216                push(
217                    "user",
218                    vec![json!({"type": "tool_result", "tool_use_id": id, "content": tool_result_content(m)})],
219                );
220            }
221            Role::Assistant => {
222                let mut blocks = Vec::new();
223                if let Some(Json::Array(state)) = &m.provider_state {
224                    blocks.extend(state.iter().cloned());
225                }
226                blocks.extend(content_blocks(&m.content));
227                for c in &m.tool_calls {
228                    // The API needs the input as an object; a malformed call must not be replayed as `{}`.
229                    let input = c.arguments_json().map_err(|e| LlmError::Config(e.to_string()))?;
230                    blocks.push(json!({"type": "tool_use", "id": c.id, "name": c.name, "input": input}));
231                }
232                push("assistant", blocks);
233            }
234        }
235    }
236
237    match &req.response_format {
238        Some(ResponseFormat::JsonObject) => {
239            system_parts.push("Respond with a single valid JSON object and nothing else.".to_owned());
240        }
241        Some(ResponseFormat::JsonSchema { schema, .. }) => system_parts.push(format!(
242            "Respond with a single valid JSON value matching this JSON Schema and nothing else:\n{schema}"
243        )),
244        None | Some(ResponseFormat::Text) => {}
245    }
246
247    let mut body = Map::new();
248    body.insert("model".into(), json!(req.model));
249    body.insert("max_tokens".into(), json!(req.max_tokens.unwrap_or(DEFAULT_MAX_TOKENS)));
250    body.insert("stream".into(), json!(true));
251    let system: Vec<&String> = system_parts.iter().filter(|s| !s.is_empty()).collect();
252    if !system.is_empty() {
253        let joined: Vec<&str> = system.iter().map(|s| s.as_str()).collect();
254        body.insert("system".into(), json!(joined.join("\n\n")));
255    }
256    let messages: Vec<Json> =
257        turns.into_iter().map(|(role, blocks)| json!({"role": role, "content": blocks})).collect();
258    body.insert("messages".into(), Json::Array(messages));
259    if !req.tools.is_empty() {
260        let tools: Vec<Json> = req
261            .tools
262            .iter()
263            .map(|t| json!({"name": t.name, "description": t.description, "input_schema": t.parameters}))
264            .collect();
265        body.insert("tools".into(), Json::Array(tools));
266    }
267    if let Some(choice) = &req.tool_choice {
268        let v = match choice {
269            ToolChoice::Auto => json!({"type": "auto"}),
270            ToolChoice::None => json!({"type": "none"}),
271            ToolChoice::Required => json!({"type": "any"}),
272            ToolChoice::Tool(name) => json!({"type": "tool", "name": name}),
273        };
274        body.insert("tool_choice".into(), v);
275    }
276    if let Some(t) = req.temperature {
277        body.insert("temperature".into(), json!(t));
278    }
279    if let Some(p) = req.top_p {
280        body.insert("top_p".into(), json!(p));
281    }
282    if !req.stop.is_empty() {
283        body.insert("stop_sequences".into(), json!(req.stop));
284    }
285    for (k, v) in &req.extra {
286        body.insert(k.clone(), v.clone());
287    }
288    Ok(Json::Object(body))
289}
290
291/// Kind of an open content block.
292#[derive(Debug)]
293enum Block {
294    Text,
295    ToolUse { call_index: usize },
296    Thinking { thinking: String, signature: String },
297    RedactedThinking { data: String },
298    Other,
299}
300
301/// Decodes Messages API stream events.
302#[derive(Debug, Default)]
303pub(crate) struct AnthropicDecoder {
304    blocks: HashMap<u64, Block>,
305    tool_calls: usize,
306    usage: Usage,
307    /// Completed thinking blocks, replayed as provider state.
308    thinking: Vec<Json>,
309}
310
311fn unknown_block(delta_type: &str, index: u64) -> LlmError {
312    LlmError::Decode(format!("`{delta_type}` for content block {index}, which is not an open block of that kind"))
313}
314
315fn stop_reason(s: &str) -> FinishReason {
316    match s {
317        "end_turn" | "stop_sequence" => FinishReason::Stop,
318        "max_tokens" => FinishReason::Length,
319        "tool_use" => FinishReason::ToolCalls,
320        "refusal" => FinishReason::ContentFilter,
321        other => FinishReason::Other(other.to_owned()),
322    }
323}
324
325impl AnthropicDecoder {
326    fn usage_delta(&mut self, usage: &Json) -> ChatDelta {
327        if let Some(n) = usage.get("input_tokens").and_then(Json::as_u64) {
328            self.usage.prompt_tokens = n;
329        }
330        if let Some(n) = usage.get("output_tokens").and_then(Json::as_u64) {
331            self.usage.completion_tokens = n;
332        }
333        self.usage.total_tokens = self.usage.prompt_tokens.saturating_add(self.usage.completion_tokens);
334        ChatDelta::Usage(self.usage)
335    }
336}
337
338impl SseDecoder for AnthropicDecoder {
339    fn decode(&mut self, event: SseEvent) -> Result<Decoded, LlmError> {
340        if event.data.trim().is_empty() {
341            return Ok(Decoded::default());
342        }
343        let v: Json =
344            serde_json::from_str(&event.data).map_err(|e| LlmError::Decode(format!("{e}: {}", event.data)))?;
345        let kind = v.get("type").and_then(Json::as_str).unwrap_or_default();
346        let index = v.get("index").and_then(Json::as_u64).unwrap_or(0);
347        let mut out = Vec::new();
348        match kind {
349            "message_start" => {
350                if let Some(u) = v.get("message").and_then(|m| m.get("usage")) {
351                    out.push(self.usage_delta(u));
352                }
353            }
354            "content_block_start" => {
355                let block = v.get("content_block").cloned().unwrap_or(Json::Null);
356                let block_type = block.get("type").and_then(Json::as_str).unwrap_or_default();
357                let state = match block_type {
358                    "text" => {
359                        if let Some(t) = block.get("text").and_then(Json::as_str).filter(|t| !t.is_empty()) {
360                            out.push(ChatDelta::Text(t.to_owned()));
361                        }
362                        Block::Text
363                    }
364                    "tool_use" => {
365                        let call_index = self.tool_calls;
366                        self.tool_calls += 1;
367                        // Some servers send the full input up front; it is normally `{}` followed by deltas.
368                        let initial = block
369                            .get("input")
370                            .filter(|i| i.as_object().is_some_and(|o| !o.is_empty()))
371                            .map(Json::to_string)
372                            .unwrap_or_default();
373                        out.push(ChatDelta::ToolCall {
374                            index: call_index,
375                            id: block.get("id").and_then(Json::as_str).map(str::to_owned),
376                            name: block.get("name").and_then(Json::as_str).map(str::to_owned),
377                            arguments: initial,
378                        });
379                        Block::ToolUse { call_index }
380                    }
381                    "thinking" => Block::Thinking {
382                        thinking: block.get("thinking").and_then(Json::as_str).unwrap_or_default().to_owned(),
383                        signature: block.get("signature").and_then(Json::as_str).unwrap_or_default().to_owned(),
384                    },
385                    "redacted_thinking" => Block::RedactedThinking {
386                        data: block.get("data").and_then(Json::as_str).unwrap_or_default().to_owned(),
387                    },
388                    _ => Block::Other,
389                };
390                self.blocks.insert(index, state);
391            }
392            "content_block_delta" => {
393                let delta = v.get("delta").cloned().unwrap_or(Json::Null);
394                let delta_type = delta.get("type").and_then(Json::as_str).unwrap_or_default();
395                let field = |name: &str| delta.get(name).and_then(Json::as_str).unwrap_or_default().to_owned();
396                match (delta_type, self.blocks.get_mut(&index)) {
397                    ("text_delta", _) => out.push(ChatDelta::Text(field("text"))),
398                    ("input_json_delta", Some(Block::ToolUse { call_index })) => out.push(ChatDelta::ToolCall {
399                        index: *call_index,
400                        id: None,
401                        name: None,
402                        arguments: field("partial_json"),
403                    }),
404                    ("input_json_delta", _) => return Err(unknown_block(delta_type, index)),
405                    ("thinking_delta", Some(Block::Thinking { thinking, .. })) => {
406                        let t = field("thinking");
407                        thinking.push_str(&t);
408                        out.push(ChatDelta::Reasoning(t));
409                    }
410                    ("thinking_delta", _) => out.push(ChatDelta::Reasoning(field("thinking"))),
411                    ("signature_delta", Some(Block::Thinking { signature, .. })) => {
412                        signature.push_str(&field("signature"))
413                    }
414                    // A lost signature would make the next turn fail; report it now.
415                    ("signature_delta", _) => return Err(unknown_block(delta_type, index)),
416                    _ => {} // citations and future delta types carry nothing we use
417                }
418            }
419            "content_block_stop" => match self.blocks.remove(&index) {
420                Some(Block::Thinking { thinking, signature }) => {
421                    self.thinking.push(json!({"type": "thinking", "thinking": thinking, "signature": signature}));
422                }
423                Some(Block::RedactedThinking { data }) => {
424                    self.thinking.push(json!({"type": "redacted_thinking", "data": data}));
425                }
426                _ => {}
427            },
428            "message_delta" => {
429                if let Some(reason) = v.get("delta").and_then(|d| d.get("stop_reason")).and_then(Json::as_str) {
430                    out.push(ChatDelta::Finish(stop_reason(reason)));
431                }
432                if let Some(u) = v.get("usage") {
433                    out.push(self.usage_delta(u));
434                }
435            }
436            "message_stop" => {
437                if !self.thinking.is_empty() {
438                    out.push(ChatDelta::ProviderState(Json::Array(std::mem::take(&mut self.thinking))));
439                }
440                return Ok(Decoded::done(out));
441            }
442            "error" => {
443                let err = v.get("error").cloned().unwrap_or(Json::Null);
444                let message = err.get("message").and_then(Json::as_str).unwrap_or("stream error").to_owned();
445                let err_type = err.get("type").and_then(Json::as_str).unwrap_or_default();
446                return Err(match err_type {
447                    "overloaded_error" | "api_error" => LlmError::Server { status: 529, message },
448                    "rate_limit_error" => LlmError::RateLimit { message, retry_after_ms: None },
449                    "authentication_error" | "permission_error" => LlmError::Auth(message),
450                    _ => LlmError::BadRequest(message),
451                });
452            }
453            _ => {} // ping and future event types
454        }
455        Ok(Decoded::deltas(out))
456    }
457}
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462    use crate::sse::SseParser;
463    use crate::types::{ToolCall, collect};
464    use graphrt_core::tool::ToolSpec;
465
466    #[test]
467    fn body_shape() {
468        let mut assistant = Message::assistant("let me check");
469        assistant.tool_calls = vec![ToolCall { id: "tu1".into(), name: "get".into(), arguments: "{\"a\":1}".into() }];
470        assistant.provider_state = Some(json!([{"type": "thinking", "thinking": "t", "signature": "s"}]));
471        let mut req = ChatRequest::new(
472            "claude-sonnet",
473            vec![
474                Message::system("be brief"),
475                Message::user("hi"),
476                Message {
477                    role: Role::User,
478                    content: vec![ContentPart::Image { url: "data:image/png;base64,AAAA".into(), detail: None }],
479                    tool_calls: vec![],
480                    tool_call_id: None,
481                    provider_state: None,
482                },
483                assistant,
484                Message::tool("tu1", "42"),
485                Message::tool("tu2", "43"),
486            ],
487        );
488        req.tools =
489            vec![ToolSpec { name: "get".into(), description: "d".into(), parameters: json!({"type": "object"}) }];
490        req.tool_choice = Some(ToolChoice::Required);
491        req.stop = vec!["END".into()];
492        req.response_format = Some(ResponseFormat::JsonObject);
493        let body = build_body(&req).unwrap();
494        assert_eq!(body["max_tokens"], DEFAULT_MAX_TOKENS);
495        assert!(body["system"].as_str().unwrap().starts_with("be brief"));
496        let msgs = body["messages"].as_array().unwrap();
497        assert_eq!(msgs.len(), 3, "consecutive user turns and tool results are merged");
498        assert_eq!(msgs[0]["content"][1]["source"]["type"], "base64");
499        assert_eq!(msgs[0]["content"][1]["source"]["media_type"], "image/png");
500        assert_eq!(msgs[1]["content"][0]["type"], "thinking");
501        assert_eq!(msgs[1]["content"][2]["input"]["a"], 1);
502        assert_eq!(msgs[2]["content"][1]["tool_use_id"], "tu2");
503        assert_eq!(body["tools"][0]["input_schema"]["type"], "object");
504        assert_eq!(body["tool_choice"]["type"], "any");
505        assert_eq!(body["stop_sequences"][0], "END");
506    }
507
508    #[test]
509    fn tool_images_are_sent_inside_the_tool_result() {
510        let mut assistant = Message::assistant("");
511        assistant.tool_calls = vec![ToolCall { id: "tu1".into(), name: "screenshot".into(), arguments: "{}".into() }];
512        let req = ChatRequest::new(
513            "claude-sonnet",
514            vec![
515                Message::user("look"),
516                assistant,
517                Message::tool_with_images(
518                    "tu1",
519                    "1280x800",
520                    ["data:image/png;base64,AAAA".to_owned(), "https://x/a.jpg".to_owned()],
521                ),
522            ],
523        );
524        let body = build_body(&req).unwrap();
525        assert_eq!(
526            body["messages"][2],
527            json!({"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu1", "content": [
528                {"type": "text", "text": "1280x800"},
529                {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "AAAA"}},
530                {"type": "image", "source": {"type": "url", "url": "https://x/a.jpg"}}
531            ]}]})
532        );
533        // Without images the content stays a plain string.
534        let req = ChatRequest::new("m", vec![Message::user("x"), req.messages[1].clone(), Message::tool("tu1", "ok")]);
535        assert_eq!(build_body(&req).unwrap()["messages"][2]["content"][0]["content"], "ok");
536    }
537
538    const FIXTURE: &str = concat!(
539        "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":10,\"output_tokens\":1}}}\n\n",
540        "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\"}}\n\n",
541        "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"thinking_delta\",\"thinking\":\"hmm\"}}\n\n",
542        "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"signature_delta\",\"signature\":\"sig\"}}\n\n",
543        "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
544        "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n",
545        "event: ping\ndata: {\"type\":\"ping\"}\n\n",
546        "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":1,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hi\"}}\n\n",
547        "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":1}\n\n",
548        "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":2,\"content_block\":{\"type\":\"tool_use\",\"id\":\"tu_1\",\"name\":\"get\",\"input\":{}}}\n\n",
549        "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":2,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{\\\"a\\\":\"}}\n\n",
550        "event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":2,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"2}\"}}\n\n",
551        "event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":2}\n\n",
552        "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\"},\"usage\":{\"output_tokens\":20}}\n\n",
553        "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n",
554    );
555
556    #[tokio::test]
557    async fn decode_recorded_stream() {
558        let (deltas, done) = decode_all(FIXTURE);
559        assert!(done);
560        let deltas: Vec<Result<ChatDelta, LlmError>> = deltas.into_iter().map(Ok).collect();
561        let r = collect(Box::pin(futures::stream::iter(deltas)), |_| {}).await.unwrap();
562        assert_eq!(r.text, "Hi");
563        assert_eq!(r.reasoning, "hmm");
564        assert_eq!(
565            r.tool_calls,
566            vec![ToolCall { id: "tu_1".into(), name: "get".into(), arguments: "{\"a\":2}".into() }]
567        );
568        assert_eq!(r.usage, Usage { prompt_tokens: 10, completion_tokens: 20, total_tokens: 30 });
569        assert_eq!(r.finish_reason, Some(FinishReason::ToolCalls));
570        assert_eq!(r.provider_state, Some(json!([{"type": "thinking", "thinking": "hmm", "signature": "sig"}])));
571        // The provider state is replayed into the next request.
572        let body = build_body(&ChatRequest::new("m", vec![r.to_message()])).unwrap();
573        assert_eq!(body["messages"][0]["content"][0]["signature"], "sig");
574    }
575
576    /// Decode a fixture; returns the deltas and whether `message_stop` was seen.
577    fn decode_all(fixture: &str) -> (Vec<ChatDelta>, bool) {
578        let mut parser = SseParser::new();
579        let mut decoder = AnthropicDecoder::default();
580        let mut deltas = Vec::new();
581        for ev in parser.push(fixture.as_bytes()).unwrap() {
582            let d = decoder.decode(ev).unwrap();
583            deltas.extend(d.deltas);
584            if d.done {
585                return (deltas, true);
586            }
587        }
588        (deltas, false)
589    }
590
591    #[test]
592    fn stream_without_message_stop_is_truncated() {
593        let cut = FIXTURE.split("event: message_delta").next().unwrap();
594        let (_, done) = decode_all(cut);
595        assert!(!done);
596        let mut decoder = AnthropicDecoder::default();
597        let err = decoder.end_of_stream().unwrap_err();
598        assert!(matches!(err, LlmError::Network(_)) && err.is_retryable());
599    }
600
601    #[test]
602    fn deltas_for_unknown_blocks_are_errors() {
603        let mut d = AnthropicDecoder::default();
604        let ev = SseEvent {
605            data: "{\"type\":\"content_block_delta\",\"index\":4,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{}\"}}".into(),
606            ..SseEvent::default()
607        };
608        assert!(matches!(d.decode(ev), Err(LlmError::Decode(_))));
609    }
610
611    #[test]
612    fn malformed_tool_arguments_are_not_replayed_as_empty_input() {
613        let mut assistant = Message::assistant("");
614        assistant.tool_calls = vec![ToolCall { id: "t".into(), name: "get".into(), arguments: "{\"a\":".into() }];
615        let req = ChatRequest::new("m", vec![Message::user("x"), assistant, Message::tool("t", "r")]);
616        assert!(matches!(build_body(&req), Err(LlmError::Config(_))));
617    }
618
619    #[test]
620    fn final_turn_keeps_tools_with_choice_none() {
621        let req = ChatRequest::new("m", vec![Message::user("x")])
622            .with_tools(vec![ToolSpec { name: "t".into(), description: "d".into(), parameters: json!({}) }])
623            .with_tool_choice(ToolChoice::None);
624        let body = build_body(&req).unwrap();
625        assert_eq!(body["tool_choice"]["type"], "none");
626        assert_eq!(body["tools"][0]["name"], "t");
627    }
628
629    #[test]
630    fn error_event() {
631        let mut d = AnthropicDecoder::default();
632        let ev = SseEvent {
633            data: "{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"busy\"}}".into(),
634            ..SseEvent::default()
635        };
636        let err = d.decode(ev).unwrap_err();
637        assert!(err.is_retryable());
638    }
639}