1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
// src/language_models/providers/anthropic/chat.rs
//! AnthropicChat client struct and core implementation.
use futures_util::Stream;
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde_json::json;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use lc_core::language_models::{LLMResult, TokenUsage};
use lc_core::tools::{StructuredOutput, ToolCall, ToolDefinition};
use lc_schema::Message;
use super::config::{AnthropicConfig, ThinkingConfig};
use super::error::AnthropicError;
use super::types::{
AnthropicContentBlock, AnthropicImageSource, AnthropicMessage, AnthropicMessageContent,
AnthropicResponse, AnthropicStreamEvent, AnthropicStreamToken,
};
use crate::openai::sse::SseByteFramer;
use crate::ProviderError;
/// Anthropic Claude chat client.
#[derive(Clone)]
pub struct AnthropicChat {
pub(crate) config: AnthropicConfig,
pub(crate) client: reqwest::Client,
}
impl AnthropicChat {
/// Creates a new Anthropic chat client with the given configuration.
pub fn new(config: AnthropicConfig) -> Self {
Self {
config,
// 0.22.0 audit fix (H-P1): shared client with a connect timeout.
client: crate::retry::default_client(),
}
}
/// Creates an AnthropicChat from environment variables, returning a Result.
pub fn from_env_result() -> Result<Self, ProviderError> {
Ok(Self::new(AnthropicConfig::from_env_result()?))
}
/// Enables extended thinking with the given token budget.
pub fn with_thinking(mut self, budget_tokens: usize) -> Self {
self.config.thinking = ThinkingConfig::enabled(budget_tokens);
self
}
/// Returns a reference to the thinking configuration.
pub fn thinking_config(&self) -> &ThinkingConfig {
&self.config.thinking
}
/// Binds tool definitions for Anthropic function calling.
///
/// Anthropic uses the `tools` field in the request body with a format
/// that differs from OpenAI: each tool has `name`, `description`, and
/// `input_schema` (instead of `parameters`).
pub fn bind_tools(&self, tools: Vec<ToolDefinition>) -> Self {
let config = AnthropicConfig {
tools: Some(tools),
..self.config.clone()
};
Self {
config,
client: self.client.clone(),
}
}
/// Sets the tool choice strategy.
///
/// Accepts "auto" (model decides), "any" (must call a tool), or a
/// specific tool name to force that tool.
pub fn with_tool_choice(mut self, choice: impl Into<String>) -> Self {
self.config.tool_choice = Some(choice.into());
self
}
/// Enables structured JSON output with schema validation.
///
/// Uses Anthropic's tool calling under the hood: a single tool named
/// "structured_output" is bound, and the model is forced to call it.
pub fn with_structured_output<T: DeserializeOwned + JsonSchema>(
&self,
) -> AnthropicStructuredOutputMethod<T> {
use schemars::schema_for;
let schema = serde_json::to_value(schema_for!(T))
.unwrap_or_else(|_| serde_json::json!({"type": "object", "properties": {}}));
let tool = ToolDefinition::new("structured_output", "Return structured JSON output")
.with_parameters(schema);
let config = AnthropicConfig {
tools: Some(vec![tool]),
tool_choice: Some("auto".to_string()),
..self.config.clone()
};
AnthropicStructuredOutputMethod {
config,
client: self.client.clone(),
_phantom: PhantomData,
}
}
pub(crate) fn message_to_anthropic_format(message: &Message) -> AnthropicMessage {
match &message.message_type {
lc_schema::MessageType::Human => {
// If the message has images, build a content blocks array
if message.has_images() {
let mut content_parts: Vec<AnthropicContentBlock> = vec![];
// Add text content first
if !message.content.is_empty() {
content_parts.push(AnthropicContentBlock::Text {
text: message.content.clone(),
});
}
// Add image blocks — Anthropic requires base64-encoded images
for img in &message.images {
if let Some(source) = Self::image_to_anthropic_source(img) {
content_parts.push(AnthropicContentBlock::Image { source });
}
// URL-based images that aren't data URIs are silently skipped
// (Anthropic doesn't support URL-based image sources)
}
if content_parts.is_empty() {
content_parts.push(AnthropicContentBlock::Text {
text: message.content.clone(),
});
}
AnthropicMessage {
role: "user".to_string(),
content: AnthropicMessageContent::Blocks(content_parts),
}
} else {
AnthropicMessage {
role: "user".to_string(),
content: AnthropicMessageContent::Text(message.content.clone()),
}
}
}
lc_schema::MessageType::AI => {
let mut content_parts: Vec<AnthropicContentBlock> = vec![];
if let Some(tool_calls) = &message.tool_calls {
for tc in tool_calls {
content_parts.push(AnthropicContentBlock::ToolUse {
id: tc.id.clone(),
name: tc.function.name.clone(),
input: serde_json::from_str(&tc.function.arguments)
.unwrap_or(json!({})),
});
}
}
if !message.content.is_empty() {
content_parts.push(AnthropicContentBlock::Text {
text: message.content.clone(),
});
}
if content_parts.is_empty() {
content_parts.push(AnthropicContentBlock::Text {
text: String::new(),
});
}
AnthropicMessage {
role: "assistant".to_string(),
content: AnthropicMessageContent::Blocks(content_parts),
}
}
lc_schema::MessageType::Tool { tool_call_id } => AnthropicMessage {
role: "user".to_string(),
content: AnthropicMessageContent::Blocks(vec![AnthropicContentBlock::ToolResult {
tool_use_id: tool_call_id.clone(),
content: message.content.clone(),
}]),
},
// System messages are handled separately in build_request_body
lc_schema::MessageType::System => AnthropicMessage {
role: "user".to_string(),
content: AnthropicMessageContent::Text(message.content.clone()),
},
}
}
/// Converts an ImageContent to an AnthropicImageSource.
///
/// Anthropic only supports base64-encoded images. If the ImageContent
/// is a URL (not a data URI), returns None (the image is skipped).
fn image_to_anthropic_source(img: &lc_schema::ImageContent) -> Option<AnthropicImageSource> {
if img.is_base64() {
// Parse data URI: "data:image/png;base64,abc123"
let url = &img.url;
// Extract media type from "data:{media_type};base64,{data}"
let media_type = url.strip_prefix("data:")?.split(';').next()?.to_string();
let data = img.base64_data()?;
Some(AnthropicImageSource {
source_type: "base64".to_string(),
media_type,
data: data.to_string(),
})
} else {
// Anthropic doesn't support URL-based image sources
// The image is silently skipped
None
}
}
pub(crate) fn build_request_body(
&self,
messages: Vec<Message>,
stream: bool,
) -> serde_json::Value {
// H42: Extract system messages into top-level system field
let mut system_text = String::new();
let mut non_system_messages: Vec<Message> = Vec::new();
for msg in messages {
if msg.message_type == lc_schema::MessageType::System {
if !system_text.is_empty() {
system_text.push('\n');
}
system_text.push_str(&msg.content);
} else {
non_system_messages.push(msg);
}
}
// Also include config system_prompt if set
if let Some(ref prompt) = self.config.system_prompt {
if !system_text.is_empty() {
system_text.push('\n');
}
system_text.push_str(prompt);
}
let anthropic_messages: Vec<AnthropicMessage> = non_system_messages
.iter()
.map(Self::message_to_anthropic_format)
.collect();
let mut body = json!({
"model": self.config.model,
"max_tokens": self.config.max_tokens,
"messages": anthropic_messages,
"stream": stream,
});
if !system_text.is_empty() {
body["system"] = json!(system_text);
}
if let Some(temp) = self.config.temperature {
body["temperature"] = json!(temp);
}
// M17: Validate thinking config - max_tokens must be > budget_tokens
if self.config.thinking.is_enabled() {
if self.config.max_tokens <= self.config.thinking.budget_tokens {
body["max_tokens"] = json!(self.config.thinking.budget_tokens + 1024);
}
body["thinking"] = json!({
"type": "enabled",
"budget_tokens": self.config.thinking.budget_tokens,
});
}
// H7: Inject tools if configured (Anthropic function calling)
if let Some(ref tools) = self.config.tools {
let anthropic_tools: Vec<serde_json::Value> = tools
.iter()
.map(|td| {
let mut tool_json = json!({
"name": td.function.name,
});
if let Some(ref desc) = td.function.description {
tool_json["description"] = json!(desc);
}
if let Some(ref params) = td.function.parameters {
tool_json["input_schema"] = json!(params);
}
tool_json
})
.collect();
body["tools"] = json!(anthropic_tools);
}
// H7: Inject tool_choice if configured
if let Some(ref choice) = self.config.tool_choice {
if choice == "auto" || choice == "any" {
body["tool_choice"] = json!({"type": choice});
} else {
// Specific tool name
body["tool_choice"] = json!({"type": "tool", "name": choice});
}
}
body
}
pub(crate) async fn chat_internal(
&self,
messages: Vec<Message>,
) -> Result<LLMResult, AnthropicError> {
let url = format!("{}/messages", self.config.base_url);
let body = self.build_request_body(messages, false);
// 0.22.0 audit fix (H-P2): retry transient failures (429/5xx/network).
let response = crate::retry::send_with_retry(
|| {
self.client
.post(&url)
.header("x-api-key", &self.config.api_key)
.header("anthropic-version", "2023-06-01")
.header("Content-Type", "application/json")
.json(&body)
},
&crate::retry::DEFAULT_RETRY,
)
.await
.map_err(|e| AnthropicError::Http(e.to_string()))?;
let status = response.status();
if !status.is_success() {
let error_text = response.text().await.unwrap_or_default();
return Err(AnthropicError::Api(format!(
"HTTP {}: {}",
status, error_text
)));
}
let anthropic_response: AnthropicResponse = response
.json()
.await
.map_err(|e| AnthropicError::Parse(e.to_string()))?;
let mut thinking_content = String::new();
let mut text_content = String::new();
let mut tool_calls: Vec<lc_core::tools::ToolCall> = Vec::new();
for block in &anthropic_response.content {
match block.content_type.as_str() {
"thinking" => {
thinking_content.push_str(&block.thinking);
}
"text" => {
text_content.push_str(&block.text);
}
// H7: Parse tool_use content blocks into ToolCall
"tool_use" => {
let id = block.id.clone().unwrap_or_default();
let name = block.name.clone().unwrap_or_default();
let input = block.input.clone().unwrap_or(json!({}));
tool_calls.push(
lc_core::tools::ToolCall::builder(id)
.name(name)
.arguments(input.to_string())
.build(),
);
}
_ => {
if !block.text.is_empty() {
text_content.push_str(&block.text);
}
}
}
}
// H1 fix: remove redundant second pass and dangerous fallback.
// If only thinking blocks exist (no text), content should be empty,
// not leaked thinking text.
// The first loop above already collected all "text" blocks.
Ok(LLMResult {
content: text_content,
model: anthropic_response.model,
token_usage: anthropic_response.usage.map(|u| TokenUsage {
prompt_tokens: u.input_tokens,
completion_tokens: u.output_tokens,
total_tokens: u.input_tokens + u.output_tokens,
}),
tool_calls: if tool_calls.is_empty() {
None
} else {
Some(tool_calls)
},
thinking_content: if thinking_content.is_empty() {
None
} else {
Some(thinking_content)
},
})
}
pub(crate) async fn stream_chat_internal(
&self,
messages: Vec<Message>,
) -> Result<
Pin<Box<dyn Stream<Item = Result<AnthropicStreamToken, AnthropicError>> + Send>>,
AnthropicError,
> {
let url = format!("{}/messages", self.config.base_url);
let body = self.build_request_body(messages, true);
let response = self
.client
.post(&url)
.header("x-api-key", &self.config.api_key)
.header("anthropic-version", "2023-06-01")
.header("Content-Type", "application/json")
.json(&body)
.send()
.await
.map_err(|e| AnthropicError::Http(e.to_string()))?;
let status = response.status();
if !status.is_success() {
let error_text = response.text().await.unwrap_or_default();
return Err(AnthropicError::Api(format!(
"HTTP {}: {}",
status, error_text
)));
}
let byte_stream = response.bytes_stream();
// 0.22.0 C1: byte-level framer — complete events are decoded to UTF-8,
// so CJK characters split across TCP chunks are never lossy-torn.
let sse_buffer = Arc::new(Mutex::new(SseByteFramer::new()));
let (tx, rx) =
tokio::sync::mpsc::channel::<Result<AnthropicStreamToken, AnthropicError>>(64);
let buffer_clone = sse_buffer.clone();
tokio::spawn(async move {
use futures_util::StreamExt;
use std::collections::HashMap;
let mut byte_stream = byte_stream;
// 0.22.0 C2: accumulate streaming tool calls. `content_block_start`
// (type=tool_use) opens a slot with id+name; `input_json_delta`
// fragments append `partial_json`; `content_block_stop` flushes a
// complete ToolCall. Previously only text/thinking deltas were
// handled and tool calls fell into `_ => {}` silently.
let mut tool_blocks: HashMap<usize, (String, String, String)> = HashMap::new();
while let Some(chunk_result) = byte_stream.next().await {
if let Ok(bytes) = chunk_result {
// Extract complete SSE events from the byte-level framer
let events = {
let mut buffer_guard =
buffer_clone.lock().unwrap_or_else(|e| e.into_inner());
buffer_guard.push(&bytes)
};
// buffer_guard is dropped here, before any await
for event_text in events {
for line in event_text.lines() {
// Tolerate both "data: {...}" and "data:{...}"
// (0.22.0 audit fix, Medium).
if let Some(rest) = line.strip_prefix("data:") {
let data = rest.trim();
if data == "[DONE]" {
continue;
}
if let Ok(event) =
serde_json::from_str::<AnthropicStreamEvent>(data)
{
if event.type_field == "error" {
// 0.22.0 (audit Medium): overloaded_error and
// friends must not end the stream looking like
// a complete answer.
let _ = tx
.send(Err(AnthropicError::Api(format!(
"anthropic stream error event: {data}"
))))
.await;
return;
}
if event.type_field == "message_delta" {
// message_delta at the end of the stream carries usage; emit it as
// a standalone token so the streaming path also gets the full call usage.
if let Some(usage) = event.usage {
if tx
.send(Ok(AnthropicStreamToken::Usage(usage)))
.await
.is_err()
{
return;
}
}
continue;
}
if event.type_field == "content_block_start" {
if let Some(block) = &event.content_block {
if block.type_field == "tool_use" {
let index = event.index.unwrap_or_default();
tool_blocks.insert(
index,
(block.id.clone(), block.name.clone(), String::new()),
);
}
}
continue;
}
if event.type_field == "content_block_delta" {
if let Some(delta) = event.delta {
match delta.type_field.as_str() {
"text_delta" => {
if !delta.text.is_empty()
&& tx
.send(Ok(AnthropicStreamToken::Text(
delta.text,
)))
.await
.is_err()
{
return;
}
}
"thinking_delta" => {
if !delta.thinking.is_empty()
&& tx
.send(Ok(
AnthropicStreamToken::Thinking(
delta.thinking,
),
))
.await
.is_err()
{
return;
}
}
"input_json_delta" => {
// C2: fold argument fragments into the slot
// opened by content_block_start.
let index = event.index.unwrap_or_default();
if let Some((_, _, partial)) =
tool_blocks.get_mut(&index)
{
partial.push_str(&delta.partial_json);
}
}
_ => {}
}
}
continue;
}
if event.type_field == "content_block_stop" {
// C2: flush the completed tool call
if let Some((id, name, partial)) =
event.index.and_then(|i| tool_blocks.remove(&i))
{
if !name.is_empty() {
let call = ToolCall::builder(&id)
.name(&name)
.arguments(&partial)
.build();
if tx
.send(Ok(AnthropicStreamToken::ToolCall(call)))
.await
.is_err()
{
return;
}
}
}
continue;
}
} else {
// 0.20.0 P3: a malformed SSE datum no longer vanishes
// silently — log it and skip this token (matching the
// OpenAI streaming path). One bad datum does not kill the
// stream, but a stream truncated by failures is not left
// unexplained.
log::error!(
"Failed to parse Anthropic streaming SSE event (skipping this token): {}",
data
);
}
}
}
}
} else if let Err(e) = chunk_result {
// 0.20.0 P3: a transport error mid-stream no longer ends the stream
// silently — surface it so the caller does not mistake a truncated
// reply for a complete one.
let _ = tx.send(Err(AnthropicError::Http(e.to_string()))).await;
return;
}
}
});
let stream = tokio_stream::wrappers::ReceiverStream::new(rx);
Ok(Box::pin(stream))
}
}
/// Method for structured output calls via Anthropic tool calling.
pub struct AnthropicStructuredOutputMethod<T: DeserializeOwned + JsonSchema> {
config: AnthropicConfig,
client: reqwest::Client,
_phantom: PhantomData<T>,
}
impl<T: DeserializeOwned + JsonSchema> AnthropicStructuredOutputMethod<T> {
/// Invokes the model and parses the result as the structured type.
pub async fn invoke(&self, messages: Vec<Message>) -> Result<T, AnthropicError> {
let chat = AnthropicChat {
config: self.config.clone(),
client: self.client.clone(),
};
let result = chat.chat_internal(messages).await?;
let structured = StructuredOutput::<T>::new(result);
structured
.parse()
.map_err(|e| AnthropicError::Parse(e.to_string()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use lc_core::tools::ToolDefinition;
use serde_json::json;
#[test]
fn test_bind_tools_creates_new_chat_with_tools() {
let config = AnthropicConfig::new("test-key");
let chat = AnthropicChat::new(config);
let tools = vec![
ToolDefinition::new("calculator", "Do math").with_parameters(
json!({"type": "object", "properties": {"expr": {"type": "string"}}}),
),
];
let bound = chat.bind_tools(tools.clone());
assert!(bound.config.tools.is_some());
assert_eq!(bound.config.tools.as_ref().unwrap().len(), 1);
assert_eq!(
bound.config.tools.as_ref().unwrap()[0].function.name,
"calculator"
);
// Original chat should not have tools
assert!(chat.config.tools.is_none());
}
#[test]
fn test_with_tool_choice_sets_config() {
let config = AnthropicConfig::new("test-key");
let chat = AnthropicChat::new(config);
let chat = chat.with_tool_choice("auto");
assert_eq!(chat.config.tool_choice.as_deref(), Some("auto"));
}
#[test]
fn test_build_request_body_includes_tools() {
let config = AnthropicConfig::new("test-key");
let tools = vec![
ToolDefinition::new("get_weather", "Get weather").with_parameters(
json!({"type": "object", "properties": {"city": {"type": "string"}}}),
),
];
let chat = AnthropicChat::new(config).bind_tools(tools);
let body = chat.build_request_body(vec![], false);
let tools_arr = body.get("tools").unwrap().as_array().unwrap();
assert_eq!(tools_arr.len(), 1);
assert_eq!(tools_arr[0]["name"], "get_weather");
assert!(tools_arr[0].get("input_schema").is_some());
}
#[test]
fn test_build_request_body_tool_choice_auto() {
let config = AnthropicConfig::new("test-key");
let chat = AnthropicChat::new(config).with_tool_choice("auto");
let body = chat.build_request_body(vec![], false);
assert_eq!(body["tool_choice"]["type"], "auto");
}
#[test]
fn test_build_request_body_tool_choice_specific() {
let config = AnthropicConfig::new("test-key");
let chat = AnthropicChat::new(config).with_tool_choice("calculator");
let body = chat.build_request_body(vec![], false);
assert_eq!(body["tool_choice"]["type"], "tool");
assert_eq!(body["tool_choice"]["name"], "calculator");
}
#[test]
fn test_with_structured_output_binds_tool() {
let config = AnthropicConfig::new("test-key");
let chat = AnthropicChat::new(config);
#[derive(serde::Deserialize, schemars::JsonSchema)]
#[allow(dead_code)]
struct TestOutput {
answer: String,
}
let _method: AnthropicStructuredOutputMethod<TestOutput> = chat.with_structured_output();
// Just verify it compiles and the method is callable
}
// --- Image handling tests ---
#[test]
fn test_human_message_without_images_uses_text_content() {
let msg = Message::human("Hello");
let anthropic_msg = AnthropicChat::message_to_anthropic_format(&msg);
assert_eq!(anthropic_msg.role, "user");
// Without images, should use simple Text variant
assert!(matches!(
anthropic_msg.content,
AnthropicMessageContent::Text(_)
));
}
#[test]
fn test_human_message_with_base64_image_uses_blocks() {
let msg = Message::human_with_image("Describe this", "data:image/png;base64,abc123");
let anthropic_msg = AnthropicChat::message_to_anthropic_format(&msg);
assert_eq!(anthropic_msg.role, "user");
// With images, should use Blocks variant
assert!(matches!(
anthropic_msg.content,
AnthropicMessageContent::Blocks(_)
));
if let AnthropicMessageContent::Blocks(blocks) = &anthropic_msg.content {
// Should have: text block + image block
assert_eq!(blocks.len(), 2);
// First block should be text
assert!(
matches!(&blocks[0], AnthropicContentBlock::Text { text } if text == "Describe this")
);
// Second block should be image
if let AnthropicContentBlock::Image { source } = &blocks[1] {
assert_eq!(source.source_type, "base64");
assert_eq!(source.media_type, "image/png");
assert_eq!(source.data, "abc123");
} else {
panic!("Expected Image block");
}
}
}
#[test]
fn test_human_message_with_url_image_skips_image() {
// Anthropic doesn't support URL-based images, so they are silently skipped
let msg = Message::human_with_image("Describe this", "https://example.com/img.png");
let anthropic_msg = AnthropicChat::message_to_anthropic_format(&msg);
assert_eq!(anthropic_msg.role, "user");
// URL image is skipped, but since has_images() is true, we still use Blocks
if let AnthropicMessageContent::Blocks(blocks) = &anthropic_msg.content {
// Only text block remains (URL image was skipped)
assert_eq!(blocks.len(), 1);
assert!(matches!(&blocks[0], AnthropicContentBlock::Text { .. }));
} else {
panic!("Expected Blocks variant for message with images");
}
}
#[test]
fn test_human_message_with_jpeg_base64_image() {
let msg =
Message::human_with_image("What is this?", "data:image/jpeg;base64,/9j/4AAQSkZJRg==");
let anthropic_msg = AnthropicChat::message_to_anthropic_format(&msg);
if let AnthropicMessageContent::Blocks(blocks) = &anthropic_msg.content {
if let AnthropicContentBlock::Image { source } = &blocks[1] {
assert_eq!(source.media_type, "image/jpeg");
assert_eq!(source.data, "/9j/4AAQSkZJRg==");
}
}
}
#[test]
fn test_image_to_anthropic_source_base64() {
let img = lc_schema::ImageContent::from_base64_with_mime("testdata", "image/webp");
let source = AnthropicChat::image_to_anthropic_source(&img);
assert!(source.is_some());
let s = source.unwrap();
assert_eq!(s.source_type, "base64");
assert_eq!(s.media_type, "image/webp");
assert_eq!(s.data, "testdata");
}
#[test]
fn test_image_to_anthropic_source_url_returns_none() {
let img = lc_schema::ImageContent::from_url("https://example.com/img.png");
let source = AnthropicChat::image_to_anthropic_source(&img);
assert!(source.is_none());
}
#[test]
fn test_build_request_body_with_image_message() {
let config = AnthropicConfig::new("test-key");
let chat = AnthropicChat::new(config);
let msg = Message::human_with_image("Describe", "data:image/png;base64,abc");
let body = chat.build_request_body(vec![msg], false);
// Messages should be an array with one element
let messages = body.get("messages").unwrap().as_array().unwrap();
assert_eq!(messages.len(), 1);
// The message content should be an array of blocks
let content = &messages[0]["content"];
assert!(content.is_array());
let blocks = content.as_array().unwrap();
assert_eq!(blocks.len(), 2); // text + image
assert_eq!(blocks[0]["type"], "text");
assert_eq!(blocks[1]["type"], "image");
assert_eq!(blocks[1]["source"]["type"], "base64");
assert_eq!(blocks[1]["source"]["media_type"], "image/png");
}
}