Skip to main content

merry_llm/
event.rs

1//! Normalized model event protocol.
2
3use crate::{ModelOutputProgress, ModelResponse, ModelToolCall};
4use schemars::JsonSchema;
5use serde::{Deserialize, Deserializer, Serialize};
6
7/// Normalized event emitted by model providers.
8#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
9#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
10pub enum ModelEvent {
11    /// Provider accepted the request and began producing output.
12    Started,
13    /// Receive-side accounting without retaining text. None clears a failed attempt's sample.
14    OutputProgress {
15        progress: Option<ModelOutputProgress>,
16    },
17    /// Incremental text output.
18    OutputTextDelta {
19        /// Delta text.
20        delta: String,
21    },
22    /// Incremental provider reasoning text. A summary is used only when raw reasoning is absent.
23    ReasoningTextDelta {
24        /// Delta text.
25        delta: String,
26    },
27    /// Model requested a tool call.
28    ToolCallRequested {
29        /// Requested tool call.
30        call: ModelToolCall,
31    },
32    /// Stream completed. No events may be emitted after this event.
33    Completed {
34        /// Aggregated model response.
35        response: ModelResponse,
36    },
37}
38
39#[derive(Deserialize)]
40#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
41enum ModelEventWire {
42    Started {},
43    OutputProgress {
44        progress: Option<ModelOutputProgress>,
45    },
46    OutputTextDelta {
47        delta: String,
48    },
49    ReasoningTextDelta {
50        delta: String,
51    },
52    ToolCallRequested {
53        call: ModelToolCall,
54    },
55    Completed {
56        response: ModelResponse,
57    },
58}
59
60impl<'de> Deserialize<'de> for ModelEvent {
61    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
62    where
63        D: Deserializer<'de>,
64    {
65        let wire = ModelEventWire::deserialize(deserializer)?;
66        Ok(match wire {
67            ModelEventWire::Started {} => Self::Started,
68            ModelEventWire::OutputProgress { progress } => Self::OutputProgress { progress },
69            ModelEventWire::OutputTextDelta { delta } => Self::OutputTextDelta { delta },
70            ModelEventWire::ReasoningTextDelta { delta } => Self::ReasoningTextDelta { delta },
71            ModelEventWire::ToolCallRequested { call } => Self::ToolCallRequested { call },
72            ModelEventWire::Completed { response } => Self::Completed { response },
73        })
74    }
75}