kalosm_language_model/model/
mod.rs

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
use kalosm_sample::Parser;
use std::{convert::Infallible, future::Future};

mod generation_parameters;
pub use generation_parameters::*;
mod ext;
pub use ext::*;
mod boxed;
pub use boxed::*;

#[doc = include_str!("../../docs/completion_session.md")]
pub trait TextCompletionSession {
    /// The type of error the session may return during operations.
    type Error: Send + Sync + 'static;

    /// Serialize the session into bytes. This method is identical to [`TextCompletionSession::to_bytes`] except it can re-use an existing [`Vec`] buffer.
    fn write_to(&self, into: &mut Vec<u8>) -> Result<(), Self::Error>;

    /// # Loading sessions
    ///
    /// Sessions can be deserialized to and from bytes using the [`TextCompletionSession::from_bytes`] method.
    /// Caching a session avoids re-processing the text again when the session is resumed.
    ///
    /// ```rust, no_run
    /// use kalosm::language::*;
    /// use std::io::Write;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut llm = Llama::new().await.unwrap();
    ///     let mut session = llm.new_session().unwrap();
    ///
    ///     // Feed some text into the session
    ///     llm.stream_text_with_callback(
    ///         &mut session,
    ///         "The capital of France is ",
    ///         GenerationParameters::new().with_max_length(0),
    ///         |_| Ok(()),
    ///     )
    ///     .await
    ///     .unwrap();
    ///
    ///     // Save the session to bytes
    ///     let session_as_bytes = session.to_bytes().unwrap();
    ///
    ///     // And write those bytes to a file
    ///     std::fs::write("session.bin", session_as_bytes).unwrap();
    /// }
    /// ```
    fn to_bytes(&self) -> Result<Vec<u8>, Self::Error> {
        let mut bytes = Vec::new();
        self.write_to(&mut bytes)?;
        Ok(bytes)
    }

    /// # Loading sessions
    ///
    /// Sessions can be deserialized to and from bytes using the [`TextCompletionSession::from_bytes`] method.
    /// Caching a session avoids re-processing the text again when the session is resumed.
    ///
    /// ```rust, no_run
    /// use kalosm::language::*;
    /// use std::io::Write;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut llm = Llama::new().await.unwrap();
    ///     // Load a text completion session from a file
    ///     let mut session =
    ///         LlamaSession::from_bytes(std::fs::read("session.bin").unwrap().as_slice()).unwrap();
    ///
    ///     // Feed some more text into the session
    ///     llm.stream_text_with_callback(
    ///         &mut session,
    ///         "The capital of France is ",
    ///         GenerationParameters::new(),
    ///         |token| {
    ///             println!("{token}");
    ///             Ok(())
    ///         },
    ///     )
    ///     .await
    ///     .unwrap();
    /// }
    /// ```
    fn from_bytes(bytes: &[u8]) -> Result<Self, Self::Error>
    where
        Self: std::marker::Sized;

    /// # Cloning Sessions
    ///
    /// Not all models support cloning sessions, but if a model does support cloning sessions, you can clone a session using the [`TextCompletionSession::try_clone`] method to clone a session state while retaining the original session.
    ///
    /// ```rust, no_run
    /// use kalosm::language::*;
    /// use std::io::Write;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut llm = Llama::new().await.unwrap();
    ///     let mut session = llm.new_session().unwrap();
    ///
    ///     // Feed some text into the session
    ///     llm.stream_text_with_callback(
    ///         &mut session,
    ///         "The capital of France is ",
    ///         GenerationParameters::new().with_max_length(0),
    ///         |_| Ok(()),
    ///     )
    ///     .await
    ///     .unwrap();
    ///
    ///     // Clone the session
    ///     let cloned_session = session.try_clone().unwrap();
    ///
    ///     // Feed some more text into the cloned session
    ///     llm.stream_text_with_callback(
    ///         &mut session,
    ///         "The capital of France is ",
    ///         GenerationParameters::new(),
    ///         |token| {
    ///             println!("{token}");
    ///             Ok(())
    ///         },
    ///     )
    ///     .await
    ///     .unwrap();
    /// }
    /// ```
    fn try_clone(&self) -> Result<Self, Self::Error>
    where
        Self: std::marker::Sized;
}

impl TextCompletionSession for () {
    type Error = Infallible;

    fn write_to(&self, _into: &mut Vec<u8>) -> Result<(), Self::Error> {
        Ok(())
    }

    fn from_bytes(_bytes: &[u8]) -> Result<(), Self::Error> {
        Ok(())
    }

    fn try_clone(&self) -> Result<(), Self::Error> {
        Ok(())
    }
}

/// A marker type that indicates that no constraints were supplied.
#[derive(Debug, Clone, Copy)]
pub struct NoConstraints;

/// A type that can constrain the output of a model into a specific output type.
pub trait ModelConstraints {
    /// The type of the output of the constraints.
    type Output;
}

