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