Skip to main content

base/interface/
model_interceptor.rs

1//! `ModelInterceptor` — the request on its way out, and the message on its
2//! way back.
3//!
4//! Two moments matter for anyone who wants to shape what the engine says to a
5//! provider and what it does with the answer: just before a request is sent,
6//! when the messages, tools and parameters are assembled and nothing has left
7//! the process yet; and just after a complete message has been assembled from
8//! a stream, when it is whole enough to reason about.
9//!
10//! # There is deliberately no per-chunk hook
11//!
12//! The obvious third moment — every streamed delta — is the one this does not
13//! offer. A turn produces thousands of chunks, so a hook there is called
14//! thousands of times, and the cost is invisible to whoever writes it: their
15//! function looks cheap, the streaming looks broken. Worse, a hook that can
16//! rewrite chunks can produce a message that never existed as a coherent
17//! whole, which nothing downstream is built to handle.
18//!
19//! So the contract offers complete things: the complete request, the complete
20//! message. Both are called once per model call, which
21//! [`does_not_run_per_chunk`](self) has a test for. If a deployment genuinely
22//! needs to transform a stream as it arrives, the answer is a declarative rule
23//! the engine executes natively — not a callback in the chunk loop.
24
25use crate::interface::model::{ModelMessage, StreamParams, ToolDef};
26use crate::prompt::PromptBlock;
27
28/// A model request, assembled and not yet sent.
29#[derive(Debug, Clone)]
30pub struct ModelRequestView {
31    pub prompt_blocks: Vec<PromptBlock>,
32    pub tool_defs: Vec<ToolDef>,
33    pub messages: Vec<ModelMessage>,
34    pub params: StreamParams,
35}
36
37/// Shapes what goes to the provider and what comes back.
38///
39/// Both methods default to doing nothing, so an implementation that cares
40/// about one moment does not have to acknowledge the other.
41pub trait ModelInterceptor: Send + Sync {
42    /// Called once per model call, immediately before the request is sent.
43    ///
44    /// Everything is mutable: messages, tools, sampling parameters, prompt
45    /// blocks. This is the last point at which the engine's idea of the
46    /// request and the provider's can still be made to differ.
47    fn on_request(&self, _request: &mut ModelRequestView) {}
48
49    /// Called once per complete message the model produced, after the stream
50    /// that carried it has finished and before the session records it.
51    ///
52    /// Whole messages only — see the module docs on why there is no
53    /// per-chunk equivalent.
54    fn on_message(&self, _message: &mut ModelMessage) {}
55}
56
57/// Run every interceptor over a request.
58pub fn intercept_request(
59    interceptors: &[std::sync::Arc<dyn ModelInterceptor>],
60    request: &mut ModelRequestView,
61) {
62    for i in interceptors {
63        i.on_request(request);
64    }
65}
66
67/// Run every interceptor over a completed message.
68pub fn intercept_message(
69    interceptors: &[std::sync::Arc<dyn ModelInterceptor>],
70    message: &mut ModelMessage,
71) {
72    for i in interceptors {
73        i.on_message(message);
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use crate::interface::model::{MessageRole, ModelContentBlock};
81    use std::sync::atomic::{AtomicUsize, Ordering};
82    use std::sync::Arc;
83
84    #[derive(Default)]
85    struct Counting {
86        requests: AtomicUsize,
87        messages: AtomicUsize,
88    }
89
90    impl ModelInterceptor for Counting {
91        fn on_request(&self, request: &mut ModelRequestView) {
92            self.requests.fetch_add(1, Ordering::SeqCst);
93            request.params.max_tokens = 42;
94        }
95        fn on_message(&self, message: &mut ModelMessage) {
96            self.messages.fetch_add(1, Ordering::SeqCst);
97            message.content.push(ModelContentBlock::Text {
98                text: "[seen]".into(),
99            });
100        }
101    }
102
103    fn request() -> ModelRequestView {
104        ModelRequestView {
105            prompt_blocks: Vec::new(),
106            tool_defs: Vec::new(),
107            messages: Vec::new(),
108            params: StreamParams {
109                model: "test-model".into(),
110                max_tokens: 1024,
111                thinking_mode: crate::interface::model::ThinkingMode::Off,
112                effort: None,
113                cache_edits: Vec::new(),
114                origin: None,
115                input_map: None,
116                provider_search: None,
117                usage_tap: Default::default(),
118            },
119        }
120    }
121
122    #[test]
123    fn a_request_can_be_reshaped_before_it_leaves() {
124        let counting = Arc::new(Counting::default());
125        let chain: Vec<Arc<dyn ModelInterceptor>> = vec![counting.clone()];
126        let mut req = request();
127        intercept_request(&chain, &mut req);
128        assert_eq!(req.params.max_tokens, 42);
129        assert_eq!(counting.requests.load(Ordering::SeqCst), 1);
130    }
131
132    #[test]
133    fn a_completed_message_can_be_reshaped_before_it_is_recorded() {
134        let counting = Arc::new(Counting::default());
135        let chain: Vec<Arc<dyn ModelInterceptor>> = vec![counting.clone()];
136        let mut message = ModelMessage {
137            role: MessageRole::Assistant,
138            content: vec![ModelContentBlock::Text { text: "hi".into() }],
139        };
140        intercept_message(&chain, &mut message);
141        assert_eq!(message.content.len(), 2);
142        assert_eq!(counting.messages.load(Ordering::SeqCst), 1);
143    }
144
145    #[test]
146    fn nothing_registered_changes_nothing() {
147        let mut req = request();
148        let before = req.clone();
149        intercept_request(&[], &mut req);
150        assert_eq!(req.params.max_tokens, before.params.max_tokens);
151        assert_eq!(req.messages.len(), before.messages.len());
152    }
153}