mojentic 3.0.0

An LLM integration framework for Rust
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
//! Single-turn streaming with terminal completion evidence.
//!
//! [`crate::llm::LlmBroker::generate_stream_events`] yields [`StreamEvent`]s for
//! one model turn. Every stream ends with exactly one terminal event:
//! [`StreamEvent::Completed`] when the provider reported a clean stop, or
//! [`StreamEvent::Error`] otherwise. Nothing follows the terminal event.
//!
//! Content yielded before an error is evidence of what the provider sent, not
//! a result. Truncated or unfinished output is always an error.

use crate::error::MojenticError;
use crate::llm::models::ResponseEvidence;
use futures::stream::{Stream, StreamExt};
use serde_json::Value;
use std::pin::Pin;
use thiserror::Error;

/// A boxed stream of [`StreamEvent`]s for one model turn.
pub type StreamEventStream<'a> = Pin<Box<dyn Stream<Item = StreamEvent> + Send + 'a>>;

/// One event in a single-turn event stream.
#[derive(Debug)]
#[non_exhaustive]
pub enum StreamEvent {
    /// Visible assistant content, in the order the provider sent it.
    Content(String),
    /// Client timing emitted immediately before terminal evidence, including errors.
    Metrics(crate::llm::gateway::StreamMetrics),
    /// Terminal success: the provider finished with `stop` and closed the stream.
    ///
    /// The evidence holds the finish reason, usage and provider model when
    /// reported, plus other provider metadata such as Ollama durations.
    Completed(ResponseEvidence),
    /// Terminal failure. Content yielded before it is not a complete result.
    Error(StreamEventError),
}

impl StreamEvent {
    /// Whether this event ends the stream.
    pub fn is_terminal(&self) -> bool {
        matches!(self, StreamEvent::Completed(_) | StreamEvent::Error(_))
    }
}

/// Why a single-turn event stream ended without a completed response.
///
/// The variants follow the cross-port reason vocabulary:
/// `incomplete_completion`, `incomplete_stream`, `provider_error`,
/// `unexpected_tool_calls`, `invalid_stream_event`,
/// `stream_events_unsupported` and `request_failed`.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum StreamEventError {
    /// The provider finished for a reason other than `stop`, for example
    /// `length`. Carries the finish reason, usage, provider model and metadata.
    ///
    /// Ollama servers too old to send `done_reason` always end here.
    #[error("incomplete completion (finish reason: {})", .0.finish_reason.as_deref().unwrap_or("unknown"))]
    IncompleteCompletion(Box<ResponseEvidence>),

    /// The stream ended without the provider's terminal marker. Carries the
    /// evidence that arrived before the end (such as model and usage), or
    /// `None` when none did.
    #[error("stream ended without a terminal marker")]
    IncompleteStream(Option<Box<ResponseEvidence>>),

    /// The provider reported an error, either as an error frame in the stream
    /// or as a non-success HTTP status.
    #[error("provider error{}: {error}", .status.map(|code| format!(" (HTTP {code})")).unwrap_or_default())]
    ProviderError {
        /// HTTP status, when the provider rejected the request with one.
        status: Option<u16>,
        /// The provider's error value: the frame's `error` field, or the
        /// response body (its `error` field when it has one).
        error: Value,
    },

    /// The provider streamed a native tool call. The events API supplies no
    /// tools and executes none.
    #[error("unexpected tool calls in stream")]
    UnexpectedToolCalls,

    /// A frame could not be read as a provider stream event.
    #[error("invalid stream event: {0}")]
    InvalidStreamEvent(String),

    /// The gateway does not implement the events API. No request was sent.
    #[error("stream events are not supported by this gateway")]
    StreamEventsUnsupported,

    /// Building the request, connecting, or reading the response body failed.
    #[error("stream request failed: {0}")]
    RequestFailed(#[source] MojenticError),
}

impl StreamEventError {
    /// A provider error for an error frame inside the stream.
    pub(crate) fn provider_frame(error: Value) -> Self {
        StreamEventError::ProviderError {
            status: None,
            error,
        }
    }

    /// A provider error for a non-success HTTP response.
    fn provider_status(status: u16, body: &str) -> Self {
        let error = match serde_json::from_str::<Value>(body) {
            Ok(Value::Object(mut fields)) if fields.contains_key("error") => {
                fields.remove("error").unwrap_or(Value::Null)
            }
            Ok(value) => value,
            Err(_) => Value::String(body.to_string()),
        };
        StreamEventError::ProviderError {
            status: Some(status),
            error,
        }
    }
}

/// Turns one provider stream line into zero or more events.
///
/// A parser owns the provider's completion rules. It returns a terminal event
/// when the line settles the outcome; the driver stops reading after it.
pub(crate) trait FrameParser {
    fn parse_line(&mut self, line: &str) -> Vec<StreamEvent>;

