cognis-llm 0.3.0

LLM client and provider abstractions for Cognis: Client, LLMProvider trait, chat options, tool definitions, and streaming. Provider implementations (OpenAI, Anthropic, Google, Ollama, Azure) are feature-gated.
Documentation
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
//! Interceptor — chat-shape before/after/error hooks for any
//! [`LLMProvider`].
//!
//! Differences from the generic `cognis_core::Middleware`:
//! - Operates on chat-specific types ([`ChatOptions`], [`ChatResponse`],
//!   [`Vec<Message>`]) rather than `(I, O)`.
//! - Hooks fire on every provider entry-point (`chat_completion`,
//!   `chat_completion_stream`, `chat_completion_with_tools`) — no need
//!   to write three sets of generic hooks.
//!
//! Customization:
//! - Implement [`ChatInterceptor`] for full control.
//! - Use [`FnChatInterceptor`] to assemble from individual closures.

use std::sync::Arc;

use async_trait::async_trait;

use cognis_core::{CognisError, Result, RunnableStream};

use crate::chat::{ChatOptions, ChatResponse, HealthStatus, StreamChunk};
use crate::provider::{LLMProvider, Provider};
use crate::tools::ToolDefinition;
use crate::Message;

/// Chat-shape hooks. All have default no-op impls.
#[async_trait]
pub trait ChatInterceptor: Send + Sync {
    /// Fired before the inner provider is called. Mutate the request in
    /// place. Return `Err(...)` to short-circuit — the provider will
    /// not be called.
    async fn before_call(
        &self,
        _messages: &mut Vec<Message>,
        _opts: &mut ChatOptions,
    ) -> Result<()> {
        Ok(())
    }

    /// Fired on a successful response. Mutate the response in place.
    async fn after_call(&self, _response: &mut ChatResponse) -> Result<()> {
        Ok(())
    }

    /// Fired on an error. Returning `Ok(Some(resp))` substitutes a
    /// recovered response. `Ok(None)` re-propagates the error. `Err(...)`
    /// substitutes the error.
    async fn on_error(&self, _err: &mut CognisError) -> Result<Option<ChatResponse>> {
        Ok(None)
    }

    /// Friendly name for diagnostics.
    fn name(&self) -> &str {
        std::any::type_name::<Self>()
    }
}

// ---------------------------------------------------------------------------
// FnChatInterceptor — assemble from individual closures.
// ---------------------------------------------------------------------------

type BeforeFn = Arc<
    dyn for<'a> Fn(
            &'a mut Vec<Message>,
            &'a mut ChatOptions,
        ) -> futures::future::BoxFuture<'a, Result<()>>
        + Send
        + Sync,
>;
type AfterFn = Arc<
    dyn for<'a> Fn(&'a mut ChatResponse) -> futures::future::BoxFuture<'a, Result<()>>
        + Send
        + Sync,
>;
type ErrFn = Arc<
    dyn for<'a> Fn(
            &'a mut CognisError,
        ) -> futures::future::BoxFuture<'a, Result<Option<ChatResponse>>>
        + Send
        + Sync,
>;

/// Closure-assembled interceptor. All hooks are optional.
#[derive(Default)]
pub struct FnChatInterceptor {
    before: Option<BeforeFn>,
    after: Option<AfterFn>,
    on_err: Option<ErrFn>,
    name: Option<String>,
}

impl FnChatInterceptor {
    /// Empty builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the friendly name.
    pub fn with_name(mut self, n: impl Into<String>) -> Self {
        self.name = Some(n.into());
        self
    }

    /// Sync `before_call` shorthand. The closure runs synchronously and
    /// is wrapped in `async`.
    pub fn before<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut Vec<Message>, &mut ChatOptions) -> Result<()> + Send + Sync + 'static,
    {
        self.before = Some(Arc::new(move |msgs, opts| {
            let res = f(msgs, opts);
            Box::pin(async move { res })
        }));
        self
    }

    /// Sync `after_call` shorthand.
    pub fn after<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut ChatResponse) -> Result<()> + Send + Sync + 'static,
    {
        self.after = Some(Arc::new(move |resp| {
            let res = f(resp);
            Box::pin(async move { res })
        }));
        self
    }

    /// Sync `on_error` shorthand.
    pub fn on_error<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut CognisError) -> Result<Option<ChatResponse>> + Send + Sync + 'static,
    {
        self.on_err = Some(Arc::new(move |e| {
            let res = f(e);
            Box::pin(async move { res })
        }));
        self
    }
}

