-
-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathchat.rs
More file actions
2866 lines (2519 loc) · 97.6 KB
/
chat.rs
File metadata and controls
2866 lines (2519 loc) · 97.6 KB
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! High-level chat API for conversational AI with tool calling support.
//!
//! This module provides an ergonomic interface for chat-based interactions with language models,
//! including support for streaming responses, tool calling, and conversation management.
//!
//! # Quick Start
//!
//! ```
//! use nobodywho::chat::ChatBuilder;
//! use nobodywho::llm;
//! use std::sync::Arc;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let model = Arc::new(llm::get_model("model.gguf", true, None, None)?);
//!
//! let chat = ChatBuilder::new(model)
//! .with_system_prompt(Some("You are a helpful assistant"))
//! .build();
//!
//! let response = chat.ask("Hello!").completed()?;
//! # Ok(())
//! # }
//! ```
//!
use crate::errors::{
ChatWorkerError, ContextSyncError, DecodingError, GenerateResponseError, InitWorkerError,
MultimodalError, RenderError, SayError, SelectTemplateError, SetToolsError, ShiftError,
WrappedResponseError,
};
use crate::llm;
use crate::llm::{GlobalInferenceLockToken, GLOBAL_INFERENCE_LOCK};
use crate::llm::{Worker, WorkerGuard, WriteOutput};
use crate::sampler_config::read_sampler_from_metadata;
use crate::sampler_config::{SamplerConfig, ShiftStep};
use crate::template::{select_template, ChatTemplate, ChatTemplateContext};
use crate::tokenizer::{
find_chunks_prefix_difference, ChunkId, Prompt, PromptPart, Promptable, TokenizerChunk,
TokenizerChunks,
};
use crate::tool_calling::{detect_tool_format, Tool, ToolCall, ToolFormat};
use ahash::AHasher;
use indexmap::IndexMap;
use llama_cpp_2::context::params::LlamaPoolingType;
use llama_cpp_2::mtmd::MtmdBitmap;
use llama_cpp_2::sampling::LlamaSampler;
use llama_cpp_2::token::LlamaToken;
use serde::{Deserialize, Serialize};
use std::cmp::min;
use std::collections::HashSet;
use std::hash::Hasher;
use std::path::PathBuf;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, MutexGuard};
use tracing::{debug, error, info, trace, trace_span};
#[derive(Deserialize, Serialize, Clone, PartialEq, Eq, Debug, Hash)]
pub struct Asset {
pub id: String,
pub path: PathBuf,
}
#[derive(Deserialize, Serialize, Clone, Debug)]
#[serde(tag = "role", rename_all = "lowercase")]
pub enum Message {
User {
content: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
assets: Vec<Asset>,
},
// The optional tool_calls field distinguishes a plain assistant response
// from one that includes tool calls. When tool_calls is Some, the content
// field is typically empty (required by qwen3 chat templates).
// https://github.com/QwenLM/Qwen3/blob/e5a1d326/docs/source/framework/function_call.md
Assistant {
content: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
tool_calls: Option<Vec<ToolCall>>,
},
System {
content: String,
},
Tool {
name: String,
content: String,
},
}
impl Message {
pub fn is_user(&self) -> bool {
matches!(self, Message::User { .. })
}
pub fn is_assistant(&self) -> bool {
matches!(self, Message::Assistant { .. })
}
pub fn is_system(&self) -> bool {
matches!(self, Message::System { .. })
}
pub fn is_tool(&self) -> bool {
matches!(self, Message::Tool { .. })
}
pub fn has_tool_calls(&self) -> bool {
matches!(
self,
Message::Assistant {
tool_calls: Some(_),
..
}
)
}
pub fn content(&self) -> &str {
match self {
Message::User { content, .. }
| Message::Assistant { content, .. }
| Message::System { content, .. }
| Message::Tool { content, .. } => content,
}
}
pub fn assets(&self) -> Vec<Asset> {
match self {
Message::User { assets, .. } => assets.clone(),
_ => vec![],
}
}
pub fn new_user(content: String) -> Self {
Self::User {
content,
assets: vec![],
}
}
pub fn new_assistant(content: String) -> Self {
Self::Assistant {
content,
tool_calls: None,
}
}
pub fn new_system(content: String) -> Self {
Self::System { content }
}
}
// PARALLELISM
///
/// Configuration for chat sessions.
///
/// This struct groups all the settings needed to initialize a chat worker.
/// Use [`ChatBuilder`] for a more ergonomic way to configure these settings.
pub struct ChatConfig {
/// Available tools for the model to use.
pub tools: Vec<Tool>,
/// Context window size.
pub n_ctx: u32,
/// System prompt for the chat session.
pub system_prompt: Option<String>,
/// Variables to add to the chat template context.
pub template_variables: std::collections::HashMap<String, bool>,
/// Sampler configuration for inference.
pub sampler_config: Option<SamplerConfig>,
}
impl Default for ChatConfig {
fn default() -> Self {
Self {
n_ctx: 4096,
template_variables: std::collections::HashMap::new(),
system_prompt: None,
tools: Vec::new(),
sampler_config: None,
}
}
}
/// Builder for creating a [`ChatHandle`] with a fluent API.
///
/// # Example
/// ```
/// use nobodywho::chat::{ChatBuilder};
/// use nobodywho::tool_calling::Tool;
/// use nobodywho::llm;
/// use std::sync::Arc;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let model = Arc::new(llm::get_model("model.gguf", true, None, None)?);
///
/// let my_tool = Tool::new(
/// "example".to_string(),
/// "Example tool".to_string(),
/// serde_json::json!({}),
/// Arc::new(|_| "result".to_string())
/// );
///
/// let chat = ChatBuilder::new(model)
/// .with_context_size(4096)
/// .with_system_prompt(Some("You're a helpful assistant"))
/// .with_tool(my_tool)
/// .build();
/// # Ok(())
/// # }
/// ```
pub struct ChatBuilder {
model: Arc<llm::Model>,
config: ChatConfig,
}
impl ChatBuilder {
/// Create a new chat builder with a model.
pub fn new(model: Arc<llm::Model>) -> Self {
Self {
model,
config: ChatConfig::default(),
}
}
/// Set the context size for the chat session.
pub fn with_context_size(mut self, n_ctx: u32) -> Self {
self.config.n_ctx = n_ctx;
self
}
/// Set the system prompt for the chat session.
pub fn with_system_prompt<S: Into<String>>(mut self, prompt: Option<S>) -> Self {
self.config.system_prompt = prompt.map(|s| s.into());
self
}
/// Add a tool that the model can use.
pub fn with_tool(mut self, tool: Tool) -> Self {
self.config.tools.push(tool);
self
}
/// Add multiple tools that the model can use.
pub fn with_tools(mut self, tools: Vec<Tool>) -> Self {
self.config.tools.extend(tools);
self
}
/// DEPRECATED: Use with_template_variable("enable_thinking", value) instead.
#[deprecated(
since = "0.6.0",
note = "Use with_template_variable(\"enable_thinking\", value) instead"
)]
pub fn with_allow_thinking(mut self, allow_thinking: bool) -> Self {
self.config
.template_variables
.insert("enable_thinking".to_string(), allow_thinking);
self
}
/// Add a single template variable
pub fn with_template_variable(mut self, variable_name: String, value: bool) -> Self {
self.config.template_variables.insert(variable_name, value);
self
}
/// Set the template_variables
pub fn with_template_variables(
mut self,
variables: std::collections::HashMap<String, bool>,
) -> Self {
self.config.template_variables = variables;
self
}
/// Set a custom sampler configuration
pub fn with_sampler(mut self, sampler: SamplerConfig) -> Self {
self.config.sampler_config = Some(sampler);
self
}
/// Build a blocking chat handle and start the background worker.
pub fn build(self) -> Result<ChatHandle, InitWorkerError> {
ChatHandle::new(self.model, self.config)
}
/// Build an async chat handle and start the background worker.
pub fn build_async(self) -> Result<ChatHandleAsync, InitWorkerError> {
ChatHandleAsync::new(self.model, self.config)
}
}
/// Interact with a ChatWorker in a blocking manner.
///
/// Use [`ChatBuilder`] to create a new instance with a fluent API.
pub struct ChatHandle {
guard: WorkerGuard<ChatMsg>,
}
impl ChatHandle {
/// Create a new chat handle directly. Consider using [`ChatBuilder`] for a more ergonomic API.
pub fn new(model: Arc<llm::Model>, config: ChatConfig) -> Result<Self, InitWorkerError> {
let (msg_tx, msg_rx) = std::sync::mpsc::channel();
let (init_tx, init_rx) = std::sync::mpsc::channel::<Result<(), InitWorkerError>>();
let should_stop = Arc::new(AtomicBool::new(false));
let should_stop_clone = Arc::clone(&should_stop);
let join_handle = std::thread::spawn(move || {
let worker = Worker::new_chat_worker(&model, config, should_stop_clone);
let mut worker_state = match worker {
Ok(w) => {
let _ = init_tx.send(Ok(()));
w
}
Err(e) => {
let _ = init_tx.send(Err(e));
return;
}
};
while let Ok(msg) = msg_rx.recv() {
if let Err(e) = process_worker_msg(&mut worker_state, msg) {
return error!("Worker crashed: {e}");
}
}
});
init_rx.recv().map_err(|_| InitWorkerError::NoResponse)??;
Ok(Self {
guard: WorkerGuard::new(msg_tx, join_handle, Some(should_stop)),
})
}
/// Send a message and get a tokio channel
/// TODO: deprecate this in favor of plain `ask` once integrations are updated
pub fn ask_channel(
&self,
prompt: Prompt,
) -> tokio::sync::mpsc::UnboundedReceiver<llm::WriteOutput> {
let (output_tx, output_rx) = tokio::sync::mpsc::unbounded_channel();
self.guard.send(ChatMsg::Ask { prompt, output_tx });
output_rx
}
/// Send a message and collect tokens as they arrive.
///
/// # Example
/// ```
/// # use nobodywho::chat::ChatHandleAsync;
/// # async fn example(chat: &ChatHandleAsync) {
/// let mut stream = chat.ask("Tell me a story");
/// while let Some(token) = stream.next_token().await {
/// print!("{}", token);
/// }
/// # }
/// ```
pub fn ask(&self, prompt: impl Promptable) -> TokenStream {
TokenStream::new(self.ask_channel(prompt.to_prompt()))
}
fn set_and_wait_blocking<F>(&self, make_msg: F) -> Option<()>
where
F: FnOnce(tokio::sync::mpsc::Sender<()>) -> ChatMsg,
{
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(1);
let msg = make_msg(output_tx);
self.guard.send(msg);
// block until processed
output_rx.blocking_recv()
}
/// Reset the chat conversation with a new system prompt and tools.
pub fn reset_chat(
&self,
system_prompt: Option<String>,
tools: Vec<Tool>,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_blocking(|output_tx| ChatMsg::ResetChat {
system_prompt,
tools,
output_tx,
})
.ok_or(crate::errors::SetterError::SetterError("reset_chat".into()))
}
/// Reset the chat conversation history.
pub fn reset_history(&self) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_blocking(|output_tx| ChatMsg::SetChatHistory {
messages: vec![],
output_tx,
})
.ok_or(crate::errors::SetterError::SetterError(
"reset_history".into(),
))
}
/// Update the available tools for the model to use.
pub fn set_tools(&self, tools: Vec<Tool>) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_blocking(|output_tx| ChatMsg::SetTools { tools, output_tx })
.ok_or(crate::errors::SetterError::SetterError("set_tools".into()))
}
/// DEPRECATED: Use set_template_variable("enable_thinking", value) instead.
#[deprecated(note = "Use set_template_variable(\"enable_thinking\", value) instead")]
pub fn set_allow_thinking(
&self,
allow_thinking: bool,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_blocking(|output_tx| ChatMsg::SetThinking {
allow_thinking,
output_tx,
})
.ok_or(crate::errors::SetterError::SetterError(
"set_allow_thinking".into(),
))
}
/// Set a single template variable.
pub fn set_template_variable(
&self,
name: String,
value: bool,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_blocking(|output_tx| ChatMsg::SetTemplateVariable {
name,
value,
output_tx,
})
.ok_or(crate::errors::SetterError::SetterError(
"set_template_variable".into(),
))
}
/// Set all template variables, replacing any existing ones.
pub fn set_template_variables(
&self,
variables: std::collections::HashMap<String, bool>,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_blocking(|output_tx| ChatMsg::SetTemplateVariables {
variables,
output_tx,
})
.ok_or(crate::errors::SetterError::SetterError(
"set_template_variables".into(),
))
}
/// Get all template variables.
pub fn get_template_variables(
&self,
) -> Result<std::collections::HashMap<String, bool>, crate::errors::GetterError> {
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(1);
self.guard.send(ChatMsg::GetTemplateVariables { output_tx });
output_rx
.blocking_recv()
.ok_or(crate::errors::GetterError::GetterError(
"get_template_variables".into(),
))
}
/// Update the sampler configuration for inference.
pub fn set_sampler_config(
&self,
sampler_config: SamplerConfig,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_blocking(|output_tx| ChatMsg::SetSamplerConfig {
sampler_config,
output_tx,
})
.ok_or(crate::errors::SetterError::SetterError(
"set_sampler_config".into(),
))
}
/// Stop the current generation if one is in progress.
pub fn stop_generation(&self) {
self.guard.stop();
}
/// Get the chat history without the system prompt (lower-level API).
pub fn get_chat_history(&self) -> Result<Vec<Message>, crate::errors::GetterError> {
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(1);
self.guard.send(ChatMsg::GetChatHistory { output_tx });
output_rx
.blocking_recv()
.ok_or(crate::errors::GetterError::GetterError(
"get_chat_history".into(),
))
}
/// Set the chat history (lower-level API).
pub fn set_chat_history(
&self,
messages: Vec<Message>,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_blocking(|output_tx| ChatMsg::SetChatHistory {
messages,
output_tx,
})
.ok_or(crate::errors::SetterError::SetterError(
"set_chat_history".into(),
))
}
/// Get the sampler config
pub fn get_sampler_config(&self) -> Result<SamplerConfig, crate::errors::GetterError> {
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(1);
self.guard.send(ChatMsg::GetSamplerConfig { output_tx });
output_rx
.blocking_recv()
.ok_or(crate::errors::GetterError::GetterError(
"get_sampler_config".into(),
))
}
/// Update the system prompt without resetting chat history.
///
/// This modifies the system message while preserving the conversation history.
/// If no system prompt exists, it will be added. If one exists, it will be replaced.
/// The model context is re-synchronized after the change, reusing the KV cache where possible.
///
/// # Arguments
///
/// * `system_prompt` - New system message to guide the model's behavior
///
/// # Errors
///
/// Returns `SetterError` if the system prompt cannot be changed or if context
/// synchronization fails.
///
/// # Examples
///
/// ```no_run
/// # use nobodywho::chat::ChatBuilder;
/// # use nobodywho::llm::get_model;
/// # use std::sync::Arc;
/// # let model = Arc::new(get_model("model.gguf", true, None, None).unwrap());
/// # let chat = ChatBuilder::new(model).build();
/// chat.set_system_prompt(Some("You are a helpful coding assistant.".to_string()))?;
/// # Ok::<(), nobodywho::errors::SetterError>(())
/// ```
pub fn set_system_prompt(
&self,
system_prompt: Option<String>,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_blocking(|output_tx| ChatMsg::SetSystemPrompt {
system_prompt,
output_tx,
})
.ok_or(crate::errors::SetterError::SetterError(
"set_system_prompt".into(),
))
}
/// Get the system prompt
pub fn get_system_prompt(&self) -> Result<Option<String>, crate::errors::GetterError> {
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(1);
self.guard.send(ChatMsg::GetSystemPrompt { output_tx });
output_rx
.blocking_recv()
.ok_or(crate::errors::GetterError::GetterError(
"get_system_prompt".into(),
))
}
}
/// Interact with a ChatWorker in an asynchronous manner.
///
/// Use [`ChatBuilder`] to create a new instance with a fluent API.
#[derive(Clone)]
pub struct ChatHandleAsync {
guard: Arc<WorkerGuard<ChatMsg>>,
}
impl ChatHandleAsync {
/// Create a new chat handle directly. Consider using [`ChatBuilder`] for a more ergonomic API.
pub fn new(model: Arc<llm::Model>, config: ChatConfig) -> Result<Self, InitWorkerError> {
let (msg_tx, msg_rx) = std::sync::mpsc::channel();
let (init_tx, init_rx) = std::sync::mpsc::channel::<Result<(), InitWorkerError>>();
let should_stop = Arc::new(AtomicBool::new(false));
let should_stop_clone = Arc::clone(&should_stop);
let join_handle = std::thread::spawn(move || {
let worker = Worker::new_chat_worker(&model, config, should_stop_clone);
let mut worker_state = match worker {
Ok(w) => {
let _ = init_tx.send(Ok(()));
w
}
Err(e) => {
let _ = init_tx.send(Err(e));
return;
}
};
while let Ok(msg) = msg_rx.recv() {
if let Err(e) = process_worker_msg(&mut worker_state, msg) {
return error!("Worker crashed: {e}");
}
}
});
init_rx.recv().map_err(|_| InitWorkerError::NoResponse)??;
Ok(Self {
guard: Arc::new(WorkerGuard::new(msg_tx, join_handle, Some(should_stop))),
})
}
/// Send a message and get a tokio channel
/// TODO: deprecate this in favor of plain `ask` once integrations are updated
pub fn ask_channel(
&self,
prompt: Prompt,
) -> tokio::sync::mpsc::UnboundedReceiver<llm::WriteOutput> {
let (output_tx, output_rx) = tokio::sync::mpsc::unbounded_channel();
self.guard.send(ChatMsg::Ask { prompt, output_tx });
output_rx
}
/// Send a message and collect tokens as they arrive.
///
/// # Example
/// ```
/// # use nobodywho::chat::ChatHandleAsync;
/// # async fn example(chat: &ChatHandleAsync) {
/// let mut stream = chat.ask("Tell me a story");
/// while let Some(token) = stream.next_token().await {
/// print!("{}", token);
/// }
/// # }
/// ```
pub fn ask(&self, prompt: impl Promptable) -> TokenStreamAsync {
TokenStreamAsync::new(self.ask_channel(prompt.to_prompt()))
}
// internal helper function for async setters
async fn set_and_wait_async<F>(&self, make_msg: F) -> Option<()>
where
F: FnOnce(tokio::sync::mpsc::Sender<()>) -> ChatMsg,
{
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(1);
let msg = make_msg(output_tx);
self.guard.send(msg);
// wait until processed
output_rx.recv().await
}
/// Reset the chat conversation with a new system prompt and tools.
pub async fn reset_chat(
&self,
system_prompt: Option<String>,
tools: Vec<Tool>,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_async(|output_tx| ChatMsg::ResetChat {
system_prompt,
tools,
output_tx,
})
.await
.ok_or(crate::errors::SetterError::SetterError("reset_chat".into()))
}
/// Reset the chat conversation history.
pub async fn reset_history(&self) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_async(|output_tx| ChatMsg::SetChatHistory {
messages: vec![],
output_tx,
})
.await
.ok_or(crate::errors::SetterError::SetterError(
"reset_history".into(),
))
}
/// Update the available tools for the model to use.
pub async fn set_tools(&self, tools: Vec<Tool>) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_async(|output_tx| ChatMsg::SetTools { tools, output_tx })
.await
.ok_or(crate::errors::SetterError::SetterError("set_tools".into()))
}
/// DEPRECATED: Use set_template_variable("enable_thinking", value) instead.
#[deprecated(note = "Use set_template_variable(\"enable_thinking\", value) instead")]
pub async fn set_allow_thinking(
&self,
allow_thinking: bool,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_async(|output_tx| ChatMsg::SetThinking {
allow_thinking,
output_tx,
})
.await
.ok_or(crate::errors::SetterError::SetterError(
"set_allow_thinking".into(),
))
}
/// Set a single template variable.
pub async fn set_template_variable(
&self,
name: String,
value: bool,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_async(|output_tx| ChatMsg::SetTemplateVariable {
name,
value,
output_tx,
})
.await
.ok_or(crate::errors::SetterError::SetterError(
"set_template_variable".into(),
))
}
/// Set all template variables, replacing any existing ones.
pub async fn set_template_variables(
&self,
variables: std::collections::HashMap<String, bool>,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_async(|output_tx| ChatMsg::SetTemplateVariables {
variables,
output_tx,
})
.await
.ok_or(crate::errors::SetterError::SetterError(
"set_template_variables".into(),
))
}
/// Get all template variables.
pub async fn get_template_variables(
&self,
) -> Result<std::collections::HashMap<String, bool>, crate::errors::GetterError> {
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(1);
self.guard.send(ChatMsg::GetTemplateVariables { output_tx });
output_rx
.recv()
.await
.ok_or(crate::errors::GetterError::GetterError(
"get_template_variables".into(),
))
}
/// Update the sampler configuration for inference.
pub async fn set_sampler_config(
&self,
sampler_config: SamplerConfig,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_async(|output_tx| ChatMsg::SetSamplerConfig {
sampler_config,
output_tx,
})
.await
.ok_or(crate::errors::SetterError::SetterError(
"set_sampler_config".into(),
))
}
/// Stop the current generation if one is in progress.
pub fn stop_generation(&self) {
self.guard.stop();
}
/// Get the chat history without the system prompt (lower-level API).
pub async fn get_chat_history(&self) -> Result<Vec<Message>, crate::errors::GetterError> {
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(1);
self.guard.send(ChatMsg::GetChatHistory { output_tx });
output_rx
.recv()
.await
.ok_or(crate::errors::GetterError::GetterError(
"get_chat_history".into(),
))
}
/// Set the chat history (lower-level API).
pub async fn set_chat_history(
&self,
messages: Vec<Message>,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_async(|output_tx| ChatMsg::SetChatHistory {
messages,
output_tx,
})
.await
.ok_or(crate::errors::SetterError::SetterError(
"set_chat_history".into(),
))
}
/// Get the sampler config.
pub async fn get_sampler_config(&self) -> Result<SamplerConfig, crate::errors::GetterError> {
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(1);
self.guard.send(ChatMsg::GetSamplerConfig { output_tx });
output_rx
.recv()
.await
.ok_or(crate::errors::GetterError::GetterError(
"get_sampler_config".into(),
))
}
/// Update the system prompt without resetting chat history.
///
/// This modifies the system message while preserving the conversation history.
/// If no system prompt exists, it will be added. If one exists, it will be replaced.
/// The model context is re-synchronized after the change, reusing the KV cache where possible.
///
/// # Arguments
///
/// * `system_prompt` - New system message to guide the model's behavior
///
/// # Errors
///
/// Returns `SetterError` if the system prompt cannot be changed or if context
/// synchronization fails.
///
/// # Examples
///
/// ```ignore
/// # use nobodywho::chat::ChatBuilder;
/// # use nobodywho::llm::get_model;
/// # use std::sync::Arc;
/// # let model = Arc::new(get_model("model.gguf", true, None, None).unwrap());
/// # let chat = ChatBuilder::new(model).build_async();
/// # chat.set_system_prompt(Some("You are a helpful coding assistant.".to_string())).await?;
/// # Ok::<(), nobodywho::errors::SetterError>(())
/// ```
pub async fn set_system_prompt(
&self,
system_prompt: Option<String>,
) -> Result<(), crate::errors::SetterError> {
self.set_and_wait_async(|output_tx| ChatMsg::SetSystemPrompt {
system_prompt,
output_tx,
})
.await
.ok_or(crate::errors::SetterError::SetterError(
"set_system_prompt".into(),
))
}
/// Get the system prompt
pub async fn get_system_prompt(&self) -> Result<Option<String>, crate::errors::GetterError> {
let (output_tx, mut output_rx) = tokio::sync::mpsc::channel(1);
self.guard.send(ChatMsg::GetSystemPrompt { output_tx });
output_rx
.recv()
.await
.ok_or(crate::errors::GetterError::GetterError(
"get_system_prompt".into(),
))
}
}
/// A stream of tokens from the model.
pub struct TokenStream {
rx: tokio::sync::mpsc::UnboundedReceiver<llm::WriteOutput>,
completed_response: Option<String>,
}
impl TokenStream {
fn new(rx: tokio::sync::mpsc::UnboundedReceiver<llm::WriteOutput>) -> Self {
Self {
rx,
completed_response: None,
}
}
/// Get the next token from the stream.
///
/// Returns `Ok(Some(token))` for each generated token, `Ok(None)` when generation is
/// complete, and `Err(e)` if the worker encountered an error mid-generation.
pub fn next_token(&mut self) -> Result<Option<String>, crate::errors::CompletionError> {
if self.completed_response.is_some() {
return Ok(None);
}
if let Some(output) = self.rx.blocking_recv() {
match output {
llm::WriteOutput::Token(token) => return Ok(Some(token)),
llm::WriteOutput::Done(completed_response) => {
self.completed_response = Some(completed_response);
return Ok(None);
}
llm::WriteOutput::Error(e) => {
return Err(crate::errors::CompletionError::WorkerError(e));
}
}
}
Ok(None)
}
/// Blocks until the entire response is completed. Does not consume the response, so this
/// method is idempotent on success.
pub fn completed(&mut self) -> Result<String, crate::errors::CompletionError> {
loop {
match self.next_token()? {
Some(_) => continue,
None => {
return self
.completed_response
.clone()
.ok_or(crate::errors::CompletionError::WorkerCrashed);
}
}
}
}
}
/// A stream of tokens from the model, async version.
pub struct TokenStreamAsync {
rx: tokio::sync::mpsc::UnboundedReceiver<llm::WriteOutput>,
completed_response: Option<String>,
}
impl TokenStreamAsync {
pub fn new(rx: tokio::sync::mpsc::UnboundedReceiver<llm::WriteOutput>) -> Self {
Self {
rx,
completed_response: None,
}
}
/// Waits for the next token in the stream. Consumes the token when emitted.
///
/// Returns `Ok(Some(token))` for each generated token, `Ok(None)` when generation is
/// complete, and `Err(e)` if the worker encountered an error mid-generation.
pub async fn next_token(&mut self) -> Result<Option<String>, crate::errors::CompletionError> {
if self.completed_response.is_some() {
return Ok(None);
}
if let Some(output) = self.rx.recv().await {
match output {
llm::WriteOutput::Token(token) => return Ok(Some(token)),
llm::WriteOutput::Done(completed_response) => {
self.completed_response = Some(completed_response);
return Ok(None);
}
llm::WriteOutput::Error(e) => {
return Err(crate::errors::CompletionError::WorkerError(e));
}
}
}
Ok(None)
}
/// Waits for the entire response to be completed. Does not consume the response, so this
/// method is idempotent on success.
pub async fn completed(&mut self) -> Result<String, crate::errors::CompletionError> {
loop {
match self.next_token().await? {
Some(_) => continue,
None => {
return self
.completed_response
.clone()
.ok_or(crate::errors::CompletionError::WorkerCrashed);
}
}
}
}
}
enum ChatMsg {
Ask {
prompt: Prompt,
output_tx: tokio::sync::mpsc::UnboundedSender<llm::WriteOutput>,
},
ResetChat {
system_prompt: Option<String>,
tools: Vec<Tool>,
output_tx: tokio::sync::mpsc::Sender<()>,
},
SetTools {
tools: Vec<Tool>,
output_tx: tokio::sync::mpsc::Sender<()>,
},
SetSystemPrompt {
system_prompt: Option<String>,
output_tx: tokio::sync::mpsc::Sender<()>,
},
GetSystemPrompt {
output_tx: tokio::sync::mpsc::Sender<Option<String>>,
},
SetThinking {
allow_thinking: bool,
output_tx: tokio::sync::mpsc::Sender<()>,
},
SetTemplateVariable {
name: String,
value: bool,
output_tx: tokio::sync::mpsc::Sender<()>,
},
SetTemplateVariables {
variables: std::collections::HashMap<String, bool>,
output_tx: tokio::sync::mpsc::Sender<()>,