    /// Evidence seen so far, for a stream that ends without a terminal marker.
    fn partial_evidence(&self) -> Option<ResponseEvidence>;
}

/// Send one streaming request and translate its lines into events.
///
/// The returned stream owns the HTTP response. Dropping the stream drops the
/// response body, which closes the connection and cancels the request.
pub(crate) fn drive_event_stream<'a, P>(
    request: reqwest::RequestBuilder,
    mut parser: P,
    clock: std::sync::Arc<dyn crate::llm::stream_timing::StreamClock>,
    provider: &'static str,
) -> StreamEventStream<'a>
where
    P: FrameParser + Send + 'a,
{
    let timing = crate::llm::stream_timing::StreamTiming::new(clock);
    let measure = timing.clone();
    let mut source: StreamEventStream<'a> = Box::pin(async_stream::stream! {
        measure.dispatch();
        let response = match request.send().await {
            Ok(response) => response,
            Err(error) => {
                yield StreamEvent::Error(StreamEventError::RequestFailed(error.into()));
                return;
            }
        };

        let status = response.status();
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            yield StreamEvent::Error(StreamEventError::provider_status(status.as_u16(), &body));
            return;
        }

        let mut bytes = response.bytes_stream();
        let mut lines = LineBuffer::default();
        while let Some(chunk) = bytes.next().await {
            let chunk = match chunk {
                Ok(chunk) => chunk,
                Err(error) => {
                    yield StreamEvent::Error(StreamEventError::RequestFailed(error.into()));
                    return;
                }
            };
            for line in lines.push(&chunk) {
                if let Ok(text) = std::str::from_utf8(&line) { measure.observe_line(text); }
                let events = match std::str::from_utf8(&line) {
                    Ok(text) => parser.parse_line(text.trim_end_matches('\r')),
                    Err(_) => vec![invalid_event("frame is not valid UTF-8")],
                };
                for event in events {
                    let terminal = event.is_terminal();
                    yield event;
                    if terminal {
                        return;
                    }
                }
            }
        }

        yield StreamEvent::Error(StreamEventError::IncompleteStream(
            parser.partial_evidence().map(Box::new),
        ));
    });
    Box::pin(async_stream::stream! {
        while let Some(mut event) = source.next().await {
            if event.is_terminal() {
                let metrics = timing.finish(crate::llm::gateway::StreamMetrics { provider: provider.into(), ..Default::default() });
                let evidence = match &mut event {
                    StreamEvent::Completed(evidence) => Some(evidence),
                    StreamEvent::Error(StreamEventError::IncompleteCompletion(evidence)) => Some(evidence.as_mut()),
                    StreamEvent::Error(StreamEventError::IncompleteStream(Some(evidence))) => Some(evidence.as_mut()),
                    _ => None,
                };
                if let Some(evidence) = evidence {
                    crate::llm::stream_timing::retain_timing(evidence, &metrics);
                }
                yield StreamEvent::Metrics(metrics);
            }
            yield event;
        }
    })
}

/// An [`StreamEvent::Error`] for a frame that is not a valid provider event.
pub(crate) fn invalid_event(reason: impl Into<String>) -> StreamEvent {
    StreamEvent::Error(StreamEventError::InvalidStreamEvent(reason.into()))
}

/// Splits a byte stream into complete newline-terminated lines.
///
/// Bytes after the last newline wait for the next chunk, so a frame split
/// across network reads (including inside a UTF-8 sequence) stays intact.
/// A trailing partial line at end of stream is never returned: a stream cut
/// mid-frame is incomplete, not malformed.
#[derive(Default)]
pub(crate) struct LineBuffer {
    pending: Vec<u8>,
}

impl LineBuffer {
    pub(crate) fn has_pending(&self) -> bool {
        !self.pending.is_empty()
    }

    pub(crate) fn push(&mut self, chunk: &[u8]) -> Vec<Vec<u8>> {
        self.pending.extend_from_slice(chunk);
        let Some(last_newline) = self.pending.iter().rposition(|byte| *byte == b'\n') else {
            return Vec::new();
        };
        let rest = self.pending.split_off(last_newline + 1);
        let complete = std::mem::replace(&mut self.pending, rest);
        complete[..complete.len() - 1]
            .split(|byte| *byte == b'\n')
            .map(<[u8]>::to_vec)
            .collect()
    }
}

#[cfg(test)]
pub(crate) mod testing {
    //! A local HTTP server that streams forever, for cancellation tests.

    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;
    use tokio::sync::oneshot;