#[async_trait]
impl ChatInterceptor for FnChatInterceptor {
    async fn before_call(&self, messages: &mut Vec<Message>, opts: &mut ChatOptions) -> Result<()> {
        if let Some(f) = &self.before {
            f(messages, opts).await
        } else {
            Ok(())
        }
    }
    async fn after_call(&self, response: &mut ChatResponse) -> Result<()> {
        if let Some(f) = &self.after {
            f(response).await
        } else {
            Ok(())
        }
    }
    async fn on_error(&self, err: &mut CognisError) -> Result<Option<ChatResponse>> {
        if let Some(f) = &self.on_err {
            f(err).await
        } else {
            Ok(None)
        }
    }
    fn name(&self) -> &str {
        self.name.as_deref().unwrap_or("FnChatInterceptor")
    }
}

// ---------------------------------------------------------------------------
// InterceptorProvider — wrap a provider with a chain of interceptors.
// ---------------------------------------------------------------------------

/// Wraps an [`LLMProvider`] with one or more [`ChatInterceptor`]s.
///
/// Execution order:
/// - `before_call` runs first → last (registration order).
/// - The inner provider runs.
/// - `after_call` runs last → first (onion-out).
/// - `on_error` runs last → first; first to recover wins.
pub struct InterceptorProvider {
    inner: Arc<dyn LLMProvider>,
    chain: Vec<Arc<dyn ChatInterceptor>>,
    name: String,
}

impl InterceptorProvider {
    /// Wrap with no interceptors (no-op until configured).
    pub fn new(inner: Arc<dyn LLMProvider>) -> Self {
        let name = inner.name().to_string();
        Self {
            inner,
            chain: Vec::new(),
            name,
        }
    }

    /// Append an interceptor to the chain.
    pub fn push(mut self, ic: Arc<dyn ChatInterceptor>) -> Self {
        self.chain.push(ic);
        self
    }

    /// Borrow the registered interceptors.
    pub fn interceptors(&self) -> &[Arc<dyn ChatInterceptor>] {
        &self.chain
    }

    async fn run_before(&self, messages: &mut Vec<Message>, opts: &mut ChatOptions) -> Result<()> {
        for ic in &self.chain {
            ic.before_call(messages, opts).await?;
        }
        Ok(())
    }

    async fn run_after(&self, resp: &mut ChatResponse) -> Result<()> {
        for ic in self.chain.iter().rev() {
            ic.after_call(resp).await?;
        }
        Ok(())
    }

    async fn run_error(
        &self,
        mut err: CognisError,
    ) -> std::result::Result<ChatResponse, CognisError> {
        for ic in self.chain.iter().rev() {
            match ic.on_error(&mut err).await {
                Ok(Some(r)) => return Ok(r),
                Ok(None) => {}
                Err(e) => err = e,
            }
        }
        Err(err)
    }
}

#[async_trait]
impl LLMProvider for InterceptorProvider {
    fn name(&self) -> &str {
        &self.name
    }

    fn provider_type(&self) -> Provider {
        self.inner.provider_type()
    }

    async fn chat_completion(
        &self,
        messages: Vec<Message>,
        opts: ChatOptions,
    ) -> Result<ChatResponse> {
        let mut messages = messages;
        let mut opts = opts;
        self.run_before(&mut messages, &mut opts).await?;
        match self.inner.chat_completion(messages, opts).await {
            Ok(mut r) => {
                self.run_after(&mut r).await?;
                Ok(r)
            }
            Err(e) => self.run_error(e).await,
        }
    }

    async fn chat_completion_stream(
        &self,
        messages: Vec<Message>,
        opts: ChatOptions,
    ) -> Result<RunnableStream<StreamChunk>> {
        // Streaming hooks only fire `before_call` (the per-chunk path
        // doesn't have a clean after-mutation point).
        let mut messages = messages;
        let mut opts = opts;
        self.run_before(&mut messages, &mut opts).await?;
        self.inner.chat_completion_stream(messages, opts).await
    }

    async fn chat_completion_with_tools(
        &self,
        messages: Vec<Message>,
        tools: Vec<ToolDefinition>,
        opts: ChatOptions,
    ) -> Result<ChatResponse> {
        let mut messages = messages;
        let mut opts = opts;
        self.run_before(&mut messages, &mut opts).await?;
        match self
            .inner
            .chat_completion_with_tools(messages, tools, opts)
            .await
        {
            Ok(mut r) => {
                self.run_after(&mut r).await?;
                Ok(r)
            }
            Err(e) => self.run_error(e).await,
        }
    }

