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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
// 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 => {
// B7: unified multimodal mapping over every attached medium.
// Images become base64 `image` blocks; PDF files become base64
// `document` blocks. The Messages API accepts neither audio/video
// nor hosted URLs — the async entry points run
// `media::resolve_message_media` (Anthropic policy) first, which
// rejects audio/video and non-PDF files and SSRF-safely inlines
// http(s) URLs before this pure mapper runs.
if message.is_multimodal() {
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(),
});
}
for part in message.media_parts() {
match part {
lc_schema::MediaPart::Image(img) => {
// URL-based images that aren't data URIs are skipped
// (Anthropic doesn't support URL-based image sources;
// the resolver fetches them into data URIs upstream).
if let Some(source) = Self::image_to_anthropic_source(img) {
content_parts.push(AnthropicContentBlock::Image { source });
}
}
lc_schema::MediaPart::File(file) => {
if let Some((source, filename)) =
Self::file_to_anthropic_document(file)
{
content_parts
.push(AnthropicContentBlock::Document { source, filename });
}
}
// Audio/video never reach here over the network path:
// the Anthropic media policy rejects them explicitly.
lc_schema::MediaPart::Audio(_) | lc_schema::MediaPart::Video(_) => {}
}
}
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
}
}
/// Converts a FileContent into an Anthropic `document` block source.
///
/// The Messages API only supports inline base64 PDF documents. Hosted
/// files and non-PDF types return `None` here; `media::resolve_message_media`
/// enforces both constraints (explicit error, never a silent drop) and
/// rewrites http(s) URLs into data URIs before request building.
fn file_to_anthropic_document(
file: &lc_schema::FileContent,
) -> Option<(AnthropicImageSource, Option<String>)> {
if !file.is_base64() {
return None;
}
let mime = file.mime_type.clone().or_else(|| {
file.url
.strip_prefix("data:")?
.split(';')
.next()
.map(str::to_string)
})?;
if mime != "application/pdf" {
return None;
}
let data = file.base64_data()?;
Some((
AnthropicImageSource {
source_type: "base64".to_string(),
media_type: mime,
data: data.to_string(),
},
file.name.clone(),
))
}
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() {
// B1 transparent passthrough: with prompt caching enabled, the system prompt
// becomes a content-block array whose (only) block carries an explicit
// `cache_control: {"type":"ephemeral"}` breakpoint. Anthropic only honors
// cache_control on content-block arrays, so the plain-string form is used
// when caching is off to keep the request byte-identical to before.
if self.config.prompt_caching {
body["system"] = json!([{
"type": "text",
"text": system_text,
"cache_control": {"type": "ephemeral"},
}]);
} else {
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 mut 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();
// B1: cache the last tool definition too (the most stable, largest prefix).
// Anthropic allows `cache_control` on tool entries for prompt caching.
if self.config.prompt_caching {
if let Some(last) = anthropic_tools.last_mut() {
last["cache_control"] = json!({"type": "ephemeral"});
}
}
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);
// B7: fetch inline-only media through the SSRF guard and reject
// modalities the Messages API does not support (audio/video, non-PDF).
let mut messages = messages;
crate::media::resolve_message_media(&mut messages, crate::media::MediaPolicy::Anthropic)
.await
.map_err(|e| AnthropicError::Api(e.to_string()))?;
let body = self.build_request_body(messages, false);
// 0.22.0 audit fix (H-P2): retry transient failures (429/5xx/network).
// A14: non-idempotent POST — DEFAULT_RETRY may replay a post-dispatch
// timeout/5xx and double-bill; use retry::SAFE_RETRY to retry only
// provably pre-dispatch transport failures.
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.
if let Some(ref usage) = anthropic_response.usage {
// B1 statistic: surface the prompt-cache breakdown on the non-streaming path.
log::info!(
target: "lc_providers::anthropic::cache",
"input={} cache_read={} cache_created={} miss={}",
usage.input_tokens,
usage.cache_read_tokens(),
usage.cache_creation_tokens(),
usage.cache_miss_tokens()
);
}
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);
// B7: same media resolution as the non-streaming path.
let mut messages = messages;
crate::media::resolve_message_media(&mut messages, crate::media::MediaPolicy::Anthropic)
.await
.map_err(|e| AnthropicError::Api(e.to_string()))?;
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();
// A12: Anthropic ends every successful stream with a terminal
// `message_stop` event. If the connection closes first (proxy reset,
// server error, timeout), the text streamed so far is a truncated prefix;
// track the marker and error after the loop instead of completing silently.
let mut saw_message_stop = false;
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_stop" {
// A12: the canonical terminal event for an
// Anthropic SSE stream.
saw_message_stop = true;
continue;
}
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 {
// B1 statistic: cache breakdown on the streaming path
// (also exposed on `AnthropicUsage` itself).
log::info!(
target: "lc_providers::anthropic::cache",
"input={} cache_read={} cache_created={} miss={}",
usage.input_tokens,
usage.cache_read_tokens(),
usage.cache_creation_tokens(),
usage.cache_miss_tokens()
);
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;
}
}
// A12: the connection closed without a terminal `message_stop` event —
// whatever text streamed so far is truncated, not a complete answer.
if !saw_message_stop {
let _ = tx
.send(Err(AnthropicError::StreamInterrupted(
"connection closed before message_stop".to_string(),
)))
.await;
}
});
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 crate::providers::anthropic::types::AnthropicUsage;
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());
}
// --- B1 prompt caching ---
#[test]
fn prompt_caching_off_keeps_plain_system_string() {
let config = AnthropicConfig::new("test-key");
let chat = AnthropicChat::new(config);
let msg = Message::system("be concise");
let body = chat.build_request_body(vec![msg], false);
assert_eq!(
body["system"], "be concise",
"caching off: keep byte-identical string"
);
}
#[test]
fn prompt_caching_on_emits_cache_control_block() {
let config = AnthropicConfig::new("test-key").with_prompt_caching(true);
let chat = AnthropicChat::new(config);
let msg = Message::system("be concise");
let body = chat.build_request_body(vec![msg], false);
let system = body["system"]
.as_array()
.expect("caching on emits a block array");
assert_eq!(system.len(), 1);
assert_eq!(system[0]["type"], "text");
assert_eq!(system[0]["text"], "be concise");
assert_eq!(system[0]["cache_control"]["type"], "ephemeral");
}
#[test]
fn prompt_caching_on_caches_last_tool() {
let config = AnthropicConfig::new("test-key").with_prompt_caching(true);
let tools = vec![
ToolDefinition::new("a", "tool a")
.with_parameters(json!({"type":"object","properties":{"x":{"type":"string"}}})),
ToolDefinition::new("b", "tool b")
.with_parameters(json!({"type":"object","properties":{"y":{"type":"string"}}})),
];
let chat = AnthropicChat::new(config).bind_tools(tools);
let body = chat.build_request_body(vec![], false);
let arr = body["tools"].as_array().unwrap();
assert_eq!(arr.len(), 2);
assert!(
arr[0].get("cache_control").is_none(),
"only the last tool is cached"
);
assert_eq!(arr[1]["cache_control"]["type"], "ephemeral");
}
#[test]
fn usage_deserializes_cache_fields() {
let raw = r#"{"input_tokens": 100, "output_tokens": 40,
"cache_creation_input_tokens": 50, "cache_read_input_tokens": 60}"#;
let usage: AnthropicUsage = serde_json::from_str(raw).unwrap();
assert_eq!(usage.cache_creation_tokens(), 50);
assert_eq!(usage.cache_read_tokens(), 60);
assert_eq!(usage.cache_miss_tokens(), 40); // 100 - 60
assert_eq!(usage.cache_breakdown(), (50, 60));
}
#[test]
fn usage_parse_tolerates_missing_cache_fields() {
// older Anthropic payloads / proxies that omit cache fields still parse
let raw = r#"{"input_tokens": 7, "output_tokens": 3}"#;
let usage: AnthropicUsage = serde_json::from_str(raw).unwrap();
assert_eq!(usage.cache_read_tokens(), 0);
assert_eq!(usage.cache_creation_tokens(), 0);
}
#[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");
}
// --- B7 multimodal mapping ---
#[test]
fn b7_image_and_pdf_file_become_image_and_document_blocks() {
let config = AnthropicConfig::new("test-key");
let chat = AnthropicChat::new(config);
let msg = Message::human("读图和附件")
.with_image(lc_schema::ImageContent::from_base64_with_mime(
"aW1n",
"image/png",
))
.with_file(
lc_schema::FileContent::from_base64("ZG9j", "application/pdf")
.with_name("brief.pdf"),
);
let body = chat.build_request_body(vec![msg], false);
let messages = body["messages"].as_array().unwrap();
let blocks = messages[0]["content"].as_array().unwrap();
let expected = serde_json::json!([
{"type": "text", "text": "读图和附件"},
{"type": "image", "source": {
"type": "base64",
"media_type": "image/png",
"data": "aW1n"
}},
{"type": "document", "source": {
"type": "base64",
"media_type": "application/pdf",
"data": "ZG9j"
}, "filename": "brief.pdf"},
]);
assert_eq!(serde_json::json!(blocks), expected);
}
#[test]
fn b7_pdf_without_explicit_mime_uses_data_uri_mime() {
// Fetch-rewritten files carry the MIME in the data URI only.
let file = lc_schema::FileContent {
url: "data:application/pdf;base64,ZmV0Y2g=".to_string(),
mime_type: None,
name: None,
};
let (source, filename) =
AnthropicChat::file_to_anthropic_document(&file).expect("data-URI PDF maps");
assert_eq!(source.media_type, "application/pdf");
assert_eq!(source.data, "ZmV0Y2g=");
assert!(filename.is_none());
}
#[test]
fn b7_non_pdf_document_is_skipped_by_sync_mapper() {
// The async entry points reject non-PDF files outright; the pure
// mapper simply does not emit a block for them.
let csv = lc_schema::FileContent::from_base64("YQ==", "text/csv");
assert!(AnthropicChat::file_to_anthropic_document(&csv).is_none());
}
#[test]
fn b7_hosted_pdf_url_is_skipped_by_sync_mapper() {
let pdf = lc_schema::FileContent::from_url("https://example.com/brief.pdf");
assert!(AnthropicChat::file_to_anthropic_document(&pdf).is_none());
}
}