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
//! Never exceed [OpenAI](https://openai.com/)'s [chat models](https://platform.openai.com/docs/api-reference/chat)' [maximum number of tokens](https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them) when using the [`async_openai`](https://github.com/64bit/async-openai) Rust crate.
//!
//! `chat-splitter` splits chats into 'outdated' and 'recent' messages.
//! You can split by
//! both
//! maximum message count and
//! maximum chat completion token count.
//! We use [`tiktoken_rs`](https://github.com/zurawiki/tiktoken-rs) for counting tokens.
//!
//! # Usage
//!
//! Here's a basic example:
//!
//! ```ignore
//! // Get all your previously stored chat messages...
//! let mut stored_messages = /* get_stored_messages()? */;
//!
//! // ...and split into 'outdated' and 'recent',
//! // where 'recent' always fits the context size.
//! let (outdated_messages, recent_messages) =
//! ChatSplitter::default().split(&stored_messages);
//! ```
//!
//! For a more detailed example,
//! see [`examples/chat.rs`](https://github.com/schneiderfelipe/chat-splitter/blob/main/examples/chat.rs).
//!
//! # Contributing
//!
//! Contributions to `chat-splitter` are welcome!
//! If you find a bug or have a feature request,
//! please [submit an issue](https://github.com/schneiderfelipe/chat-splitter/issues).
//! If you'd like to contribute code,
//! please feel free to [submit a pull request](https://github.com/schneiderfelipe/chat-splitter/pulls).
use std::cmp::Ordering;
use indxvec::Search;
use tiktoken_rs::get_chat_completion_max_tokens;
use tiktoken_rs::model::get_context_size;
/// Chat splitter for [OpenAI](https://openai.com/)'s [chat models](https://platform.openai.com/docs/api-reference/chat) when using [`async_openai`].
///
/// For more detailed information,
/// see the [crate documentation](`crate`).
#[derive(Clone, Debug)]
pub struct ChatSplitter {
/// The model to use for tokenization, e.g., `gpt-3.5-turbo`.
///
/// It is passed to [`tiktoken_rs`] to select the correct tokenizer.
model: String,
/// The maximum number of tokens to leave for chat completion.
///
/// This is the same as in the [official API](https://platform.openai.com/docs/api-reference/chat#completions/create-prompt) and given to [`async_openai`].
/// The total length of input tokens and generated tokens is limited by the
/// model's context size.
/// Splits will have at least that many tokens
/// available for chat completion,
/// never less.
max_tokens: u16,
/// The maximum number of messages to have in the chat.
///
/// Splits will have at most that many messages,
/// never more.
max_messages: usize,
}
/// Hard limit that seems to be imposed by the `OpenAI` API.
const MAX_MESSAGES_LIMIT: usize = 2_048;
/// Recommended minimum for maximum chat completion tokens.
const RECOMMENDED_MIN_MAX_TOKENS: u16 = 256;
impl Default for ChatSplitter {
#[inline]
fn default() -> Self {
Self::new("gpt-3.5-turbo")
}
}
impl ChatSplitter {
/// Create a new [`ChatSplitter`] for the given model.
///
/// # Panics
///
/// If for some reason [`tiktoken_rs`] gives a context size twice as large
/// as what would fit in a [`u16`].
/// If this happens,
/// it should be considered a bug,
/// but this behaviour might change in the future,
/// as models with larger context sizes are released.
#[inline]
pub fn new(model: impl Into<String>) -> Self {
let model = model.into();
let max_tokens = u16::try_from(get_context_size(&model) / 2).unwrap();
let max_messages = MAX_MESSAGES_LIMIT / 2;
Self {
model,
max_tokens,
max_messages,
}
}
/// Set the maximum number of messages to have in the chat.
///
/// Splits will have at most that many messages,
/// never more.
#[inline]
#[must_use]
pub fn max_messages(mut self, max_messages: impl Into<usize>) -> Self {
self.max_messages = max_messages.into();
if self.max_messages > MAX_MESSAGES_LIMIT {
log::warn!(
"max_messages = {} > {MAX_MESSAGES_LIMIT}",
self.max_messages
);
}
self
}
/// Set the maximum number of tokens to leave for chat completion.
///
/// This is the same as in the [official API](https://platform.openai.com/docs/api-reference/chat#completions/create-prompt) and given to [`async_openai`].
/// The total length of input tokens and generated tokens is limited by the
/// model's context size.
/// Splits will have at least that many tokens
/// available for chat completion,
/// never less.
#[inline]
#[must_use]
pub fn max_tokens(mut self, max_tokens: impl Into<u16>) -> Self {
self.max_tokens = max_tokens.into();
if self.max_tokens < RECOMMENDED_MIN_MAX_TOKENS {
log::warn!(
"max_tokens = {} < {RECOMMENDED_MIN_MAX_TOKENS}",
self.max_tokens
);
}
self
}
/// Set the model to use for tokenization, e.g., `gpt-3.5-turbo`.
///
/// It is passed to [`tiktoken_rs`] to select the correct tokenizer.
#[inline]
#[must_use]
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = model.into();
self
}
/// Get a split position by only considering `max_messages`.
#[inline]
fn position_by_max_messages<M>(&self, messages: &[M]) -> usize {
let upper_limit = self.max_messages.min(MAX_MESSAGES_LIMIT);
let n = messages.len();
let n = if n <= upper_limit { 0 } else { n - upper_limit };
debug_assert!(messages[n..].len() <= upper_limit);
n
}
/// Get a split position by only considering `max_tokens`.
///
/// # Panics
///
/// If tokenizer for the specified model is not found or is not a supported
/// chat model.
#[inline]
fn position_by_max_tokens<M>(&self, messages: &[M]) -> usize
where
M: IntoChatCompletionRequestMessage + Clone,
{
let max_tokens = self.max_tokens as usize;
let lower_limit = max_tokens.min(get_context_size(&self.model));
let messages: Vec<_> = messages
.iter()
.cloned()
.map(IntoChatCompletionRequestMessage::into_tiktoken_rs)
.collect();
let (n, _range) = (0..=messages.len()).binary_any(|n| {
debug_assert!(n < messages.len());
let tokens = get_chat_completion_max_tokens(&self.model, &messages[n..])
.expect("tokenizer should be available");
let cmp = tokens.cmp(&lower_limit);
debug_assert_ne!(cmp, Ordering::Equal);
cmp
});
debug_assert!(
get_chat_completion_max_tokens(&self.model, &messages[n..])
.expect("tokenizer should be available")
>= lower_limit
);
n
}
/// Get a split position by first considering the `max_messages` limit,
/// then
/// the `max_tokens` limit.
///
/// # Panics
///
/// If tokenizer for the specified model is not found or is not a supported
/// chat model.
#[inline]
fn position<M>(&self, messages: &[M]) -> usize
where
M: IntoChatCompletionRequestMessage + Clone,
{
let n = self.position_by_max_messages(messages);
n + self.position_by_max_tokens(&messages[n..])
}
/// Split the chat into two groups of messages,
/// the 'outdated' and the
/// 'recent' ones.
///
/// The 'recent' messages are guaranteed to satisfy the given limits,
/// while
/// the 'outdated' ones contain all the ones before 'recent'.
///
/// For a detailed usage example,
/// see [`examples/chat.rs`](https://github.com/schneiderfelipe/chat-splitter/blob/main/examples/chat.rs).
///
/// # Panics
///
/// If tokenizer for the specified model is not found or is not a supported
/// chat model.
#[inline]
pub fn split<'a, M>(&self, messages: &'a [M]) -> (&'a [M], &'a [M])
where
M: IntoChatCompletionRequestMessage + Clone,
{
messages.split_at(self.position(messages))
}
}
/// Extension trait for converting between different chat completion request
/// message types.
///
/// For a usage example,
/// see [`examples/chat.rs`](https://github.com/schneiderfelipe/chat-splitter/blob/736f4fceb57bc12adb2b70deb990030a266a95a5/examples/chat.rs#L44-L55).
pub trait IntoChatCompletionRequestMessage {
/// Convert to [`tiktoken_rs` chat completion request message
/// type](`tiktoken_rs::ChatCompletionRequestMessage`).
fn into_tiktoken_rs(self) -> tiktoken_rs::ChatCompletionRequestMessage;
/// Convert to [`async_openai` chat completion request message
/// type](`async_openai::types::ChatCompletionRequestMessage`).
fn into_async_openai(self) -> async_openai::types::ChatCompletionRequestMessage;
}
impl IntoChatCompletionRequestMessage for tiktoken_rs::ChatCompletionRequestMessage {
#[inline]
fn into_tiktoken_rs(self) -> tiktoken_rs::ChatCompletionRequestMessage {
self
}
#[inline]
fn into_async_openai(self) -> async_openai::types::ChatCompletionRequestMessage {
async_openai::types::ChatCompletionRequestMessage {
role: match self.role.as_ref() {
"user" => async_openai::types::Role::User,
"system" => async_openai::types::Role::System,
"assistant" => async_openai::types::Role::Assistant,
"function" => async_openai::types::Role::Function,
role => panic!("unknown role '{role}'"),
},
content: self.content,
function_call: self.function_call.map(|fc| {
async_openai::types::FunctionCall {
name: fc.name,
arguments: fc.arguments,
}
}),
name: self.name,
}
}
}
impl IntoChatCompletionRequestMessage for async_openai::types::ChatCompletionRequestMessage {
#[inline]
fn into_tiktoken_rs(self) -> tiktoken_rs::ChatCompletionRequestMessage {
tiktoken_rs::ChatCompletionRequestMessage {
role: self.role.to_string(),
content: self.content,
function_call: self.function_call.map(|fc| {
tiktoken_rs::FunctionCall {
name: fc.name,
arguments: fc.arguments,
}
}),
name: self.name,
}
}
#[inline]
fn into_async_openai(self) -> async_openai::types::ChatCompletionRequestMessage {
self
}
}
impl IntoChatCompletionRequestMessage for async_openai::types::ChatCompletionResponseMessage {
#[inline]
fn into_tiktoken_rs(self) -> tiktoken_rs::ChatCompletionRequestMessage {
tiktoken_rs::ChatCompletionRequestMessage {
role: self.role.to_string(),
content: self.content,
function_call: self.function_call.map(|fc| {
tiktoken_rs::FunctionCall {
name: fc.name,
arguments: fc.arguments,
}
}),
name: None,
}
}
#[inline]
fn into_async_openai(self) -> async_openai::types::ChatCompletionRequestMessage {
async_openai::types::ChatCompletionRequestMessage {
role: self.role,
content: self.content,
function_call: self.function_call,
name: None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let messages: Vec<async_openai::types::ChatCompletionRequestMessage> = Vec::new();
assert_eq!(ChatSplitter::default().split(&messages).0, &[]);
assert_eq!(ChatSplitter::default().split(&messages).1, &[]);
}
}