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
//! An HTTP client to the Anthropic Messages API (`platform.claude.com`), implementing
//! [`EngineBackend`]. A protocol separate from OpenAI (`/v1/messages`, headers
//! `x-api-key` + `anthropic-version`, event-based SSE). See ADR 0004, Phase 2.
//!
//! Anthropic has no embeddings — [`Embedder`](super::super::contract::Embedder) isn't
//! implemented here (RAG uses a separate embedder, ADR 0002).
use std::sync::atomic::{AtomicBool, Ordering};
use anyhow::Result;
use async_stream::stream;
use eventsource_stream::Eventsource;
use futures_util::StreamExt;
use tokio_util::sync::CancellationToken;
use super::wire::{self, AntDelta, AntStartBlock, AntStreamEvent, AntUsage};
use crate::shared::api::contract::{
ChatChunk, ChatRequest, ChatStream, EngineBackend, FinishReason, ThinkingRef, ToolCallDelta,
VisionSupport,
};
use crate::shared::api::effort::{self, EffortMemo, EffortWire};
use crate::shared::api::error::{self, EngineError, SUBJECT_ANTHROPIC};
use crate::shared::api::http;
/// The Anthropic API version (the mandatory `anthropic-version` header). Shared
/// with the model catalogue ([`super::super::catalogue`]), which sends the same
/// header — one spelling for the whole provider.
pub(crate) const ANTHROPIC_VERSION: &str = "2023-06-01";
/// A client to the Anthropic Messages API.
pub struct AnthropicClient {
http: reqwest::Client,
/// The base URL with no suffix (the client appends `/v1/messages`), e.g.
/// `https://api.anthropic.com`.
base_url: String,
api_key: String,
model: String,
/// The effort levels this model has refused, and what it took in each
/// one's place. The API's vocabulary has `xhigh` and `max`; which of them a
/// model has is its own — the 4.6 generation has no `xhigh` — and its
/// refusal says so. (The Models API publishes it too; why the refusal is
/// read instead is on [`Self::open`].)
efforts: EffortMemo,
/// This model has refused adaptive thinking and taken a thinking budget —
/// the 4.5 generation. From then on a thinking turn goes out in that shape
/// at once. Set only once the budgeted request was accepted.
budget_thinking: AtomicBool,
}
impl AnthropicClient {
pub fn new(
base_url: impl Into<String>,
api_key: impl Into<String>,
model: impl Into<String>,
) -> Self {
let base_url = base_url.into().trim_end_matches('/').to_string();
Self {
http: http::engine_client(),
base_url,
api_key: api_key.into(),
model: model.into(),
efforts: EffortMemo::default(),
budget_thinking: AtomicBool::new(false),
}
}
/// Whether this model has been found to think within a budget rather than
/// adaptively — unset while it has not refused the adaptive shape. For the
/// tests and smokes, which must tell a turn that survived the refusal from
/// one that never met it.
#[cfg(test)]
pub(super) fn thinks_within_a_budget(&self) -> bool {
self.budget_thinking.load(Ordering::Relaxed)
}
/// Sends the request, and answers the two refusals a thinking turn can meet
/// that are about the request's **shape** rather than its content.
///
/// - An **effort level** the model does not have (`xhigh` on the 4.6
/// generation) — [`effort::send_asking_again`], the nearest listed.
/// - **Adaptive thinking** on a model that has no such mode — the 4.5
/// generation, `claude-haiku-4-5` among it. The thinking switch is on by
/// default, so on such a model *every ordinary turn* was this `400`. The
/// request is made once more with a thinking budget
/// ([`wire::AntRequest::think_within_a_budget`]) and the shape is kept
/// for the client only once it was accepted.
///
/// Both facts are published — `GET /v1/models/{id}` lists
/// `capabilities.thinking.types` and `capabilities.effort` per model
/// (measured 2026-10-01). They are read off the refusal anyway: a refused
/// request is free and only a model that needs the other shape meets it,
/// once per client, while asking ahead would cost every session a request
/// and still need this path under it for the day that request fails.
async fn open(
&self,
req: &ChatRequest,
cancel: &CancellationToken,
) -> Result<Option<reqwest::Response>, EngineError> {
let mut body = wire::build_request(req, &self.model, true);
if self.budget_thinking.load(Ordering::Relaxed) {
body.think_within_a_budget();
}
let first = effort::send_asking_again(self, &mut body, cancel).await;
let Err(refused) = &first else {
return first;
};
if !(body.thinks_adaptively() && wire::refuses_adaptive_thinking(refused)) {
return first;
}
tracing::info!(
model = %self.model,
"the model does not take adaptive thinking; asking again with a thinking budget"
);
body.think_within_a_budget();
let second = effort::send_asking_again(self, &mut body, cancel).await;
if matches!(second, Ok(Some(_))) {
self.budget_thinking.store(true, Ordering::Relaxed);
}
second
}
/// What this model has been found to take in place of the effort `wish` —
/// unset while it has not refused it. For the tests and smokes, which must
/// tell a turn that survived a refusal from one that never met it.
#[cfg(test)]
pub(super) fn learned(&self, wish: &str) -> Option<Option<&'static str>> {
self.efforts.instead_of(wish)
}
}
impl EffortWire for AnthropicClient {
type Body = wire::AntRequest;
fn model(&self) -> &str {
&self.model
}
fn efforts(&self) -> &EffortMemo {
&self.efforts
}
async fn send(
&self,
body: &wire::AntRequest,
cancel: &CancellationToken,
) -> Result<Option<reqwest::Response>, EngineError> {
let url = format!("{}/v1/messages", self.base_url);
let request = self
.http
.post(&url)
.header("x-api-key", &self.api_key)
.header("anthropic-version", ANTHROPIC_VERSION)
.json(body);
let Some(response) = http::send_cancellable(request, cancel).await? else {
return Ok(None);
};
error::check_status(SUBJECT_ANTHROPIC, response)
.await
.map(Some)
}
/// The nearest level the refusal itself lists; with nothing listed the
/// refusal is the answer.
fn answer(&self, wish: &'static str, refused: &EngineError) -> Option<Option<&'static str>> {
if !wire::refuses_effort(refused) {
return None;
}
effort::nearest(wish, &effort::listed(&refused.message)).map(Some)
}
}
/// Maps Anthropic's `stop_reason` to the domain [`FinishReason`].
fn map_stop_reason(s: &str) -> FinishReason {
match s {
"end_turn" | "stop_sequence" => FinishReason::Stop,
"max_tokens" => FinishReason::Length,
"tool_use" => FinishReason::ToolCalls,
// The streaming classifiers stopped the reply.
"refusal" => FinishReason::Filtered,
_ => FinishReason::Stop,
}
}
#[async_trait::async_trait]
impl EngineBackend for AnthropicClient {
async fn chat_stream(&self, req: ChatRequest, cancel: CancellationToken) -> Result<ChatStream> {
let Some(response) = self.open(&req, &cancel).await? else {
return Ok(http::cancelled_stream());
};
let mut events = response.bytes_stream().eventsource();
let s = stream! {
// The input side (with the cache fields) arrives in message_start,
// output_tokens — in message_delta.
let mut start = AntUsage::default();
loop {
tokio::select! {
biased;
_ = cancel.cancelled() => {
yield ChatChunk::Finished(FinishReason::Cancelled);
break;
}
next = events.next() => {
match next {
None => {
yield ChatChunk::Finished(FinishReason::Stop);
break;
}
Some(Err(err)) => {
let message = error::chain_text(&err);
tracing::warn!(error = %message, "SSE stream error (anthropic)");
for chunk in ChatChunk::failure(message, true) { yield chunk; }
break;
}
Some(Ok(event)) => {
match serde_json::from_str::<AntStreamEvent>(&event.data) {
Ok(AntStreamEvent::MessageStart { message }) => {
if let Some(u) = message.usage {
start = u;
}
}
Ok(AntStreamEvent::ContentBlockStart {
index,
content_block: AntStartBlock::ToolUse { id, name },
}) => {
yield ChatChunk::ToolCall(ToolCallDelta { thought_signature: None,
index,
id: Some(id),
name: Some(name),
arguments: String::new(),
});
}
Ok(AntStreamEvent::ContentBlockStart { .. }) => {}
Ok(AntStreamEvent::ContentBlockDelta { index, delta }) => match delta {
AntDelta::TextDelta { text } if !text.is_empty() => {
yield ChatChunk::Text(text);
}
AntDelta::ThinkingDelta { thinking } if !thinking.is_empty() => {
yield ChatChunk::Thoughts(thinking);
}
AntDelta::SignatureDelta { signature } if !signature.is_empty() => {
yield ChatChunk::ThoughtsSignature(ThinkingRef {
id: None,
signature,
});
}
AntDelta::InputJsonDelta { partial_json } => {
yield ChatChunk::ToolCall(ToolCallDelta { thought_signature: None,
index,
id: None,
name: None,
arguments: partial_json,
});
}
_ => {}
},
Ok(AntStreamEvent::MessageDelta { delta, usage }) => {
let completion = usage.map(|u| u.output_tokens).unwrap_or(0);
yield ChatChunk::Usage(start.token_usage(completion));
let reason = delta
.stop_reason
.as_deref()
.map(map_stop_reason)
.unwrap_or(FinishReason::Stop);
yield ChatChunk::Finished(reason);
break;
}
// The documented way a failure arrives once the
// stream is open: `overloaded_error` here is the
// `529` that would have been the status code a
// moment earlier.
Ok(AntStreamEvent::Error { error: e }) => {
let transient = error::stream_error_transient(&e.name, None);
tracing::warn!(
name = %e.name,
transient,
message = %e.message,
"anthropic reported an error inside the stream"
);
let message = error::stream_error_text(&e.name, &e.message);
for chunk in ChatChunk::failure(message, transient) { yield chunk; }
break;
}
Ok(AntStreamEvent::Other) => {}
Err(err) => {
tracing::warn!(error = %err, data = %event.data, "failed to parse anthropic SSE chunk");
}
}
}
}
}
}
}
};
Ok(Box::pin(s))
}
/// Claude takes images on every current model, so the answer is static.
///
/// Deliberately **not** a model-name allowlist: a hardcoded list of vision
/// models goes stale the week after it is written and then lies confidently —
/// the trap docs/research/grok-xai-provider.md recorded for reasoning detection.
/// A genuinely text-only model returns a clear provider error on send, which is
/// a far better failure than refusing an attach on a guess.
async fn vision(&self) -> VisionSupport {
VisionSupport::Supported
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::shared::api::sse_stub::{self, collect, serve as serve_sse};
/// The input side of the counter arrives in `message_start` and the output
/// in `message_delta`; the cache fields ride the first and must survive to
/// the second, summed into a whole prompt (docs/research/cached-tokens.md
/// §4.2–§4.3).
#[tokio::test]
async fn the_cache_fields_of_message_start_reach_the_usage() {
let base = serve_sse(&[
r#"{"type":"message_start","message":{"usage":{"input_tokens":13,"cache_creation_input_tokens":2304,"cache_read_input_tokens":5067,"output_tokens":1}}}"#,
r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pong"}}"#,
r#"{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}"#,
]);
let client = AnthropicClient::new(base, "k", "claude-x");
let req = ChatRequest {
messages: vec![crate::shared::api::contract::ApiMessage::user("hi")],
..Default::default()
};
let chunks = collect(client.chat_stream(req, Default::default()).await.unwrap()).await;
let usage = chunks
.iter()
.find_map(|c| match c {
ChatChunk::Usage(u) => Some(*u),
_ => None,
})
.expect("usage");
assert_eq!(usage.prompt_tokens, 13 + 2304 + 5067);
assert_eq!(usage.cached_tokens, Some(5067));
assert_eq!(usage.cache_write_tokens, Some(2304));
assert_eq!(usage.completion_tokens, 2);
}
/// The headline defect: Anthropic sheds load *after* accepting the stream, and
/// that event used to fall into `AntStreamEvent::Other` — so the connection then
/// closed, the `None` arm reported `Finished(Stop)`, and an overloaded
/// truncation was byte-for-byte a normal completion.
#[tokio::test]
async fn an_overloaded_error_mid_stream_ends_the_turn_as_an_error() {
let base = serve_sse(&[
r#"{"type":"message_start","message":{"usage":{"input_tokens":10}}}"#,
r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Half an ans"}}"#,
r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#,
]);
let client = AnthropicClient::new(base, "k", "claude-x");
let req = ChatRequest {
continue_final: false,
system: None,
messages: vec![crate::shared::api::contract::ApiMessage::user("hi")],
sampling: Default::default(),
tools: vec![],
};
let chunks = collect(client.chat_stream(req, Default::default()).await.unwrap()).await;
assert!(
chunks.contains(&ChatChunk::Text("Half an ans".into())),
"the partial text still arrives: {chunks:?}"
);
let Some(ChatChunk::Error { message, transient }) = chunks
.iter()
.find(|c| matches!(c, ChatChunk::Error { .. }))
.cloned()
else {
panic!("the error must reach the consumer, not just the log: {chunks:?}");
};
assert!(message.contains("overloaded_error"), "{message}");
assert!(transient, "an overloaded provider is worth another attempt");
assert_eq!(
chunks.last(),
Some(&ChatChunk::Finished(FinishReason::Error)),
"and the turn must not end as a plain Stop: {chunks:?}"
);
}
/// The other half of the same claim: a stream that ends normally must still end
/// as `Stop`, with no error chunk invented.
#[tokio::test]
async fn a_clean_stream_still_finishes_without_an_error_chunk() {
let base = serve_sse(&[
r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pong"}}"#,
r#"{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}"#,
]);
let client = AnthropicClient::new(base, "k", "claude-x");
let req = ChatRequest {
continue_final: false,
system: None,
messages: vec![crate::shared::api::contract::ApiMessage::user("hi")],
sampling: Default::default(),
tools: vec![],
};
let chunks = collect(client.chat_stream(req, Default::default()).await.unwrap()).await;
assert!(
!chunks.iter().any(|c| matches!(c, ChatChunk::Error { .. })),
"{chunks:?}"
);
assert_eq!(
chunks.last(),
Some(&ChatChunk::Finished(FinishReason::Stop))
);
}
/// The streaming classifiers stop a reply with `stop_reason: "refusal"`: what
/// arrived before it stays, and the turn ends as filtered rather than as a
/// complete answer (docs/research/content-filter-finish.md).
#[tokio::test]
async fn a_refusal_ends_the_turn_as_filtered() {
let base = serve_sse(&[
r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Here is how"}}"#,
r#"{"type":"message_delta","delta":{"stop_reason":"refusal"},"usage":{"output_tokens":3}}"#,
]);
let client = AnthropicClient::new(base, "k", "claude-x");
let chunks = collect(
client
.chat_stream(sse_stub::hello(), Default::default())
.await
.unwrap(),
)
.await;
assert!(
chunks.contains(&ChatChunk::Text("Here is how".into())),
"{chunks:?}"
);
assert_eq!(
chunks.last(),
Some(&ChatChunk::Finished(FinishReason::Filtered))
);
}
/// A whole reply: one word, and the reason it stopped.
const REPLY: sse_stub::Canned = (
"200 OK",
"text/event-stream",
"data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"pong\"}}\n\n\
data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":2}}\n\n",
);
/// A thinking turn at the settings' `xhigh`.
fn thinking_at_xhigh() -> ChatRequest {
let mut req = sse_stub::hello();
req.sampling.thinking = Some(true);
req.sampling.reasoning_effort = Some(crate::entities::sampling::ReasoningEffort::XHigh);
req
}
/// The 4.6 generation has `max` and no `xhigh`, and says so: the turn is
/// asked again at the nearest level the refusal lists — `high`, the lower of
/// the two it stands between — and the next turn asks for that at once.
#[tokio::test]
async fn a_refused_level_is_asked_again_as_the_nearest_listed() {
let (url, stub) = sse_stub::serve_in_turn(&[
(sse_stub::BAD_REQUEST, sse_stub::JSON, wire::EFFORT_REFUSED),
REPLY,
REPLY,
]);
let client = AnthropicClient::new(url, "k", "claude-sonnet-4-6");
for _ in 0..2 {
let chunks = collect(
client
.chat_stream(thinking_at_xhigh(), CancellationToken::new())
.await
.expect("the turn survives the refusal"),
)
.await;
assert!(
chunks.contains(&ChatChunk::Text("pong".into())),
"{chunks:?}"
);
}
let efforts: Vec<serde_json::Value> = stub
.join()
.unwrap()
.iter()
.map(|b| {
let body: serde_json::Value = serde_json::from_str(b).unwrap();
body["output_config"]["effort"].clone()
})
.collect();
assert_eq!(efforts, ["xhigh", "high", "high"]);
assert_eq!(client.learned("xhigh"), Some(Some("high")));
}
/// A `400` that is about neither the level nor the thinking shape is
/// reported as it came, after one request.
#[tokio::test]
async fn another_refusal_of_a_thinking_turn_is_reported_as_it_came() {
let (url, stub) = sse_stub::serve_in_turn(&[(
sse_stub::BAD_REQUEST,
sse_stub::JSON,
r#"{"type":"error","error":{"type":"invalid_request_error","message":"prompt is too long: 250000 tokens > 200000 maximum"}}"#,
)]);
let client = AnthropicClient::new(url, "k", "claude-haiku-4-5");
let err = client
.chat_stream(thinking_at_xhigh(), CancellationToken::new())
.await
.err()
.expect("the refusal is the answer");
assert!(err.to_string().contains("prompt is too long"), "{err}");
assert_eq!(stub.join().unwrap().len(), 1);
assert_eq!(client.learned("xhigh"), None);
assert!(!client.thinks_within_a_budget());
}
/// The `thinking` object and the `output_config` of each request the stub
/// was sent, in order.
fn shapes_sent(bodies: &[String]) -> Vec<(serde_json::Value, serde_json::Value)> {
bodies
.iter()
.map(|b| {
let body: serde_json::Value =
serde_json::from_str(b).unwrap_or_else(|e| panic!("{e}: {b:?}"));
(body["thinking"].clone(), body["output_config"].clone())
})
.collect()
}
/// The defect: the 4.5 generation has no adaptive thinking, the thinking
/// switch is on by default, and so every ordinary turn on `claude-haiku-4-5`
/// was a `400`. The turn completes on the second request, which thinks
/// within a budget and carries no effort — and the next turn goes out in
/// that shape at once.
#[tokio::test]
async fn refused_adaptive_thinking_is_asked_again_with_a_budget() {
let (url, stub) = sse_stub::serve_in_turn(&[
(
sse_stub::BAD_REQUEST,
sse_stub::JSON,
wire::ADAPTIVE_REFUSED,
),
REPLY,
REPLY,
]);
let client = AnthropicClient::new(url, "k", "claude-haiku-4-5");
for _ in 0..2 {
let mut req = thinking_at_xhigh();
req.sampling.max_tokens = Some(16384);
let chunks = collect(
client
.chat_stream(req, CancellationToken::new())
.await
.expect("the turn survives the refusal"),
)
.await;
assert!(
chunks.contains(&ChatChunk::Text("pong".into())),
"{chunks:?}"
);
}
let budget =
serde_json::json!({"type": "enabled", "budget_tokens": 8192, "display": "summarized"});
assert_eq!(
shapes_sent(&stub.join().unwrap()),
[
(
serde_json::json!({"type": "adaptive", "display": "summarized"}),
serde_json::json!({"effort": "xhigh"})
),
(budget.clone(), serde_json::Value::Null),
(budget, serde_json::Value::Null),
]
);
assert!(client.thinks_within_a_budget());
}
/// A budget refused too is the turn's error, and teaches the client
/// nothing: the next turn starts from the adaptive shape again.
#[tokio::test]
async fn a_budget_that_was_refused_too_is_not_remembered() {
let (url, stub) = sse_stub::serve_in_turn(&[
(
sse_stub::BAD_REQUEST,
sse_stub::JSON,
wire::ADAPTIVE_REFUSED,
),
(
sse_stub::BAD_REQUEST,
sse_stub::JSON,
r#"{"type":"error","error":{"type":"invalid_request_error","message":"thinking: Extra inputs are not permitted"}}"#,
),
REPLY,
]);
let client = AnthropicClient::new(url, "k", "claude-x");
let err = client
.chat_stream(thinking_at_xhigh(), CancellationToken::new())
.await
.err()
.expect("both shapes were refused");
assert!(err.to_string().contains("Extra inputs"), "{err}");
assert!(!client.thinks_within_a_budget());
collect(
client
.chat_stream(thinking_at_xhigh(), CancellationToken::new())
.await
.expect("the stub takes the third request"),
)
.await;
let kinds: Vec<_> = shapes_sent(&stub.join().unwrap())
.into_iter()
.map(|(thinking, _)| thinking["type"].clone())
.collect();
assert_eq!(kinds, ["adaptive", "enabled", "adaptive"]);
}
#[test]
fn stop_reason_mapping() {
assert_eq!(map_stop_reason("end_turn"), FinishReason::Stop);
assert_eq!(map_stop_reason("stop_sequence"), FinishReason::Stop);
assert_eq!(map_stop_reason("max_tokens"), FinishReason::Length);
assert_eq!(map_stop_reason("tool_use"), FinishReason::ToolCalls);
assert_eq!(map_stop_reason("refusal"), FinishReason::Filtered);
assert_eq!(map_stop_reason("weird"), FinishReason::Stop);
}
}
/// A manual smoke against the real Anthropic API. Marked `#[ignore]` — doesn't run in CI.
/// Run: `MINDFORK_ANTHROPIC_KEY=sk-ant-... cargo test anthropic -- --ignored`.
#[cfg(test)]
mod ignored_smoke {
use super::*;
use crate::entities::sampling::SamplingConfig;
use crate::shared::api::contract::{ApiMessage, ApiToolCall, ThinkingBlock, ToolSchema};
fn client_from_env() -> Option<AnthropicClient> {
let key = std::env::var("MINDFORK_ANTHROPIC_KEY").ok()?;
let model =
std::env::var("MINDFORK_ANTHROPIC_MODEL").unwrap_or_else(|_| "claude-opus-4-8".into());
Some(AnthropicClient::new(
"https://api.anthropic.com",
key,
model,
))
}
#[tokio::test]
#[ignore = "requires MINDFORK_ANTHROPIC_KEY (live Anthropic API)"]
async fn simple_generation() {
let Some(client) = client_from_env() else {
eprintln!("skip: MINDFORK_ANTHROPIC_KEY not set");
return;
};
let req = ChatRequest {
continue_final: false,
system: Some("You are a helpful assistant.".into()),
messages: vec![ApiMessage::user("Reply with exactly: pong")],
sampling: SamplingConfig {
max_tokens: Some(64),
..Default::default()
},
tools: vec![],
};
let mut stream = client.chat_stream(req, Default::default()).await.unwrap();
let mut text = String::new();
let mut finish = None;
while let Some(chunk) = stream.next().await {
match chunk {
ChatChunk::Text(t) => text.push_str(&t),
ChatChunk::Finished(r) => {
finish = Some(r);
break;
}
ChatChunk::Error { message, .. } => {
eprintln!("engine error: {message}");
}
_ => {}
}
}
assert!(!text.is_empty(), "expected non-empty response");
assert!(matches!(
finish,
Some(FinishReason::Stop | FinishReason::Length)
));
}
/// Image input (spec §9.10): a base64 `image` block reaches the model and is
/// described. Verified live before the wire was written — see
/// docs/research/multimodal-images.md §2.2.
#[tokio::test]
#[ignore = "requires MINDFORK_ANTHROPIC_KEY (live Anthropic API)"]
async fn image_input_is_described() {
let Some(client) = client_from_env() else {
eprintln!("skip: MINDFORK_ANTHROPIC_KEY not set");
return;
};
let req = ChatRequest {
continue_final: false,
system: None,
messages: vec![
ApiMessage::user(crate::shared::api::VISION_PROMPT).with_images(vec![
crate::shared::api::ApiImage::new(
"image/png",
&crate::shared::api::blue_square_png_base64(),
None,
),
]),
],
sampling: SamplingConfig {
max_tokens: Some(256),
..Default::default()
},
tools: vec![],
};
let mut stream = client.chat_stream(req, Default::default()).await.unwrap();
let mut text = String::new();
while let Some(chunk) = stream.next().await {
match chunk {
ChatChunk::Text(t) => text.push_str(&t),
ChatChunk::Error { message, .. } => eprintln!("engine error: {message}"),
ChatChunk::Finished(_) => break,
_ => {}
}
}
eprintln!("anthropic vision reply: {text}");
crate::shared::api::assert_sees_blue_square(&text, "anthropic");
}
/// Phase A: with thinking enabled, extended thinking runs and its signature
/// arrives; the visible **summary is best-effort**.
///
/// The original assertion — `display:"summarized"` implies non-empty
/// "thoughts" — turned out not to be an invariant, and it had been failing:
/// **measured** on `claude-opus-4-8` (2026-08-12, five runs, clean streams with
/// no error chunk) the turn comes back `thoughts=0 chars, signature=380 chars,
/// text=50 chars`. A signature that long only exists for a real thinking block,
/// so thinking *did* happen — Anthropic simply summarized a short one to
/// nothing. The deterministic claims are therefore the signature (which is also
/// what the tool-use round-trip depends on, and which is empty if `thinking` is
/// ever dropped from the request or `signature_delta` stops being parsed) and
/// the answer itself; the summary is logged, not asserted. Same shape as the
/// OpenAI Responses sibling, whose comment already said "on a trivial task the
/// summary might be absent".
///
/// `reasoning_effort: High` is kept for the reason its tool-use sibling states:
/// `thinking:{type:"adaptive"}` lets the model decide *whether* to think, and
/// without the nudge a trivial prompt can skip reasoning altogether — which
/// would empty the signature too, and that assertion is the point of this smoke.
#[tokio::test]
#[ignore = "requires MINDFORK_ANTHROPIC_KEY (live Anthropic API)"]
async fn extended_thinking_streams_thoughts_and_signature() {
let Some(client) = client_from_env() else {
eprintln!("skip: MINDFORK_ANTHROPIC_KEY not set");
return;
};
let req = ChatRequest {
continue_final: false,
system: None,
messages: vec![ApiMessage::user(
"Think step by step: what is 17 * 23? Show brief reasoning.",
)],
sampling: SamplingConfig {
max_tokens: Some(2048),
thinking: Some(true),
reasoning_effort: Some(crate::entities::sampling::ReasoningEffort::High),
..Default::default()
},
tools: vec![],
};
let mut stream = client.chat_stream(req, Default::default()).await.unwrap();
let mut thoughts = String::new();
let mut signature = String::new();
let mut text = String::new();
while let Some(chunk) = stream.next().await {
match chunk {
ChatChunk::Thoughts(t) => thoughts.push_str(&t),
ChatChunk::ThoughtsSignature(r) => signature.push_str(&r.signature),
ChatChunk::Text(t) => text.push_str(&t),
ChatChunk::Finished(_) => break,
ChatChunk::Error { message, .. } => {
eprintln!("engine error: {message}");
}
_ => {}
}
}
eprintln!(
"thoughts={} chars, signature={} chars, text={} chars",
thoughts.len(),
signature.len(),
text.len()
);
if thoughts.is_empty() {
eprintln!("note: the provider delivered no thinking summary for this turn");
}
assert!(
!signature.is_empty(),
"expected a thinking signature — extended thinking did not run \
(thoughts={} chars, text={} chars)",
thoughts.len(),
text.len()
);
assert!(!text.is_empty(), "expected final answer");
}
/// Phase B: thinking + tool-use. The first round gives "thoughts"+a signature+a call; the second
/// request resends the thinking block (with the signature) on an assistant turn with tool_use and
/// the tool result — Anthropic must not return 400 (which is exactly what checks the signature).
#[tokio::test]
#[ignore = "requires MINDFORK_ANTHROPIC_KEY (live Anthropic API)"]
async fn thinking_with_tool_use_round_trips_signature() {
let Some(client) = client_from_env() else {
eprintln!("skip: MINDFORK_ANTHROPIC_KEY not set");
return;
};
let tool = ToolSchema {
name: "get_weather".into(),
description: "Get the current weather for a city.".into(),
parameters: serde_json::json!({
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
}),
};
let sampling = SamplingConfig {
max_tokens: Some(2048),
thinking: Some(true),
// High effort: nudge the model to actually think before the
// call (otherwise on a trivial request adaptive thinking might
// skip the reasoning — and there'd be no signature).
reasoning_effort: Some(crate::entities::sampling::ReasoningEffort::High),
..Default::default()
};
// A prompt with an explicit reasoning step (picking a city) — so the model
// generates a thinking block with a signature before calling the tool.
let prompt = "Two candidate cities: Paris and Berlin. Reason briefly about \
which one is the capital of France, then call the get_weather tool for \
that city.";
let round1 = ChatRequest {
continue_final: false,
system: None,
messages: vec![ApiMessage::user(prompt)],
sampling: sampling.clone(),
tools: vec![tool.clone()],
};
let mut stream = client
.chat_stream(round1, Default::default())
.await
.unwrap();
let mut thoughts = String::new();
let mut signature = String::new();
let mut acc = crate::shared::api::ToolCallAccumulator::default();
let mut reason = FinishReason::Stop;
while let Some(chunk) = stream.next().await {
match chunk {
ChatChunk::Thoughts(t) => thoughts.push_str(&t),
ChatChunk::ThoughtsSignature(r) => signature.push_str(&r.signature),
ChatChunk::ToolCall(d) => acc.push(d),
ChatChunk::Finished(r) => {
reason = r;
break;
}
ChatChunk::Error { message, .. } => {
eprintln!("engine error: {message}");
}
_ => {}
}
}
assert_eq!(
reason,
FinishReason::ToolCalls,
"model should call the tool"
);
let calls = acc.finish();
assert!(!calls.is_empty(), "expected a tool call");
assert!(!signature.is_empty(), "expected a thinking signature");
let call = &calls[0];
// Second round: assistant(thinking+signature, tool_use) → tool_result.
let round2 = ChatRequest {
continue_final: false,
system: None,
messages: vec![
ApiMessage::user(prompt),
ApiMessage::assistant_tool_calls(
"",
vec![ApiToolCall {
thought_signature: None,
id: call.id.clone(),
name: call.name.clone(),
arguments: call.arguments.clone(),
}],
)
.with_thinking_blocks(vec![ThinkingBlock {
text: thoughts.clone(),
signature: signature.clone(),
id: None,
}]),
ApiMessage::tool(&call.id, "18°C, sunny"),
],
sampling,
tools: vec![tool],
};
let mut stream = client
.chat_stream(round2, Default::default())
.await
.unwrap();
let mut text = String::new();
let mut finish = None;
while let Some(chunk) = stream.next().await {
match chunk {
ChatChunk::Text(t) => text.push_str(&t),
ChatChunk::Finished(r) => {
finish = Some(r);
break;
}
ChatChunk::Error { message, .. } => {
eprintln!("engine error: {message}");
}
_ => {}
}
}
// If the signature hadn't been resent/were invalid, Anthropic would return 400
// and chat_stream would yield Finished(Error) with empty text.
assert!(
matches!(finish, Some(FinishReason::Stop | FinishReason::Length)),
"second round must succeed (signature round-trip), got {finish:?}"
);
assert!(
!text.is_empty(),
"expected a final answer after tool result"
);
}
}