impl<P: Parser> ModelConstraints for P {
    type Output = <P as Parser>::Output;
}

/// A trait for creating a text completion session for a model. While it the core trait
/// every text completion model must implement, most methods to use models that implement
/// this trait are implemented in the [`TextCompletionModelExt`] trait.
///
/// # Example
///
/// ```rust, no_run
/// use kalosm::language::*;
///
/// #[tokio::main]
/// async fn main() {
///     // Create a new model which implements the CreateTextCompletionSession trait
///     let mut llm = Llama::new().await.unwrap();
///     // Create a new session for the model
///     let mut session = llm.new_session().unwrap();
/// }
/// ```
pub trait CreateTextCompletionSession {
    /// The type of error this model may return during operations.
    type Error: Send + Sync + 'static;

    /// The type of the session that this model uses.
    type Session: TextCompletionSession;

    /// Create a new session for this model.
    ///
    /// # Example
    /// ```rust, no_run
    /// # use kalosm::language::*;
    /// # #[tokio::main]
    /// # async fn main() {
    /// // Create a new model which implements the CreateTextCompletionSession trait
    /// let llm = Llama::new().await.unwrap();
    /// // Create a new session for the model
    /// let session = llm.new_session().unwrap();
    /// # }
    /// ```
    fn new_session(&self) -> Result<Self::Session, Self::Error>;
}

/// A trait that defines the default constraints for a type with this model.
pub trait CreateDefaultCompletionConstraintsForType<T>:
    StructuredTextCompletionModel<Self::DefaultConstraints>
{
    /// The default constraints for this type that work with this model.
    type DefaultConstraints: ModelConstraints<Output = T>;

    /// Create [`Self::DefaultConstraints`] which parse the type `T` for this model.
    fn create_default_constraints() -> Self::DefaultConstraints;
}

/// A trait for unstructured text completion models. This trait is required for any text completion models
/// even if they do not support structured generation. While this trait is implemented for all text completion models,
/// most methods to use models that implement this trait are implemented in the [`TextCompletionModelExt`] trait.
///
/// # Example
///
/// ```rust, no_run
/// use kalosm::language::*;
///
/// #[tokio::main]
/// async fn main() {
///     // Create a new model which implements the CreateTextCompletionSession trait
///     let mut llm = Llama::new().await.unwrap();
///     // Create a new session for the model
///     let mut session = llm.new_session().unwrap();
///     // Feed some text into the session using the raw text completion api that accepts a session, prompt, sampler, and on token callback
///     llm.stream_text_with_callback(&mut session, "The capital of France is ", GenerationParameters::new(), |token| {println!("{token}"); Ok(())}).await.unwrap();
/// }
/// ```
pub trait TextCompletionModel<Sampler = GenerationParameters>: CreateTextCompletionSession {
    /// Generate text with the given prompt.
    ///
    /// See [`TextCompletionModelExt::complete`] for nicer API with an example.
    fn stream_text_with_callback<'a>(
        &'a self,
        session: &'a mut Self::Session,
        text: &str,
        sampler: Sampler,
        on_token: impl FnMut(String) -> Result<(), Self::Error> + Send + Sync + 'static,
    ) -> impl Future<Output = Result<(), Self::Error>> + Send + 'a;
}

/// A trait for text completion models that support structured generation. While this trait is implemented for
/// all structured text completion models, most methods to use models that implement this trait are implemented
/// in the [`TextCompletionModelExt`] trait.
///
/// # Example
///
/// ```rust, no_run
/// use kalosm::language::*;
///
/// #[tokio::main]
/// async fn main() {
///     // Create a new model which implements the CreateTextCompletionSession trait
///     let mut llm = Llama::new().await.unwrap();
///     // Create a new session for the model
///     let mut session = llm.new_session().unwrap();
///     // Create a parser for your data. Different models accept different types of parsers. The Llama model accepts
///     // any parsers that implements the `Parse` trait.
///     let parser = i32::new_parser();
///     // Feed some text into the session using the raw structured text completion api that accepts a session, prompt, sampler, and on token callback
///     llm.stream_text_with_callback_and_parser(&mut session, "5 * 5 = ", GenerationParameters::new(), parser, |token| {println!("{token}"); Ok(())}).await.unwrap();
/// }
/// ```
pub trait StructuredTextCompletionModel<
    Constraints: ModelConstraints,
    Sampler = GenerationParameters,
>: TextCompletionModel<Sampler>
{
    /// Generate text with the given prompt and the given constraints.
    ///
    /// See [`TextCompletionModelExt::complete`] for nicer API with an example.
    fn stream_text_with_callback_and_parser<'a>(
        &'a self,
        session: &'a mut Self::Session,
        text: &str,
        sampler: Sampler,
        parser: Constraints,
        on_token: impl FnMut(String) -> Result<(), Self::Error> + Send + Sync + 'static,
    ) -> impl Future<Output = Result<Constraints::Output, Self::Error>> + Send + 'a;
}