Skip to main content

kaeso_kpp/
block.rs

1use bytes::Bytes;
2use serde::{Deserialize, Serialize};
3
4use crate::b64::Base64Text;
5use crate::dialect::{DialectId, Origin};
6use crate::error::KppError;
7use crate::extras::Extras;
8use crate::raw::RawJson;
9
10#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12#[non_exhaustive]
13pub enum Block {
14    Text(TextBlock),
15    Image(ImageBlock),
16    Document(DocumentBlock),
17    Audio(AudioBlock),
18    Video(VideoBlock),
19    ToolCall(ToolCallBlock),
20    ToolResult(ToolResultBlock),
21    Reasoning(ReasoningBlock),
22    Refusal(RefusalBlock),
23    Unknown(RawItem),
24    /// Structured data as a part of its own, such as OpenAI's `input_json` in a decision request.
25    Json(JsonBlock),
26}
27
28impl Block {
29    pub fn text(text: impl Into<String>) -> Self {
30        Block::Text(TextBlock::new(text))
31    }
32
33    pub fn tool_call(id: impl Into<String>, name: impl Into<String>, arguments: RawJson) -> Self {
34        Block::ToolCall(ToolCallBlock::new(id, name, arguments))
35    }
36
37    pub fn tool_result(call_id: impl Into<String>, content: Vec<Block>, is_error: bool) -> Self {
38        let mut result = ToolResultBlock::new(call_id, content);
39        result.is_error = is_error;
40        Block::ToolResult(result)
41    }
42
43    pub fn image(source: Source) -> Self {
44        Block::Image(ImageBlock::new(source))
45    }
46
47    pub fn audio(source: Source) -> Self {
48        Block::Audio(AudioBlock::new(source))
49    }
50
51    pub fn video(source: Source) -> Self {
52        Block::Video(VideoBlock::new(source))
53    }
54
55    pub fn json(data: RawJson) -> Self {
56        Block::Json(JsonBlock::new(data))
57    }
58
59    pub fn kind(&self) -> &'static str {
60        match self {
61            Block::Text(_) => "text",
62            Block::Image(_) => "image",
63            Block::Document(_) => "document",
64            Block::Audio(_) => "audio",
65            Block::Video(_) => "video",
66            Block::ToolCall(_) => "tool_call",
67            Block::ToolResult(_) => "tool_result",
68            Block::Reasoning(_) => "reasoning",
69            Block::Refusal(_) => "refusal",
70            Block::Unknown(_) => "unknown",
71            Block::Json(_) => "json",
72        }
73    }
74
75    pub fn extras(&self) -> Option<&Extras> {
76        match self {
77            Block::Text(b) => Some(&b.extras),
78            Block::Image(b) => Some(&b.extras),
79            Block::Document(b) => Some(&b.extras),
80            Block::Audio(b) => Some(&b.extras),
81            Block::Video(b) => Some(&b.extras),
82            Block::ToolCall(b) => Some(&b.extras),
83            Block::ToolResult(b) => Some(&b.extras),
84            Block::Reasoning(b) => Some(&b.extras),
85            Block::Refusal(b) => Some(&b.extras),
86            Block::Json(b) => Some(&b.extras),
87            Block::Unknown(_) => None,
88        }
89    }
90
91    pub fn cache(&self) -> Option<&CacheHint> {
92        match self {
93            Block::Text(b) => b.cache.as_ref(),
94            Block::Image(b) => b.cache.as_ref(),
95            Block::Document(b) => b.cache.as_ref(),
96            Block::Audio(b) => b.cache.as_ref(),
97            Block::Video(b) => b.cache.as_ref(),
98            Block::ToolCall(b) => b.cache.as_ref(),
99            Block::ToolResult(b) => b.cache.as_ref(),
100            Block::Json(b) => b.cache.as_ref(),
101            Block::Reasoning(_) | Block::Refusal(_) | Block::Unknown(_) => None,
102        }
103    }
104}
105
106#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
107#[non_exhaustive]
108pub struct TextBlock {
109    pub text: String,
110    #[serde(default, skip_serializing_if = "Vec::is_empty")]
111    pub citations: Vec<Citation>,
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub cache: Option<CacheHint>,
114    #[serde(default, skip_serializing_if = "Extras::is_empty")]
115    pub extras: Extras,
116}
117
118impl TextBlock {
119    pub fn new(text: impl Into<String>) -> Self {
120        TextBlock {
121            text: text.into(),
122            ..TextBlock::default()
123        }
124    }
125}
126
127/// Structured data, written as the app wrote it.
128#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
129#[non_exhaustive]
130pub struct JsonBlock {
131    pub data: RawJson,
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub cache: Option<CacheHint>,
134    #[serde(default, skip_serializing_if = "Extras::is_empty")]
135    pub extras: Extras,
136}
137
138impl JsonBlock {
139    pub fn new(data: RawJson) -> Self {
140        JsonBlock {
141            data,
142            cache: None,
143            extras: Extras::default(),
144        }
145    }
146}
147
148#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
149#[non_exhaustive]
150pub struct ImageBlock {
151    pub source: Source,
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub cache: Option<CacheHint>,
154    #[serde(default, skip_serializing_if = "Extras::is_empty")]
155    pub extras: Extras,
156}
157
158impl ImageBlock {
159    pub fn new(source: Source) -> Self {
160        ImageBlock {
161            source,
162            cache: None,
163            extras: Extras::default(),
164        }
165    }
166}
167
168#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
169#[non_exhaustive]
170pub struct AudioBlock {
171    pub source: Source,
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub transcript: Option<String>,
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub cache: Option<CacheHint>,
176    #[serde(default, skip_serializing_if = "Extras::is_empty")]
177    pub extras: Extras,
178}
179
180impl AudioBlock {
181    pub fn new(source: Source) -> Self {
182        AudioBlock {
183            source,
184            transcript: None,
185            cache: None,
186            extras: Extras::default(),
187        }
188    }
189}
190
191#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
192#[non_exhaustive]
193pub struct VideoBlock {
194    pub source: Source,
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub cache: Option<CacheHint>,
197    #[serde(default, skip_serializing_if = "Extras::is_empty")]
198    pub extras: Extras,
199}
200
201impl VideoBlock {
202    pub fn new(source: Source) -> Self {
203        VideoBlock {
204            source,
205            cache: None,
206            extras: Extras::default(),
207        }
208    }
209}
210
211#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
212#[non_exhaustive]
213pub struct DocumentBlock {
214    pub source: Source,
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub title: Option<String>,
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub context: Option<String>,
219    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
220    pub citations: bool,
221    #[serde(default, skip_serializing_if = "Option::is_none")]
222    pub cache: Option<CacheHint>,
223    #[serde(default, skip_serializing_if = "Extras::is_empty")]
224    pub extras: Extras,
225}
226
227impl DocumentBlock {
228    pub fn new(source: Source) -> Self {
229        DocumentBlock {
230            source,
231            title: None,
232            context: None,
233            citations: false,
234            cache: None,
235            extras: Extras::default(),
236        }
237    }
238}
239
240#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
241#[non_exhaustive]
242pub struct ToolCallBlock {
243    pub id: String,
244    pub name: String,
245    pub arguments: RawJson,
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub cache: Option<CacheHint>,
248    #[serde(default, skip_serializing_if = "Extras::is_empty")]
249    pub extras: Extras,
250}
251
252impl ToolCallBlock {
253    pub fn new(id: impl Into<String>, name: impl Into<String>, arguments: RawJson) -> Self {
254        ToolCallBlock {
255            id: id.into(),
256            name: name.into(),
257            arguments,
258            cache: None,
259            extras: Extras::default(),
260        }
261    }
262}
263
264#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
265#[non_exhaustive]
266pub struct ToolResultBlock {
267    pub call_id: String,
268    pub content: Vec<Block>,
269    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
270    pub is_error: bool,
271    #[serde(default, skip_serializing_if = "Option::is_none")]
272    pub cache: Option<CacheHint>,
273    #[serde(default, skip_serializing_if = "Extras::is_empty")]
274    pub extras: Extras,
275}
276
277impl ToolResultBlock {
278    pub fn new(call_id: impl Into<String>, content: Vec<Block>) -> Self {
279        ToolResultBlock {
280            call_id: call_id.into(),
281            content,
282            ..ToolResultBlock::default()
283        }
284    }
285}
286
287#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
288#[non_exhaustive]
289pub struct ReasoningBlock {
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub origin: Option<Origin>,
292    #[serde(default, skip_serializing_if = "Vec::is_empty")]
293    pub summary: Vec<String>,
294    #[serde(default, skip_serializing_if = "Vec::is_empty")]
295    pub text: Vec<String>,
296    #[serde(default, skip_serializing_if = "Vec::is_empty")]
297    pub opaque: Vec<Opaque>,
298    #[serde(default, skip_serializing_if = "Extras::is_empty")]
299    pub extras: Extras,
300}
301
302impl ReasoningBlock {
303    pub fn new(origin: impl Into<Origin>) -> Self {
304        ReasoningBlock {
305            origin: Some(origin.into()),
306            ..ReasoningBlock::default()
307        }
308    }
309
310    pub fn replayable_to(&self, dialect: DialectId) -> bool {
311        self.origin.as_ref().is_some_and(|o| o.is(dialect))
312    }
313
314    pub fn opaque_of(&self, kind: OpaqueKind) -> Option<&Opaque> {
315        self.opaque.iter().find(|o| o.kind == kind)
316    }
317}
318
319#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
320#[non_exhaustive]
321pub struct RefusalBlock {
322    pub text: String,
323    #[serde(default, skip_serializing_if = "Extras::is_empty")]
324    pub extras: Extras,
325}
326
327impl RefusalBlock {
328    pub fn new(text: impl Into<String>) -> Self {
329        RefusalBlock {
330            text: text.into(),
331            extras: Extras::default(),
332        }
333    }
334}
335
336#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
337#[non_exhaustive]
338pub struct RawItem {
339    pub origin: Origin,
340    pub raw: RawJson,
341}
342
343impl RawItem {
344    pub fn new(origin: impl Into<Origin>, raw: RawJson) -> Self {
345        RawItem {
346            origin: origin.into(),
347            raw,
348        }
349    }
350}
351
352#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
353#[serde(rename_all = "snake_case")]
354#[non_exhaustive]
355pub enum Source {
356    Url(String),
357    Base64(Base64Source),
358    Text(TextSource),
359    FileId(FileIdSource),
360}
361
362impl Source {
363    /// Media given as base64 text, decoded once. Padding is optional; text that is not standard
364    /// base64 is an `InvalidRequest`.
365    pub fn base64(media_type: impl Into<String>, data: impl AsRef<[u8]>) -> Result<Self, KppError> {
366        Base64Source::from_base64(media_type, data).map(Source::Base64)
367    }
368
369    /// Media given as its bytes. Cloning the source shares them.
370    pub fn bytes(media_type: impl Into<String>, data: impl Into<Bytes>) -> Self {
371        Source::Base64(Base64Source::new(media_type, data))
372    }
373
374    pub fn text(media_type: impl Into<String>, data: impl Into<String>) -> Self {
375        Source::Text(TextSource {
376            media_type: media_type.into(),
377            data: data.into(),
378        })
379    }
380
381    pub fn file_id(origin: impl Into<Origin>, id: impl Into<String>) -> Self {
382        Source::FileId(FileIdSource {
383            origin: origin.into(),
384            id: id.into(),
385        })
386    }
387
388    pub fn media_type(&self) -> Option<&str> {
389        match self {
390            Source::Base64(s) => Some(&s.media_type),
391            Source::Text(s) => Some(&s.media_type),
392            Source::Url(_) | Source::FileId(_) => None,
393        }
394    }
395}
396
397/// Inline media: its bytes, held once and decoded, and their media type.
398///
399/// The bytes are a [`Bytes`] buffer, so cloning a request shares them instead of copying, and a
400/// codec that read them from an upload can slice them out of the request body. KPP's JSON form
401/// writes them as standard base64: `{"base64": {"media_type": "image/png", "data": "iVBOR…"}}`.
402#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
403#[non_exhaustive]
404pub struct Base64Source {
405    pub media_type: String,
406    #[serde(with = "crate::b64")]
407    pub data: Bytes,
408}
409
410impl Base64Source {
411    pub fn new(media_type: impl Into<String>, data: impl Into<Bytes>) -> Self {
412        Base64Source {
413            media_type: media_type.into(),
414            data: data.into(),
415        }
416    }
417
418    /// Decodes base64 text; padding is optional.
419    pub fn from_base64(
420        media_type: impl Into<String>,
421        text: impl AsRef<[u8]>,
422    ) -> Result<Self, KppError> {
423        let data = crate::b64::decode(text.as_ref())
424            .map_err(|_| KppError::invalid_request("The media data is not valid base64."))?;
425        Ok(Base64Source::new(media_type, data))
426    }
427
428    /// The bytes as standard, padded base64, to format or serialize without building the text.
429    pub fn base64(&self) -> Base64Text<'_> {
430        Base64Text(&self.data)
431    }
432
433    /// The bytes as standard, padded base64 text.
434    pub fn to_base64(&self) -> String {
435        let mut out = String::new();
436        self.push_base64(&mut out);
437        out
438    }
439
440    /// Appends the bytes as standard, padded base64 to `out`, such as after a data URL's header.
441    pub fn push_base64(&self, out: &mut String) {
442        crate::b64::push(&self.data, out);
443    }
444
445    /// A `data:` URL of the bytes: `data:<media type>;base64,<data>`.
446    pub fn data_url(&self) -> String {
447        self.data_url_with(&format!("data:{};base64", self.media_type))
448    }
449
450    /// A `data:` URL of the bytes after `header`, the part before the comma as an app wrote it.
451    pub fn data_url_with(&self, header: &str) -> String {
452        let mut out = String::with_capacity(header.len() + 1 + self.base64().len());
453        out.push_str(header);
454        out.push(',');
455        self.push_base64(&mut out);
456        out
457    }
458}
459
460impl std::fmt::Debug for Base64Source {
461    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
462        f.debug_struct("Base64Source")
463            .field("media_type", &self.media_type)
464            .field("data", &format_args!("{} bytes", self.data.len()))
465            .finish()
466    }
467}
468
469#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
470#[non_exhaustive]
471pub struct TextSource {
472    pub media_type: String,
473    pub data: String,
474}
475
476#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
477#[non_exhaustive]
478pub struct FileIdSource {
479    pub origin: Origin,
480    pub id: String,
481}
482
483#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
484#[non_exhaustive]
485pub struct Opaque {
486    pub origin: Origin,
487    pub kind: OpaqueKind,
488    pub data: String,
489}
490
491impl Opaque {
492    pub fn new(origin: impl Into<Origin>, kind: OpaqueKind, data: impl Into<String>) -> Self {
493        Opaque {
494            origin: origin.into(),
495            kind,
496            data: data.into(),
497        }
498    }
499
500    pub fn replayable_to(&self, dialect: DialectId) -> bool {
501        self.origin.is(dialect)
502    }
503}
504
505#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
506#[non_exhaustive]
507pub enum OpaqueKind {
508    #[serde(rename = "anthropic_thinking_signature")]
509    AnthropicThinkingSignature,
510    #[serde(rename = "anthropic_redacted_thinking")]
511    AnthropicRedactedThinking,
512    #[serde(rename = "openai_encrypted_reasoning")]
513    OpenAiEncryptedReasoning,
514    #[serde(rename = "openai_reasoning_item_id")]
515    OpenAiReasoningItemId,
516    #[serde(rename = "gemini_thought_signature")]
517    GeminiThoughtSignature,
518    #[serde(rename = "bedrock_reasoning_signature")]
519    BedrockReasoningSignature,
520    #[serde(rename = "bedrock_redacted_reasoning")]
521    BedrockRedactedReasoning,
522}
523
524#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
525#[non_exhaustive]
526pub struct CacheHint {
527    #[serde(default, skip_serializing_if = "Option::is_none")]
528    pub ttl: Option<CacheTtl>,
529    #[serde(default, skip_serializing_if = "Extras::is_empty")]
530    pub extras: Extras,
531}
532
533impl CacheHint {
534    pub fn new(ttl: Option<CacheTtl>) -> Self {
535        CacheHint {
536            ttl,
537            extras: Extras::default(),
538        }
539    }
540}
541
542#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
543#[serde(rename_all = "snake_case")]
544#[non_exhaustive]
545pub enum CacheTtl {
546    FiveMinutes,
547    OneHour,
548    Other(String),
549}
550
551#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
552#[non_exhaustive]
553pub struct Citation {
554    pub origin: Origin,
555    pub raw: RawJson,
556}
557
558impl Citation {
559    pub fn new(origin: impl Into<Origin>, raw: RawJson) -> Self {
560        Citation {
561            origin: origin.into(),
562            raw,
563        }
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570
571    #[test]
572    fn stable_json_form_round_trips() {
573        let mut reasoning = ReasoningBlock::new(DialectId::AnthropicMessages);
574        reasoning.text.push("thinking".into());
575        reasoning.opaque.push(Opaque::new(
576            DialectId::AnthropicMessages,
577            OpaqueKind::AnthropicThinkingSignature,
578            "sig",
579        ));
580        let blocks = vec![
581            Block::text("hi"),
582            Block::tool_call(
583                "toolu_01",
584                "get_weather",
585                RawJson::from_string("{\"city\": \"Paris\"}".into()).unwrap(),
586            ),
587            Block::tool_result("toolu_01", vec![Block::text("sunny")], false),
588            Block::Reasoning(reasoning),
589            Block::Unknown(RawItem::new(
590                DialectId::AnthropicMessages,
591                RawJson::from_string("{\"type\":\"server_tool_use\"}".into()).unwrap(),
592            )),
593            Block::image(Source::base64("image/png", "AAAA").unwrap()),
594            Block::audio(Source::base64("audio/wav", "UklGRg==").unwrap()),
595            Block::video(Source::Url(
596                "https://www.youtube.com/watch?v=9hE5-98ZeCg".into(),
597            )),
598        ];
599        let json = serde_json::to_string(&blocks).unwrap();
600        let back: Vec<Block> = serde_json::from_str(&json).unwrap();
601        assert_eq!(back, blocks);
602        assert!(
603            json.contains("{\"city\": \"Paris\"}"),
604            "raw bytes kept: {json}"
605        );
606        assert!(json.starts_with(r#"[{"text":{"text":"hi"}}"#), "{json}");
607    }
608
609    #[test]
610    fn reasoning_and_opaque_are_bound_to_origin() {
611        let o = Opaque::new(
612            DialectId::OpenAiResponses,
613            OpaqueKind::OpenAiEncryptedReasoning,
614            "gAAAA",
615        );
616        assert!(o.replayable_to(DialectId::OpenAiResponses));
617        assert!(!o.replayable_to(DialectId::OpenAiChat));
618        let mut r = ReasoningBlock::new(DialectId::OpenAiResponses);
619        r.opaque.push(o);
620        assert!(r.replayable_to(DialectId::OpenAiResponses));
621        assert!(!r.replayable_to(DialectId::AnthropicMessages));
622        assert!(r.opaque_of(OpaqueKind::OpenAiEncryptedReasoning).is_some());
623        assert!(!ReasoningBlock::default().replayable_to(DialectId::OpenAiChat));
624    }
625
626    #[test]
627    fn opaque_kinds_spell_providers_like_dialect_ids() {
628        let kinds = [
629            (
630                OpaqueKind::AnthropicThinkingSignature,
631                "anthropic_thinking_signature",
632            ),
633            (
634                OpaqueKind::AnthropicRedactedThinking,
635                "anthropic_redacted_thinking",
636            ),
637            (
638                OpaqueKind::OpenAiEncryptedReasoning,
639                "openai_encrypted_reasoning",
640            ),
641            (
642                OpaqueKind::OpenAiReasoningItemId,
643                "openai_reasoning_item_id",
644            ),
645            (
646                OpaqueKind::GeminiThoughtSignature,
647                "gemini_thought_signature",
648            ),
649            (
650                OpaqueKind::BedrockReasoningSignature,
651                "bedrock_reasoning_signature",
652            ),
653            (
654                OpaqueKind::BedrockRedactedReasoning,
655                "bedrock_redacted_reasoning",
656            ),
657        ];
658        for (kind, name) in kinds {
659            let json = serde_json::to_string(&kind).unwrap();
660            assert_eq!(json, format!("\"{name}\""));
661            assert_eq!(serde_json::from_str::<OpaqueKind>(&json).unwrap(), kind);
662        }
663        assert!(serde_json::from_str::<OpaqueKind>("\"open_ai_encrypted_reasoning\"").is_err());
664    }
665}