Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: streaming input text in dry-run mode #154

Merged
merged 2 commits into from
Oct 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use crate::{
client::localai::LocalAIClient,
config::{Config, SharedConfig},
repl::{ReplyStreamHandler, SharedAbortSignal},
utils::split_text,
};

#[allow(clippy::struct_excessive_bools)]
Expand Down Expand Up @@ -92,7 +93,11 @@ pub trait Client {
tokio::select! {
ret = async {
if self.get_config().read().dry_run {
handler.text(&self.get_config().read().echo_messages(content))?;
let words = split_text(content)?;
for word in words {
tokio::time::sleep(Duration::from_millis(25)).await;
handler.text(&self.get_config().read().echo_messages(&word))?;
}
return Ok(());
}
self.send_message_streaming_inner(content, handler).await
Expand Down
2 changes: 1 addition & 1 deletion src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ impl Config {
if self.dry_run {
if let Ok(messages) = self.build_messages(input) {
let tokens = num_tokens_from_messages(&messages);
println!(">>> The following message consumes {tokens} tokens.");
println!(">>> This message consumes {tokens} tokens. <<<");
}
}
}
Expand Down
8 changes: 8 additions & 0 deletions src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod tiktoken;

use self::tiktoken::cl100k_base;
pub use self::tiktoken::{cl100k_base_singleton, count_tokens, text_to_tokens, tokens_to_text};

use arboard::Clipboard;
Expand Down Expand Up @@ -41,3 +42,10 @@ pub fn copy(src: &str) -> Result<(), arboard::Error> {
let mut clipboard = Clipboard::new()?;
clipboard.set_text(src)
}

pub fn split_text(text: &str) -> Result<Vec<String>, anyhow::Error> {
let bpe = cl100k_base()?;
let tokens = bpe.encode_with_special_tokens(text);
let data: Result<Vec<String>, _> = tokens.into_iter().map(|v| bpe.decode(&[v])).collect();
data
}