    async fn health_check(&self) -> Result<HealthStatus> {
        self.inner.health_check().await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Echo;
    #[async_trait]
    impl LLMProvider for Echo {
        fn name(&self) -> &str {
            "echo"
        }
        fn provider_type(&self) -> Provider {
            Provider::OpenAI
        }
        async fn chat_completion(
            &self,
            messages: Vec<Message>,
            _: ChatOptions,
        ) -> Result<ChatResponse> {
            Ok(ChatResponse {
                message: Message::ai(
                    messages
                        .last()
                        .map(|m| m.content())
                        .unwrap_or("")
                        .to_string(),
                ),
                usage: None,
                finish_reason: "stop".into(),
                model: "echo".into(),
            })
        }
        async fn chat_completion_stream(
            &self,
            _: Vec<Message>,
            _: ChatOptions,
        ) -> Result<RunnableStream<StreamChunk>> {
            unimplemented!()
        }
        async fn health_check(&self) -> Result<HealthStatus> {
            Ok(HealthStatus::Healthy { latency_ms: 0 })
        }
    }

    struct Failing;
    #[async_trait]
    impl LLMProvider for Failing {
        fn name(&self) -> &str {
            "failing"
        }
        fn provider_type(&self) -> Provider {
            Provider::OpenAI
        }
        async fn chat_completion(&self, _: Vec<Message>, _: ChatOptions) -> Result<ChatResponse> {
            Err(CognisError::Internal("boom".into()))
        }
        async fn chat_completion_stream(
            &self,
            _: Vec<Message>,
            _: ChatOptions,
        ) -> Result<RunnableStream<StreamChunk>> {
            unimplemented!()
        }
        async fn health_check(&self) -> Result<HealthStatus> {
            Ok(HealthStatus::Healthy { latency_ms: 0 })
        }
    }

    #[tokio::test]
    async fn before_can_rewrite_messages() {
        let inner = Arc::new(Echo);
        let ic = FnChatInterceptor::new().before(|msgs, _| {
            // Append a sentinel suffix to the last human message.
            if let Some(last) = msgs.last_mut() {
                if matches!(last, Message::Human(_)) {
                    let new = format!("{}!!!", last.content());
                    *last = Message::human(new);
                }
            }
            Ok(())
        });
        let p = InterceptorProvider::new(inner).push(Arc::new(ic));
        let r = p
            .chat_completion(vec![Message::human("hi")], ChatOptions::default())
            .await
            .unwrap();
        assert_eq!(r.message.content(), "hi!!!");
    }

    #[tokio::test]
    async fn after_can_rewrite_response() {
        let inner = Arc::new(Echo);
        let ic = FnChatInterceptor::new().after(|resp| {
            let new = format!("[{}]", resp.message.content());
            resp.message = Message::ai(new);
            Ok(())
        });
        let p = InterceptorProvider::new(inner).push(Arc::new(ic));
        let r = p
            .chat_completion(vec![Message::human("hi")], ChatOptions::default())
            .await
            .unwrap();
        assert_eq!(r.message.content(), "[hi]");
    }

    #[tokio::test]
    async fn on_error_can_recover() {
        let inner = Arc::new(Failing);
        let ic = FnChatInterceptor::new().on_error(|_e| {
            Ok(Some(ChatResponse {
                message: Message::ai("recovered"),
                usage: None,
                finish_reason: "stop".into(),
                model: "n/a".into(),
            }))
        });
        let p = InterceptorProvider::new(inner).push(Arc::new(ic));
        let r = p
            .chat_completion(vec![Message::human("hi")], ChatOptions::default())
            .await
            .unwrap();
        assert_eq!(r.message.content(), "recovered");
    }

    #[tokio::test]
    async fn before_short_circuits_via_err() {
        let inner = Arc::new(Echo);
        let ic = FnChatInterceptor::new()
            .before(|_msgs, _opts| Err(CognisError::Configuration("blocked".into())));
        let p = InterceptorProvider::new(inner).push(Arc::new(ic));
        let err = p
            .chat_completion(vec![Message::human("x")], ChatOptions::default())
            .await
            .unwrap_err();
        assert!(matches!(err, CognisError::Configuration(_)));
    }

    #[tokio::test]
    async fn onion_order_after_runs_outer_to_inner_reverse() {
        // outer adds (), inner adds [].
        let inner = Arc::new(Echo);
        let outer = FnChatInterceptor::new().after(|r| {
            let n = format!("({})", r.message.content());
            r.message = Message::ai(n);
            Ok(())
        });
        let inner_ic = FnChatInterceptor::new().after(|r| {
            let n = format!("[{}]", r.message.content());
            r.message = Message::ai(n);
            Ok(())
        });
        let p = InterceptorProvider::new(inner)
            .push(Arc::new(outer))
            .push(Arc::new(inner_ic));
        let r = p
            .chat_completion(vec![Message::human("x")], ChatOptions::default())
            .await
            .unwrap();
        // after runs reversed: inner first → "[x]", then outer → "([x])".
        assert_eq!(r.message.content(), "([x])");
    }
}