Skip to main content

kaeso_kpp/
request.rs

1use serde::{Deserialize, Serialize};
2
3use crate::audio::{SpeechRequest, TranscriptionRequest};
4use crate::block::{Block, CacheHint, RawItem};
5use crate::decision::DecideRequest;
6use crate::extras::Extras;
7use crate::image::ImageRequest;
8use crate::raw::RawJson;
9use crate::rerank::RerankRequest;
10use crate::video::VideoRequest;
11
12#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
13#[serde(rename_all = "snake_case")]
14#[non_exhaustive]
15pub enum Request {
16    Generate(GenerateRequest),
17    CountTokens(GenerateRequest),
18    Embed(EmbedRequest),
19    Image(ImageRequest),
20    Speech(SpeechRequest),
21    Transcription(TranscriptionRequest),
22    Video(VideoRequest),
23    /// Typed questions answered with probabilities.
24    Decide(DecideRequest),
25    /// Documents ordered by how well each answers a query.
26    Rerank(RerankRequest),
27}
28
29impl Request {
30    pub fn kind(&self) -> RequestKind {
31        match self {
32            Request::Generate(_) => RequestKind::Generate,
33            Request::CountTokens(_) => RequestKind::CountTokens,
34            Request::Embed(_) => RequestKind::Embed,
35            Request::Image(_) => RequestKind::Image,
36            Request::Speech(_) => RequestKind::Speech,
37            Request::Transcription(_) => RequestKind::Transcription,
38            Request::Video(_) => RequestKind::Video,
39            Request::Decide(_) => RequestKind::Decide,
40            Request::Rerank(_) => RequestKind::Rerank,
41        }
42    }
43
44    pub fn model(&self) -> &str {
45        match self {
46            Request::Generate(r) | Request::CountTokens(r) => &r.model,
47            Request::Embed(r) => &r.model,
48            Request::Image(r) => &r.model,
49            Request::Speech(r) => &r.model,
50            Request::Transcription(r) => &r.model,
51            Request::Video(r) => &r.model,
52            Request::Decide(r) => &r.model,
53            Request::Rerank(r) => &r.model,
54        }
55    }
56
57    pub fn stream_mode(&self) -> StreamMode {
58        match self {
59            Request::Generate(r) => r.stream,
60            Request::Image(r) => r.stream,
61            Request::Speech(r) => r.stream,
62            Request::Transcription(r) => r.stream,
63            Request::CountTokens(_)
64            | Request::Embed(_)
65            | Request::Video(_)
66            | Request::Decide(_)
67            | Request::Rerank(_) => StreamMode::Off,
68        }
69    }
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
73#[serde(rename_all = "snake_case")]
74#[non_exhaustive]
75pub enum RequestKind {
76    Generate,
77    CountTokens,
78    Embed,
79    Image,
80    Speech,
81    Transcription,
82    Video,
83    Decide,
84    Rerank,
85}
86
87#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
88#[non_exhaustive]
89pub struct GenerateRequest {
90    pub model: String,
91    #[serde(default, skip_serializing_if = "Vec::is_empty")]
92    pub system: Vec<Block>,
93    #[serde(default)]
94    pub messages: Vec<Message>,
95    #[serde(default, skip_serializing_if = "Vec::is_empty")]
96    pub tools: Vec<ToolDef>,
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub tool_choice: Option<ToolChoice>,
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub parallel_tool_calls: Option<bool>,
101    #[serde(default, skip_serializing_if = "OutputSpec::is_text")]
102    pub output: OutputSpec,
103    #[serde(default, skip_serializing_if = "Vec::is_empty")]
104    pub output_modalities: Vec<Modality>,
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub audio_output: Option<AudioOutput>,
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub reasoning: Option<ReasoningConfig>,
109    #[serde(default, skip_serializing_if = "Sampling::is_empty")]
110    pub sampling: Sampling,
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub user: Option<String>,
113    #[serde(default, skip_serializing_if = "StreamMode::is_off")]
114    pub stream: StreamMode,
115    #[serde(default, skip_serializing_if = "Extras::is_empty")]
116    pub extras: Extras,
117}
118
119impl GenerateRequest {
120    pub fn new(model: impl Into<String>) -> Self {
121        GenerateRequest {
122            model: model.into(),
123            ..GenerateRequest::default()
124        }
125    }
126
127    #[must_use]
128    pub fn with_message(mut self, message: Message) -> Self {
129        self.messages.push(message);
130        self
131    }
132
133    #[must_use]
134    pub fn with_system(mut self, text: impl Into<String>) -> Self {
135        self.system = vec![Block::text(text)];
136        self
137    }
138
139    #[must_use]
140    pub fn with_tool(mut self, tool: ToolDef) -> Self {
141        self.tools.push(tool);
142        self
143    }
144
145    #[must_use]
146    pub fn with_stream(mut self, stream: StreamMode) -> Self {
147        self.stream = stream;
148        self
149    }
150
151    pub fn all_blocks(&self) -> impl Iterator<Item = &Block> {
152        let mut stack: Vec<&Block> = Vec::new();
153        for m in self.messages.iter().rev() {
154            stack.extend(m.blocks.iter().rev());
155        }
156        stack.extend(self.system.iter().rev());
157        std::iter::from_fn(move || {
158            let block = stack.pop()?;
159            if let Block::ToolResult(result) = block {
160                stack.extend(result.content.iter().rev());
161            }
162            Some(block)
163        })
164    }
165}
166
167#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
168#[non_exhaustive]
169pub struct Message {
170    pub role: Role,
171    pub blocks: Vec<Block>,
172    #[serde(default, skip_serializing_if = "Extras::is_empty")]
173    pub extras: Extras,
174}
175
176impl Message {
177    pub fn new(role: Role, blocks: Vec<Block>) -> Self {
178        Message {
179            role,
180            blocks,
181            extras: Extras::default(),
182        }
183    }
184
185    pub fn user(text: impl Into<String>) -> Self {
186        Message::new(Role::User, vec![Block::text(text)])
187    }
188
189    pub fn assistant(text: impl Into<String>) -> Self {
190        Message::new(Role::Assistant, vec![Block::text(text)])
191    }
192}
193
194#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
195#[serde(rename_all = "snake_case")]
196#[non_exhaustive]
197pub enum Role {
198    User,
199    Assistant,
200    System,
201}
202
203impl Role {
204    pub fn as_str(self) -> &'static str {
205        match self {
206            Role::User => "user",
207            Role::Assistant => "assistant",
208            Role::System => "system",
209        }
210    }
211}
212
213#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
214#[serde(rename_all = "snake_case")]
215#[non_exhaustive]
216pub enum ToolDef {
217    Function(FunctionTool),
218    Unknown(RawItem),
219}
220
221#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
222#[non_exhaustive]
223pub struct FunctionTool {
224    pub name: String,
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub description: Option<String>,
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub parameters: Option<RawJson>,
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub strict: Option<bool>,
231    #[serde(default, skip_serializing_if = "Option::is_none")]
232    pub cache: Option<CacheHint>,
233    #[serde(default, skip_serializing_if = "Extras::is_empty")]
234    pub extras: Extras,
235}
236
237impl FunctionTool {
238    pub fn new(name: impl Into<String>, parameters: Option<RawJson>) -> Self {
239        FunctionTool {
240            name: name.into(),
241            description: None,
242            parameters,
243            strict: None,
244            cache: None,
245            extras: Extras::default(),
246        }
247    }
248}
249
250#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
251#[serde(rename_all = "snake_case")]
252#[non_exhaustive]
253pub enum ToolChoice {
254    Auto,
255    None,
256    Required,
257    Tool(String),
258    Unknown(RawItem),
259}
260
261#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
262#[serde(rename_all = "snake_case")]
263#[non_exhaustive]
264pub enum OutputSpec {
265    #[default]
266    Text,
267    JsonObject,
268    JsonSchema(JsonSchemaSpec),
269}
270
271impl OutputSpec {
272    pub fn is_text(&self) -> bool {
273        matches!(self, OutputSpec::Text)
274    }
275}
276
277#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
278#[serde(rename_all = "snake_case")]
279#[non_exhaustive]
280pub enum Modality {
281    Text,
282    Image,
283    Audio,
284    Other(String),
285}
286
287impl Modality {
288    pub fn from_wire(s: &str) -> Self {
289        match s {
290            "text" => Modality::Text,
291            "image" => Modality::Image,
292            "audio" => Modality::Audio,
293            other => Modality::Other(other.to_owned()),
294        }
295    }
296
297    pub fn as_wire(&self) -> &str {
298        match self {
299            Modality::Text => "text",
300            Modality::Image => "image",
301            Modality::Audio => "audio",
302            Modality::Other(s) => s,
303        }
304    }
305}
306
307#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
308#[non_exhaustive]
309pub struct AudioOutput {
310    #[serde(default, skip_serializing_if = "Option::is_none")]
311    pub voice: Option<String>,
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub format: Option<AudioFormat>,
314    #[serde(default, skip_serializing_if = "Extras::is_empty")]
315    pub extras: Extras,
316}
317
318impl AudioOutput {
319    pub fn new(voice: Option<String>, format: Option<AudioFormat>) -> Self {
320        AudioOutput {
321            voice,
322            format,
323            extras: Extras::default(),
324        }
325    }
326}
327
328#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
329#[serde(rename_all = "snake_case")]
330#[non_exhaustive]
331pub enum AudioFormat {
332    Wav,
333    Mp3,
334    Flac,
335    Opus,
336    Aac,
337    Pcm16,
338    Other(String),
339}
340
341impl AudioFormat {
342    pub fn from_wire(s: &str) -> Self {
343        match s {
344            "wav" => AudioFormat::Wav,
345            "mp3" => AudioFormat::Mp3,
346            "flac" => AudioFormat::Flac,
347            "opus" => AudioFormat::Opus,
348            "aac" => AudioFormat::Aac,
349            "pcm16" => AudioFormat::Pcm16,
350            other => AudioFormat::Other(other.to_owned()),
351        }
352    }
353
354    pub fn as_wire(&self) -> &str {
355        match self {
356            AudioFormat::Wav => "wav",
357            AudioFormat::Mp3 => "mp3",
358            AudioFormat::Flac => "flac",
359            AudioFormat::Opus => "opus",
360            AudioFormat::Aac => "aac",
361            AudioFormat::Pcm16 => "pcm16",
362            AudioFormat::Other(s) => s,
363        }
364    }
365
366    pub fn media_type(&self) -> Option<&'static str> {
367        match self {
368            AudioFormat::Wav => Some("audio/wav"),
369            AudioFormat::Mp3 => Some("audio/mpeg"),
370            AudioFormat::Flac => Some("audio/flac"),
371            AudioFormat::Opus => Some("audio/opus"),
372            AudioFormat::Aac => Some("audio/aac"),
373            AudioFormat::Pcm16 => Some(PCM16_MEDIA_TYPE),
374            AudioFormat::Other(_) => None,
375        }
376    }
377}
378
379pub const PCM16_MEDIA_TYPE: &str = "audio/l16; rate=24000; channels=1";
380
381#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
382#[non_exhaustive]
383pub struct JsonSchemaSpec {
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub name: Option<String>,
386    #[serde(default, skip_serializing_if = "Option::is_none")]
387    pub description: Option<String>,
388    pub schema: RawJson,
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub strict: Option<bool>,
391    #[serde(default, skip_serializing_if = "Extras::is_empty")]
392    pub extras: Extras,
393}
394
395impl JsonSchemaSpec {
396    pub fn new(schema: RawJson) -> Self {
397        JsonSchemaSpec {
398            name: None,
399            description: None,
400            schema,
401            strict: None,
402            extras: Extras::default(),
403        }
404    }
405}
406
407#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
408#[non_exhaustive]
409pub struct ReasoningConfig {
410    #[serde(default, skip_serializing_if = "Option::is_none")]
411    pub mode: Option<ReasoningMode>,
412    #[serde(default, skip_serializing_if = "Option::is_none")]
413    pub effort: Option<ReasoningEffort>,
414    #[serde(default, skip_serializing_if = "Option::is_none")]
415    pub budget_tokens: Option<u32>,
416    #[serde(default, skip_serializing_if = "Option::is_none")]
417    pub summary: Option<ReasoningSummary>,
418    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
419    pub include_encrypted: bool,
420    /// Hide reasoning from the reply returned to the app while still letting the model reason.
421    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
422    pub exclude: bool,
423    #[serde(default, skip_serializing_if = "Extras::is_empty")]
424    pub extras: Extras,
425}
426
427#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
428#[serde(rename_all = "snake_case")]
429#[non_exhaustive]
430pub enum ReasoningMode {
431    Enabled,
432    Disabled,
433    Adaptive,
434    Other(String),
435}
436
437impl ReasoningMode {
438    pub fn from_wire(s: &str) -> Self {
439        match s {
440            "enabled" => ReasoningMode::Enabled,
441            "disabled" => ReasoningMode::Disabled,
442            "adaptive" => ReasoningMode::Adaptive,
443            other => ReasoningMode::Other(other.to_owned()),
444        }
445    }
446
447    pub fn as_wire(&self) -> &str {
448        match self {
449            ReasoningMode::Enabled => "enabled",
450            ReasoningMode::Disabled => "disabled",
451            ReasoningMode::Adaptive => "adaptive",
452            ReasoningMode::Other(s) => s,
453        }
454    }
455}
456
457#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
458#[serde(rename_all = "snake_case")]
459#[non_exhaustive]
460pub enum ReasoningEffort {
461    None,
462    Minimal,
463    Low,
464    Medium,
465    High,
466    #[serde(rename = "xhigh")]
467    XHigh,
468    Max,
469    Other(String),
470}
471
472impl ReasoningEffort {
473    pub fn from_wire(s: &str) -> Self {
474        match s {
475            "none" => ReasoningEffort::None,
476            "minimal" => ReasoningEffort::Minimal,
477            "low" => ReasoningEffort::Low,
478            "medium" => ReasoningEffort::Medium,
479            "high" => ReasoningEffort::High,
480            "xhigh" => ReasoningEffort::XHigh,
481            "max" => ReasoningEffort::Max,
482            other => ReasoningEffort::Other(other.to_owned()),
483        }
484    }
485
486    pub fn as_wire(&self) -> &str {
487        match self {
488            ReasoningEffort::None => "none",
489            ReasoningEffort::Minimal => "minimal",
490            ReasoningEffort::Low => "low",
491            ReasoningEffort::Medium => "medium",
492            ReasoningEffort::High => "high",
493            ReasoningEffort::XHigh => "xhigh",
494            ReasoningEffort::Max => "max",
495            ReasoningEffort::Other(s) => s,
496        }
497    }
498}
499
500#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
501#[serde(rename_all = "snake_case")]
502#[non_exhaustive]
503pub enum ReasoningSummary {
504    Auto,
505    Concise,
506    Detailed,
507    Other(String),
508}
509
510impl ReasoningSummary {
511    pub fn from_wire(s: &str) -> Self {
512        match s {
513            "auto" => ReasoningSummary::Auto,
514            "concise" => ReasoningSummary::Concise,
515            "detailed" => ReasoningSummary::Detailed,
516            other => ReasoningSummary::Other(other.to_owned()),
517        }
518    }
519
520    pub fn as_wire(&self) -> &str {
521        match self {
522            ReasoningSummary::Auto => "auto",
523            ReasoningSummary::Concise => "concise",
524            ReasoningSummary::Detailed => "detailed",
525            ReasoningSummary::Other(s) => s,
526        }
527    }
528}
529
530#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
531#[non_exhaustive]
532pub struct Sampling {
533    #[serde(default, skip_serializing_if = "Option::is_none")]
534    pub max_output_tokens: Option<u32>,
535    #[serde(default, skip_serializing_if = "Option::is_none")]
536    pub temperature: Option<f64>,
537    #[serde(default, skip_serializing_if = "Option::is_none")]
538    pub top_p: Option<f64>,
539    #[serde(default, skip_serializing_if = "Option::is_none")]
540    pub top_k: Option<u32>,
541    #[serde(default, skip_serializing_if = "Vec::is_empty")]
542    pub stop: Vec<String>,
543    #[serde(default, skip_serializing_if = "Option::is_none")]
544    pub seed: Option<i64>,
545    #[serde(default, skip_serializing_if = "Option::is_none")]
546    pub frequency_penalty: Option<f64>,
547    #[serde(default, skip_serializing_if = "Option::is_none")]
548    pub presence_penalty: Option<f64>,
549}
550
551impl Sampling {
552    pub fn is_empty(&self) -> bool {
553        *self == Sampling::default()
554    }
555}
556
557#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
558#[serde(rename_all = "snake_case")]
559#[non_exhaustive]
560pub enum StreamMode {
561    #[default]
562    Off,
563    #[non_exhaustive]
564    On { include_usage: bool },
565}
566
567impl StreamMode {
568    pub const fn on(include_usage: bool) -> Self {
569        StreamMode::On { include_usage }
570    }
571
572    pub fn is_off(&self) -> bool {
573        matches!(self, StreamMode::Off)
574    }
575}
576
577#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
578#[non_exhaustive]
579pub struct EmbedRequest {
580    pub model: String,
581    pub input: Vec<EmbedInput>,
582    #[serde(default, skip_serializing_if = "Option::is_none")]
583    pub dimensions: Option<u32>,
584    #[serde(default)]
585    pub encoding: EmbedEncoding,
586    #[serde(default, skip_serializing_if = "Option::is_none")]
587    pub user: Option<String>,
588    #[serde(default, skip_serializing_if = "Extras::is_empty")]
589    pub extras: Extras,
590}
591
592impl EmbedRequest {
593    pub fn new(model: impl Into<String>, input: Vec<EmbedInput>) -> Self {
594        EmbedRequest {
595            model: model.into(),
596            input,
597            ..EmbedRequest::default()
598        }
599    }
600}
601
602#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
603#[serde(rename_all = "snake_case")]
604#[non_exhaustive]
605pub enum EmbedInput {
606    Text(String),
607    Tokens(Vec<u32>),
608}
609
610#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
611#[serde(rename_all = "snake_case")]
612#[non_exhaustive]
613pub enum EmbedEncoding {
614    #[default]
615    Float,
616    Base64,
617}
618
619#[cfg(test)]
620mod tests {
621    use super::*;
622
623    #[test]
624    fn all_blocks_walks_tool_results_in_order() {
625        let req = GenerateRequest::new("m")
626            .with_system("sys")
627            .with_message(Message::user("a"))
628            .with_message(Message::new(
629                Role::User,
630                vec![Block::tool_result(
631                    "c1",
632                    vec![Block::text("r1"), Block::text("r2")],
633                    false,
634                )],
635            ));
636        let kinds: Vec<_> = req
637            .all_blocks()
638            .map(|b| match b {
639                Block::Text(t) => t.text.clone(),
640                other => other.kind().to_owned(),
641            })
642            .collect();
643        assert_eq!(kinds, ["sys", "a", "tool_result", "r1", "r2"]);
644    }
645
646    #[test]
647    fn minimal_request_has_a_small_stable_form() {
648        let req = GenerateRequest::new("m").with_message(Message::user("hi"));
649        let json = serde_json::to_string(&req).unwrap();
650        assert_eq!(
651            json,
652            r#"{"model":"m","messages":[{"role":"user","blocks":[{"text":{"text":"hi"}}]}]}"#
653        );
654        let back: GenerateRequest = serde_json::from_str(&json).unwrap();
655        assert_eq!(back, req);
656    }
657
658    #[test]
659    fn effort_and_summary_round_trip_wire_values() {
660        for s in [
661            "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra",
662        ] {
663            assert_eq!(ReasoningEffort::from_wire(s).as_wire(), s);
664        }
665        for s in ["auto", "concise", "detailed", "brief"] {
666            assert_eq!(ReasoningSummary::from_wire(s).as_wire(), s);
667        }
668        for s in ["enabled", "disabled", "adaptive", "between_tools"] {
669            assert_eq!(ReasoningMode::from_wire(s).as_wire(), s);
670        }
671        assert_eq!(
672            ReasoningMode::from_wire("between_tools"),
673            ReasoningMode::Other("between_tools".into())
674        );
675    }
676
677    #[test]
678    fn modalities_and_audio_formats_round_trip_wire_values() {
679        for s in ["text", "image", "audio", "video"] {
680            assert_eq!(Modality::from_wire(s).as_wire(), s);
681        }
682        for s in ["wav", "mp3", "flac", "opus", "aac", "pcm16", "alaw"] {
683            assert_eq!(AudioFormat::from_wire(s).as_wire(), s);
684        }
685        assert_eq!(AudioFormat::Pcm16.media_type(), Some(PCM16_MEDIA_TYPE));
686        assert_eq!(AudioFormat::Other("alaw".into()).media_type(), None);
687        let mut req = GenerateRequest::new("m");
688        req.output_modalities = vec![Modality::Text, Modality::Audio];
689        req.audio_output = Some(AudioOutput::new(
690            Some("marin".into()),
691            Some(AudioFormat::Wav),
692        ));
693        let json = serde_json::to_string(&req).unwrap();
694        assert!(
695            json.contains(r#""output_modalities":["text","audio"],"audio_output":{"voice":"marin","format":"wav"}"#),
696            "{json}"
697        );
698        assert_eq!(serde_json::from_str::<GenerateRequest>(&json).unwrap(), req);
699    }
700
701    #[test]
702    fn stream_mode_constructor_keeps_the_wire_form() {
703        let mode = StreamMode::on(true);
704        assert_eq!(
705            mode,
706            StreamMode::On {
707                include_usage: true
708            }
709        );
710        assert_eq!(
711            serde_json::to_string(&mode).unwrap(),
712            r#"{"on":{"include_usage":true}}"#
713        );
714        assert!(!mode.is_off());
715    }
716}