-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmessage.rs
More file actions
1579 lines (1484 loc) · 55.8 KB
/
Copy pathmessage.rs
File metadata and controls
1579 lines (1484 loc) · 55.8 KB
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
//! Protocol-agnostic message types. This module replaces the prior practice of
//! storing the entire conversation as `Vec<serde_json::Value>` (implicitly
//! OpenAI chat-completions shaped). Every message is now a first-class Rust
//! type so that the harness can speak both OpenAI `/chat/completions` and
//! Anthropic `/v1/messages` natively — each provider path converts *from* these
//! types directly into its own wire format, instead of translating JSON→JSON.
//!
//! **Persistence compatibility:** serialisation uses serde with `#[serde(tag =
//! "role")]` so the on-disk JSONL format is **byte-for-byte identical** to the
//! old `Vec<Value>` format. Old sessions load seamlessly; new sessions can be
//! read by an older harness without any migration.
//!
//! **Tolerant deserialization:** the [`Message::try_from`] impl uses a custom
//! helper that coerces / defaults a few fields providers sometimes emit in
//! shapes that do not match the strong type (e.g. `arguments` as a JSON object
//! instead of a string, or assistant `content` as a multimodal array). This
//! keeps a single malformed tool-call or content block from aborting the
//! whole conversation deserialization, and mirrors the sanitizers in
//! `provider::sanitize_tool_call_arguments` which used to run *after* the
//! number-crunching `Value` parse.
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
// ---------------------------------------------------------------------------
// Core types
// ---------------------------------------------------------------------------
/// One message in the agent conversation — the canonical, provider-agnostic
/// format used everywhere except the actual HTTP wire bytes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "role")]
#[serde(rename_all = "lowercase")]
pub enum Message {
#[serde(rename = "system")]
System {
#[serde(default, skip_serializing_if = "Option::is_none")]
name: Option<String>,
content: Content,
},
#[serde(rename = "user")]
User {
#[serde(default, skip_serializing_if = "Option::is_none")]
name: Option<String>,
content: Content,
},
#[serde(rename = "assistant")]
Assistant {
#[serde(default, skip_serializing_if = "Option::is_none")]
name: Option<String>,
/// Assistant text content. Providers may emit this as a JSON array of
/// text blocks (multimodal-shaped assistant content), as a plain string,
/// or omit it entirely when only tool_calls are present.
/// `coerce_optional_text` accepts a string or a multimodal array and
/// joins the text parts into one string so the field is always a string.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "coerce_optional_text"
)]
content: Option<String>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
rename = "reasoning_content"
)]
thinking: Option<String>,
/// Provider-native signed thinking blocks. LiteLLM exposes these on its
/// OpenAI-compatible response and requires them verbatim on later tool
/// turns for Anthropic-backed models.
#[serde(default, skip_serializing_if = "Option::is_none")]
thinking_blocks: Option<Vec<ThinkingBlock>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
tool_calls: Option<Vec<ToolCall>>,
},
#[serde(rename = "tool")]
Tool {
tool_call_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
name: Option<String>,
content: String,
},
}
/// Message content — either a plain string or a multimodal array of parts
/// (text blocks / inline images).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Content {
Text(String),
Multimodal(Vec<ContentPart>),
}
/// One part of a multimodal user message.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ContentPart {
#[serde(rename = "text")]
Text { text: String },
#[serde(rename = "image_url")]
Image { image_url: ImageUrl },
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageUrl {
pub url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
/// Replayable provider-native thinking block. `data` carries Anthropic's
/// redacted-thinking payload; ordinary thinking blocks use `thinking` plus the
/// provider signature.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ThinkingBlock {
#[serde(rename = "type")]
pub typ: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thinking: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signature: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data: Option<String>,
}
/// An assistant tool-call entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCall {
#[serde(default)]
pub id: String,
#[serde(rename = "type", default)]
pub typ: String,
pub function: FunctionCall,
/// Gemini 3 / Code Assist thought signature for this function call part.
/// Must be echoed back on subsequent turns or the API 400s with
/// "Function call is missing a thought_signature". Not part of the OpenAI
/// wire shape; ignored by non-Google providers.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thought_signature: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionCall {
#[serde(default)]
pub name: String,
/// Tool-call arguments, always stored as a JSON **string**. Some providers
/// emit this as a JSON object instead of a string, and some omit it entirely.
/// The custom deserializer normalizes all of these to a string so the
/// downstream sanitizers/dispatchers always see the same shape.
#[serde(default = "empty_object_string", deserialize_with = "coerce_arguments")]
pub arguments: String,
}
fn empty_object_string() -> String {
"{}".to_string()
}
/// Serde deserializer that accepts whatever the provider sent for `arguments`
/// and always produces a `String` field:
/// - a string value is taken verbatim;
/// - a non-string value (e.g. an object) is re-serialized back to a string;
/// - a missing value or null becomes "{}".
fn coerce_arguments<'de, D>(de: D) -> Result<String, D::Error>
where
D: serde::Deserializer<'de>,
{
let v = Option::<Value>::deserialize(de)?.unwrap_or(Value::Null);
match v {
Value::String(s) => Ok(s),
Value::Null => Ok("{}".to_string()),
other => Ok(match serde_json::to_string(&other) {
Ok(s) => s,
// Fallback for un-serializable values (shouldn't happen, but never
// make deserialization itself fail).
Err(_) => "{}".to_string(),
}),
}
}
/// Serde deserializer for assistant `content`. Accepts: a string (kept verbatim);
/// a multimodal array (text parts joined with a newline, image parts become
/// a placeholder so they're not dropped silently); null/missing (None).
fn coerce_optional_text<'de, D>(de: D) -> Result<Option<String>, D::Error>
where
D: serde::Deserializer<'de>,
{
let v = Option::<Value>::deserialize(de)?;
match v {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s)),
Some(Value::Array(arr)) => {
let mut out = String::new();
for part in arr {
let text = match part.get("type").and_then(|t| t.as_str()).unwrap_or("") {
"text" => part.get("text").and_then(|t| t.as_str()).unwrap_or(""),
"image_url" => "[image]",
_ => "",
};
if text.is_empty() {
continue;
}
if !out.is_empty() {
out.push('\n');
}
out.push_str(text);
}
Ok(Some(out))
}
Some(other) => Ok(Some(other.to_string())),
}
}
// ---------------------------------------------------------------------------
// Constructors — ergonomic Message builders
// ---------------------------------------------------------------------------
impl Message {
pub fn system(content: impl Into<String>) -> Self {
Message::System {
name: None,
content: Content::Text(content.into()),
}
}
pub fn user(content: impl Into<String>) -> Self {
Message::User {
name: None,
content: Content::Text(content.into()),
}
}
pub fn user_multimodal(parts: Vec<ContentPart>) -> Self {
Message::User {
name: None,
content: Content::Multimodal(parts),
}
}
pub fn assistant(content: impl Into<String>) -> Self {
Message::Assistant {
name: None,
content: Some(content.into()),
thinking: None,
thinking_blocks: None,
tool_calls: None,
}
}
pub fn assistant_tool_calls(calls: Vec<ToolCall>) -> Self {
Message::Assistant {
name: None,
content: None,
thinking: None,
thinking_blocks: None,
tool_calls: Some(calls),
}
}
pub fn tool(call_id: impl Into<String>, result: impl Into<String>) -> Self {
Message::Tool {
tool_call_id: call_id.into(),
name: None,
content: result.into(),
}
}
}
// ---------------------------------------------------------------------------
// Accessors
// ---------------------------------------------------------------------------
impl Message {
/// The role string: "system" | "user" | "assistant" | "tool".
pub fn role(&self) -> &'static str {
match self {
Message::System { .. } => "system",
Message::User { .. } => "user",
Message::Assistant { .. } => "assistant",
Message::Tool { .. } => "tool",
}
}
/// Plain-text content, if this message has exactly a string content.
pub fn content_text(&self) -> Option<&str> {
match self {
Message::System { content, .. } | Message::User { content, .. } => match content {
Content::Text(s) => Some(s.as_str()),
Content::Multimodal(_) => None,
},
Message::Assistant { content, .. } => content.as_deref(),
Message::Tool { content, .. } => Some(content.as_str()),
}
}
/// Multimodal parts, if any.
pub fn content_parts(&self) -> Option<&[ContentPart]> {
match self {
Message::System {
content: Content::Multimodal(p),
..
}
| Message::User {
content: Content::Multimodal(p),
..
} => Some(p.as_slice()),
_ => None,
}
}
/// Tool calls, if this is an assistant message with tool_calls.
pub fn tool_calls(&self) -> Option<&[ToolCall]> {
match self {
Message::Assistant {
tool_calls: Some(ref tc),
..
} => Some(tc.as_slice()),
_ => None,
}
}
/// Assistant thinking content, if any.
pub fn thinking(&self) -> Option<&str> {
match self {
Message::Assistant {
thinking: Some(t), ..
} => Some(t.as_str()),
_ => None,
}
}
/// Signed provider thinking blocks, if the assistant response supplied any.
pub fn thinking_blocks(&self) -> Option<&[ThinkingBlock]> {
match self {
Message::Assistant {
thinking_blocks: Some(blocks),
..
} => Some(blocks.as_slice()),
_ => None,
}
}
/// Tool result call-id, for tool messages only.
pub fn tool_call_id(&self) -> Option<&str> {
match self {
Message::Tool {
tool_call_id: ref id,
..
} => Some(id.as_str()),
_ => None,
}
}
// Predicates
pub fn is_system(&self) -> bool {
matches!(self, Message::System { .. })
}
pub fn is_user(&self) -> bool {
matches!(self, Message::User { .. })
}
pub fn is_assistant(&self) -> bool {
matches!(self, Message::Assistant { .. })
}
pub fn is_tool(&self) -> bool {
matches!(self, Message::Tool { .. })
}
pub fn has_tool_calls(&self) -> bool {
matches!(
self,
Message::Assistant {
tool_calls: Some(_),
..
}
)
}
/// If assistant `content` embeds MiniMax-style `<think>…</think>` and no
/// separate `thinking` field is set, peel the tag into `thinking` and leave
/// only the visible answer in `content`. Idempotent. Used on session load
/// so older proxy sessions (thinking stuck in content) render correctly and
/// multi-turn replay can re-embed cleanly.
pub fn normalize_embedded_thinking(&mut self) {
let Message::Assistant {
content, thinking, ..
} = self
else {
return;
};
if thinking.as_ref().is_some_and(|t| !t.is_empty()) {
return;
}
let Some(raw) = content.as_deref() else {
return;
};
if let Some((thought, visible)) = peel_think_tags(raw) {
*thinking = if thought.is_empty() {
None
} else {
Some(thought)
};
*content = if visible.is_empty() {
None
} else {
Some(visible)
};
}
}
}
/// Peel a leading `<think>…</think>` block from assistant content.
/// Returns `(thinking, visible_content)` when a complete open tag is present.
pub fn peel_think_tags(raw: &str) -> Option<(String, String)> {
let trimmed = raw.trim_start();
let rest = trimmed.strip_prefix("<think>")?;
let close = rest.find("</think>")?;
let thought = rest[..close].trim().to_string();
// Drop repeated/stray closing tags some MiniMax proxy streams append.
let mut visible = rest[close + "</think>".len()..].to_string();
while let Some(v) = visible
.trim_start()
.strip_prefix("</think>")
.map(|s| s.to_string())
{
visible = v;
}
let visible = visible.trim_start().to_string();
Some((thought, visible))
}
// ---------------------------------------------------------------------------
// Conversion: Message ↔ serde_json::Value (the old format, for gradual
// migration and backwards-compat).
// ---------------------------------------------------------------------------
impl From<&Message> for Value {
fn from(msg: &Message) -> Value {
// We literally re-serialise the Message — because the serde attributes
// are designed to match the old JSON format exactly, this produces the
// same JSON that the old `Vec<Value>` pipeline did.
serde_json::to_value(msg).unwrap_or(Value::Null)
}
}
impl TryFrom<&Value> for Message {
type Error = String;
fn try_from(v: &Value) -> Result<Self, Self::Error> {
serde_json::from_value(v.clone()).map_err(|e| format!("invalid message: {e}"))
}
}
// ---------------------------------------------------------------------------
// Batch conversion helpers
// ---------------------------------------------------------------------------
/// Convert a slice of Messages into the old `Vec<Value>` format. Useful during
/// migration when a function still expects `&[Value]`.
pub fn to_values(messages: &[Message]) -> Vec<Value> {
messages.iter().map(Value::from).collect()
}
/// Try to parse a slice of JSON Values into Messages. Returns an error on the
/// first malformed entry.
#[allow(dead_code)]
pub fn from_values(values: &[Value]) -> Result<Vec<Message>, String> {
values.iter().map(Message::try_from).collect()
}
/// Best-effort variant: silently skips any malformed entry instead of failing
/// the whole batch. Use when the source may contain hand-edited or externally-
/// sourced messages where a single bad entry shouldn't drop the entire history.
#[allow(dead_code)]
pub fn from_values_best_effort(values: &[Value]) -> Vec<Message> {
values
.iter()
.filter_map(|v| Message::try_from(v).ok())
.collect()
}
// ---------------------------------------------------------------------------
// Wire-format helpers (protocol-specific → placed here so provider.rs doesn't
// have to reach into raw JSON for message fields).
// ---------------------------------------------------------------------------
impl Message {
/// Build the top-level `messages` array for an **OpenAI `/v1/chat/completions`**
/// request body directly from this slice of Messages — no intermediate
/// translation step.
pub fn to_openai_messages(messages: &[Self]) -> Vec<Value> {
to_values(messages)
}
/// Build the `tools` array for an **OpenAI `/v1/chat/completions`** request
/// body from a list of tool definitions (still in OpenAI function-calling
/// shape — the canonical tool-definition format is provider-agnostic for
/// now since both OpenAI and the Anthropic converter read the same schema).
pub fn to_openai_tools(defs: &[Value]) -> Vec<Value> {
defs.to_vec()
}
}
// ---------------------------------------------------------------------------
// Anthropic wire-format (native, not a JSON→JSON translator — reads Message
// fields directly via pattern matching).
// ---------------------------------------------------------------------------
/// Host-aware flags for Anthropic `/v1/messages`.
///
/// Official Anthropic gets cache breakpoints and signed-only thinking replay.
/// Compatible gateways (LiteLLM, MiniMax, llama.cpp, OpenCode Go) drop
/// first-party-only fields that 400 and replay unsigned thinking the way
/// Oh My Pi does.
#[derive(Clone, Copy, Debug)]
pub struct AnthropicWireOptions<'a> {
pub reasoning_effort: &'a str,
pub thinking_levels: &'a [String],
pub max_tokens: u32,
pub cache_control: bool,
pub replay_unsigned_thinking: bool,
pub sanitize_tool_schema: bool,
pub send_tool_choice: bool,
}
/// Build an Anthropic `/v1/messages` request body from Messages.
///
/// Prompt-cache breakpoints (`cache_control: ephemeral`) are first-party only:
/// - Standing system prompt (leading system messages only) gets an explicit
/// breakpoint — stable across turns within a session.
/// - System messages that appear AFTER conversation content (relevant-memory /
/// work-state tails) are emitted as a final **user** message so they never
/// sit under the system breakpoint (that would bust the cache every turn).
/// - A rolling breakpoint is placed on the last cache-eligible block of the
/// last **persisted** message (not on the transient tail, never on thinking).
pub fn build_anthropic_request(
messages: &[Message],
tools: &[Value],
reasoning_effort: &str,
thinking_levels: &[String],
max_tokens: u32,
) -> Value {
build_anthropic_wire(
messages,
tools,
AnthropicWireOptions {
reasoning_effort,
thinking_levels,
max_tokens,
cache_control: true,
replay_unsigned_thinking: false,
sanitize_tool_schema: true,
send_tool_choice: true,
},
)
}
/// Build an Anthropic `/v1/messages` body with explicit compatibility flags.
pub fn build_anthropic_wire(
messages: &[Message],
tools: &[Value],
opts: AnthropicWireOptions<'_>,
) -> Value {
let mut system_parts: Vec<String> = Vec::new();
let mut trailing_transient: Vec<String> = Vec::new();
let mut out: Vec<Value> = Vec::new();
let mut seen_non_system = false;
for m in messages {
match m {
Message::System { content, .. } => {
if !seen_non_system {
push_content(content, &mut system_parts);
} else {
// Transient tails pushed after conversation content — keep
// them out of the cached system prefix.
push_content(content, &mut trailing_transient);
}
}
Message::User { content, .. } => {
seen_non_system = true;
let blocks = content_to_blocks(content);
if blocks_are_empty_text(&blocks) {
continue;
}
push_or_merge_anth(&mut out, "user", blocks);
}
Message::Assistant {
content: text,
thinking,
thinking_blocks,
tool_calls,
..
} => {
seen_non_system = true;
let mut blocks =
assistant_content_blocks(text, thinking, thinking_blocks, tool_calls, &opts);
partition_tool_use_to_tail(&mut blocks);
if blocks.is_empty() {
continue;
}
push_or_merge_anth(&mut out, "assistant", blocks);
}
Message::Tool {
ref tool_call_id,
ref content,
..
} => {
seen_non_system = true;
let result = if content.is_empty() {
"Tool finished with no output."
} else {
content.as_str()
};
push_or_merge_anth(
&mut out,
"user",
vec![json!({
"type": "tool_result",
"tool_use_id": tool_call_id,
"content": result,
})],
);
}
}
}
repair_anthropic_roles(&mut out);
// Rolling breakpoint on the last persisted message (before any transient
// tail we may append below). Anthropic's lookback is 20 blocks. Never put
// cache_control on thinking — first-party 400s that.
if opts.cache_control {
apply_cache_control_to_last_eligible(&mut out);
}
// Transient tails as a final user message — no cache_control (changes
// every turn; must not be the automatic/explicit breakpoint).
if !trailing_transient.is_empty() {
out.push(json!({
"role": "user",
"content": [{
"type": "text",
"text": trailing_transient.join("\n\n"),
}]
}));
} else if out
.last()
.and_then(|m| m.get("role").and_then(Value::as_str))
== Some("assistant")
{
// Anthropic rejects a trailing assistant turn. Oh My Pi inserts the
// same neutral nudge so tool-less retries stay valid.
out.push(json!({
"role": "user",
"content": [{"type": "text", "text": "Continue."}]
}));
}
let mut body = serde_json::Map::new();
// model is set by the caller (stream_turn_anthropic appends it).
// Anthropic requires a positive max_tokens; 0 is invalid on the wire.
// Match the adapter default (8192) rather than sending 1, which would
// truncate every reply when the model budget is unknown/unset.
let max_tokens = if opts.max_tokens == 0 {
8192
} else {
opts.max_tokens
};
body.insert("max_tokens".into(), json!(max_tokens));
if !system_parts.is_empty() {
let mut system_block = json!({
"type": "text",
"text": system_parts.join("\n\n"),
});
if opts.cache_control {
system_block["cache_control"] = json!({"type": "ephemeral"});
}
body.insert("system".into(), json!([system_block]));
}
if !out.is_empty() {
body.insert("messages".into(), Value::Array(out));
}
if !tools.is_empty() {
let mut atools = anthropic_tools_from_defs(tools, opts.sanitize_tool_schema);
if opts.cache_control {
if let Some(last) = atools.last_mut() {
if let Some(obj) = last.as_object_mut() {
obj.insert("cache_control".into(), json!({"type": "ephemeral"}));
}
}
}
body.insert("tools".into(), Value::Array(atools));
if opts.send_tool_choice {
body.insert("tool_choice".into(), json!({"type": "auto"}));
}
}
if !opts.thinking_levels.is_empty() {
let wants = !matches!(
opts.reasoning_effort.to_ascii_lowercase().as_str(),
"" | "none" | "minimal" | "off"
);
if wants {
let resolved = resolve_effort_local(opts.reasoning_effort, opts.thinking_levels);
if let Some(budget) = anthropic_thinking_budget(&resolved, max_tokens) {
body.insert(
"thinking".into(),
json!({"type": "enabled", "budget_tokens": budget}),
);
}
}
}
Value::Object(body)
}
// ---- private helpers for the Anthropic builder ----
fn push_content(content: &Content, parts: &mut Vec<String>) {
match content {
Content::Text(s) => {
if !s.is_empty() {
parts.push(s.clone());
}
}
Content::Multimodal(arr) => {
for p in arr {
if let ContentPart::Text { text } = p {
if !text.is_empty() {
parts.push(text.clone());
}
}
}
}
}
}
fn content_to_blocks(content: &Content) -> Vec<Value> {
match content {
Content::Text(s) => vec![json!({"type": "text", "text": s})],
Content::Multimodal(arr) => arr
.iter()
.map(|p| match p {
ContentPart::Text { text } => json!({"type": "text", "text": text}),
ContentPart::Image { image_url } => {
anthropic_image_block(&image_url.url, image_url.detail.as_deref())
}
})
.collect(),
}
}
fn assistant_content_blocks(
text: &Option<String>,
thinking: &Option<String>,
thinking_blocks: &Option<Vec<ThinkingBlock>>,
tool_calls: &Option<Vec<ToolCall>>,
opts: &AnthropicWireOptions<'_>,
) -> Vec<Value> {
let mut blocks = Vec::new();
let mut emitted_thinking = false;
if let Some(signed) = thinking_blocks {
for block in signed {
let valid_signed = match block.typ.as_str() {
"thinking" => block.signature.as_ref().is_some_and(|s| !s.is_empty()),
"redacted_thinking" => block.data.as_ref().is_some_and(|s| !s.is_empty()),
_ => false,
};
if valid_signed {
if let Ok(value) = serde_json::to_value(block) {
blocks.push(value);
emitted_thinking = true;
}
continue;
}
if opts.replay_unsigned_thinking && block.typ == "thinking" {
if let Some(thought) = block.thinking.as_ref().filter(|s| !s.is_empty()) {
blocks.push(json!({
"type": "thinking",
"thinking": thought,
"signature": "",
}));
emitted_thinking = true;
}
}
}
}
if !emitted_thinking && opts.replay_unsigned_thinking {
if let Some(thought) = thinking.as_ref().filter(|s| !s.is_empty()) {
blocks.push(json!({
"type": "thinking",
"thinking": thought,
"signature": "",
}));
}
}
if let Some(t) = text {
if !t.is_empty() {
blocks.push(json!({"type": "text", "text": t}));
}
}
if let Some(calls) = tool_calls {
for tc in calls {
let input: Value =
serde_json::from_str(&tc.function.arguments).unwrap_or_else(|_| json!({}));
blocks.push(json!({
"type": "tool_use",
"id": tc.id,
"name": tc.function.name,
"input": input,
}));
}
}
blocks
}
/// Anthropic rejects any non-`tool_use` block after a `tool_use` in the same
/// assistant turn. Stable-partition so thinking/text stay ahead of tools.
fn partition_tool_use_to_tail(blocks: &mut Vec<Value>) {
let mut saw_tool = false;
let needs_partition = blocks.iter().any(|block| {
if block_type(block) == Some("tool_use") {
saw_tool = true;
false
} else {
saw_tool
}
});
if !needs_partition {
return;
}
let (tools, rest): (Vec<_>, Vec<_>) = blocks
.drain(..)
.partition(|block| block_type(block) == Some("tool_use"));
blocks.extend(rest);
blocks.extend(tools);
}
fn repair_anthropic_roles(out: &mut Vec<Value>) {
let mut i = out.len();
while i > 1 {
i -= 1;
let prev_assistant = out[i - 1].get("role").and_then(Value::as_str) == Some("assistant");
let this_assistant = out[i].get("role").and_then(Value::as_str) == Some("assistant");
if prev_assistant && this_assistant {
out.insert(
i,
json!({
"role": "user",
"content": [{"type": "text", "text": "Continue."}]
}),
);
}
}
}
fn apply_cache_control_to_last_eligible(out: &mut [Value]) {
let Some(last) = out.last_mut() else {
return;
};
let Some(arr) = last.get_mut("content").and_then(|c| c.as_array_mut()) else {
return;
};
for block in arr.iter_mut().rev() {
if !block.is_object() {
continue;
}
match block_type(block) {
Some("thinking") | Some("redacted_thinking") => continue,
_ => {
if let Some(obj) = block.as_object_mut() {
obj.insert("cache_control".into(), json!({"type": "ephemeral"}));
}
return;
}
}
}
}
fn blocks_are_empty_text(blocks: &[Value]) -> bool {
!blocks.is_empty()
&& blocks.iter().all(|block| {
block_type(block) == Some("text")
&& block
.get("text")
.and_then(Value::as_str)
.is_none_or(|text| text.trim().is_empty())
})
}
fn block_type(block: &Value) -> Option<&str> {
block.get("type").and_then(Value::as_str)
}
/// Build an Anthropic `image` block from an OpenAI `image_url.url`. Supports
/// `data:<media>;base64,<data>` (-> base64 source) and plain URLs (-> url source).
/// The optional `detail` is forwarded as a `detail` field on the source when the
/// url source path is taken (Anthropic image blocks accept a `detail` hint).
fn anthropic_image_block(url: &str, detail: Option<&str>) -> Value {
if let Some(rest) = url.strip_prefix("data:") {
if let Some((meta, data)) = rest.split_once(',') {
let media = meta.split(';').next().unwrap_or("image/png");
return json!({
"type": "image",
"source": { "type": "base64", "media_type": media, "data": data }
});
}
}
let mut img = json!({"type": "image", "source": {
"type": "url",
"url": url,
}});
if let Some(d) = detail {
img["source"]["detail"] = json!(d);
}
img
}
fn push_or_merge_anth(out: &mut Vec<Value>, role: &str, blocks: Vec<Value>) {
if let Some(last) = out.last_mut() {
if last.get("role").and_then(|v| v.as_str()) == Some(role) {
if let Some(arr) = last.get_mut("content").and_then(|c| c.as_array_mut()) {
arr.extend(blocks);
return;
}
}
}
out.push(json!({"role": role, "content": blocks}));
}
/// Convert OpenAI function-calling tool defs to Anthropic `input_schema` tools.
fn anthropic_tools_from_defs(tools: &[Value], sanitize_schema: bool) -> Vec<Value> {
tools
.iter()
.filter_map(|t| {
let f = t.get("function")?;
let name = f.get("name")?.as_str()?;
let description = f.get("description").and_then(|v| v.as_str()).unwrap_or("");
let mut schema = f.get("parameters").cloned().unwrap_or_else(|| json!({}));
if sanitize_schema {
schema = sanitize_anthropic_tool_schema(schema);
}
Some(json!({
"name": name,
"description": description,
"input_schema": schema,
}))
})
.collect()
}
/// JSON Schema whitelist matching Oh My Pi / Anthropic's accepted subset.
/// Extra keywords (`$schema`, `$defs`, `unevaluatedProperties`, …) 400 both
/// first-party Anthropic and most compatible gateways.
fn sanitize_anthropic_tool_schema(value: Value) -> Value {
match value {
Value::Object(map) => {
let typ = map
.get("type")
.and_then(Value::as_str)
.unwrap_or("")
.to_string();
let mut out = serde_json::Map::new();
for (key, child) in map {
if !keep_anthropic_schema_key(&key, &typ) {
continue;
}
let child = if key == "properties" {
sanitize_schema_property_map(child)
} else {
sanitize_anthropic_tool_schema(child)
};
out.insert(key, child);
}
Value::Object(out)
}
Value::Array(arr) => Value::Array(
arr.into_iter()
.map(sanitize_anthropic_tool_schema)
.collect(),
),
other => other,
}
}
fn sanitize_schema_property_map(value: Value) -> Value {
match value {
Value::Object(map) => {
let mut out = serde_json::Map::new();
for (key, child) in map {
out.insert(key, sanitize_anthropic_tool_schema(child));
}
Value::Object(out)
}
other => sanitize_anthropic_tool_schema(other),
}
}
fn keep_anthropic_schema_key(key: &str, typ: &str) -> bool {
matches!(
key,
"type"