    /// Serve one chunked response that sends `first_frame` and then never ends.
    ///
    /// Returns the base URL and a receiver that resolves when the client
    /// closes the connection.
    pub(crate) async fn endless_stream_server(
        first_frame: &'static str,
    ) -> (String, oneshot::Receiver<()>) {
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind test server");
        let address = listener.local_addr().expect("test server address");
        let (closed_tx, closed_rx) = oneshot::channel();

        tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.expect("accept client");
            read_request(&mut socket).await;
            let head = "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n\r\n";
            let chunk = format!("{:x}\r\n{}\r\n", first_frame.len(), first_frame);
            socket.write_all(head.as_bytes()).await.expect("write head");
            socket.write_all(chunk.as_bytes()).await.expect("write first frame");

            // The response never ends. A read of zero bytes means the client hung up.
            let mut buffer = [0u8; 64];
            while let Ok(read) = socket.read(&mut buffer).await {
                if read == 0 {
                    break;
                }
            }
            let _ = closed_tx.send(());
        });

        (format!("http://{address}"), closed_rx)
    }

    /// Serve one chunked response that sends each of `parts` as its own
    /// network write, pausing between them so the client reads them apart.
    ///
    /// Returns the base URL.
    pub(crate) async fn split_body_server(parts: Vec<Vec<u8>>) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind test server");
        let address = listener.local_addr().expect("test server address");

        tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.expect("accept client");
            read_request(&mut socket).await;
            let head = "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\ntransfer-encoding: chunked\r\n\r\n";
            socket.write_all(head.as_bytes()).await.expect("write head");
            for part in parts {
                let mut chunk = format!("{:x}\r\n", part.len()).into_bytes();
                chunk.extend_from_slice(&part);
                chunk.extend_from_slice(b"\r\n");
                socket.write_all(&chunk).await.expect("write part");
                socket.flush().await.expect("flush part");
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
            }
            socket.write_all(b"0\r\n\r\n").await.expect("write end");
            socket.flush().await.expect("flush end");
        });

        format!("http://{address}")
    }

    /// `body` split into two parts inside the first multi-byte UTF-8 character.
    pub(crate) fn split_inside_first_multibyte_char(body: &str) -> Vec<Vec<u8>> {
        let (index, _) = body
            .char_indices()
            .find(|(_, c)| c.len_utf8() > 1)
            .expect("body has a multi-byte character");
        let bytes = body.as_bytes();
        vec![bytes[..index + 1].to_vec(), bytes[index + 1..].to_vec()]
    }

    async fn read_request(socket: &mut tokio::net::TcpStream) {
        let mut request = Vec::new();
        let mut buffer = [0u8; 4096];
        loop {
            let read = socket.read(&mut buffer).await.expect("read request");
            request.extend_from_slice(&buffer[..read]);
            let text = String::from_utf8_lossy(&request);
            if let Some(head_end) = text.find("\r\n\r\n") {
                let length = text[..head_end]
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("content-length")
                            .then(|| value.trim().parse::<usize>().ok())?
                    })
                    .unwrap_or(0);
                if request.len() >= head_end + 4 + length {
                    return;
                }
            }
            if read == 0 {
                return;
            }
        }
    }
}

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

    #[test]
    fn line_buffer_returns_only_complete_lines() {
        let mut lines = LineBuffer::default();

        assert!(lines.push(b"data: {\"a\"").is_empty());
        assert_eq!(lines.push(b":1}\n\ndata: [DO"), vec![b"data: {\"a\":1}".to_vec(), vec![]]);
        assert_eq!(lines.push(b"NE]\n"), vec![b"data: [DONE]".to_vec()]);
    }

    #[test]
    fn line_buffer_keeps_utf8_sequences_split_across_chunks() {
        let mut lines = LineBuffer::default();
        let text = "héllo\n".as_bytes();

        assert!(lines.push(&text[..2]).is_empty());
        let complete = lines.push(&text[2..]);

        assert_eq!(complete, vec!["héllo".as_bytes().to_vec()]);
    }

    #[test]
    fn only_content_is_non_terminal() {
        assert!(!StreamEvent::Content("x".into()).is_terminal());
        assert!(StreamEvent::Completed(ResponseEvidence::default()).is_terminal());
        assert!(StreamEvent::Error(StreamEventError::IncompleteStream(None)).is_terminal());
    }

    #[test]
    fn http_provider_error_keeps_status_and_error_field() {
        let error = StreamEventError::provider_status(429, r#"{"error":{"message":"slow"}}"#);

        assert!(matches!(
            &error,
            StreamEventError::ProviderError { status: Some(429), error } if error["message"] == "slow"
        ));
        assert!(error.to_string().starts_with("provider error (HTTP 429)"));
    }

    #[test]
    fn http_provider_error_keeps_a_non_json_body_as_text() {
        let error = StreamEventError::provider_status(502, "Bad Gateway");

        assert!(matches!(
            error,
            StreamEventError::ProviderError { status: Some(502), error } if error == "Bad Gateway"
        ));
    }

    #[test]
    fn incomplete_completion_names_its_finish_reason() {
        let error = StreamEventError::IncompleteCompletion(Box::new(ResponseEvidence {
            finish_reason: Some("length".into()),
            ..Default::default()
        }));

        assert_eq!(error.to_string(), "incomplete completion (finish reason: length)");
    }
}