1use std::sync::Arc;
2
3use anyhow::Result;
4use assistant_tool::ToolWorkingSet;
5use chrono::{DateTime, Utc};
6use collections::{BTreeMap, HashMap, HashSet};
7use futures::StreamExt as _;
8use gpui::{App, AppContext, Context, Entity, EventEmitter, SharedString, Task};
9use language_model::{
10 LanguageModel, LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
11 LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
12 LanguageModelToolUseId, MaxMonthlySpendReachedError, MessageContent, PaymentRequiredError,
13 Role, StopReason,
14};
15use project::Project;
16use scripting_tool::{ScriptingSession, ScriptingTool};
17use serde::{Deserialize, Serialize};
18use util::{post_inc, TryFutureExt as _};
19use uuid::Uuid;
20
21use crate::context::{attach_context_to_message, ContextId, ContextSnapshot};
22use crate::thread_store::SavedThread;
23use crate::tool_use::{PendingToolUse, ToolUse, ToolUseState};
24
25#[derive(Debug, Clone, Copy)]
26pub enum RequestKind {
27 Chat,
28 /// Used when summarizing a thread.
29 Summarize,
30}
31
32#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
33pub struct ThreadId(Arc<str>);
34
35impl ThreadId {
36 pub fn new() -> Self {
37 Self(Uuid::new_v4().to_string().into())
38 }
39}
40
41impl std::fmt::Display for ThreadId {
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 write!(f, "{}", self.0)
44 }
45}
46
47#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
48pub struct MessageId(pub(crate) usize);
49
50impl MessageId {
51 fn post_inc(&mut self) -> Self {
52 Self(post_inc(&mut self.0))
53 }
54}
55
56/// A message in a [`Thread`].
57#[derive(Debug, Clone)]
58pub struct Message {
59 pub id: MessageId,
60 pub role: Role,
61 pub text: String,
62}
63
64/// A thread of conversation with the LLM.
65pub struct Thread {
66 id: ThreadId,
67 updated_at: DateTime<Utc>,
68 summary: Option<SharedString>,
69 pending_summary: Task<Option<()>>,
70 messages: Vec<Message>,
71 next_message_id: MessageId,
72 context: BTreeMap<ContextId, ContextSnapshot>,
73 context_by_message: HashMap<MessageId, Vec<ContextId>>,
74 completion_count: usize,
75 pending_completions: Vec<PendingCompletion>,
76 project: Entity<Project>,
77 tools: Arc<ToolWorkingSet>,
78 tool_use: ToolUseState,
79 scripting_session: Entity<ScriptingSession>,
80 scripting_tool_use: ToolUseState,
81}
82
83impl Thread {
84 pub fn new(
85 project: Entity<Project>,
86 tools: Arc<ToolWorkingSet>,
87 cx: &mut Context<Self>,
88 ) -> Self {
89 let scripting_session = cx.new(|cx| ScriptingSession::new(project.clone(), cx));
90
91 Self {
92 id: ThreadId::new(),
93 updated_at: Utc::now(),
94 summary: None,
95 pending_summary: Task::ready(None),
96 messages: Vec::new(),
97 next_message_id: MessageId(0),
98 context: BTreeMap::default(),
99 context_by_message: HashMap::default(),
100 completion_count: 0,
101 pending_completions: Vec::new(),
102 project,
103 tools,
104 tool_use: ToolUseState::new(),
105 scripting_session,
106 scripting_tool_use: ToolUseState::new(),
107 }
108 }
109
110 pub fn from_saved(
111 id: ThreadId,
112 saved: SavedThread,
113 project: Entity<Project>,
114 tools: Arc<ToolWorkingSet>,
115 cx: &mut Context<Self>,
116 ) -> Self {
117 let next_message_id = MessageId(
118 saved
119 .messages
120 .last()
121 .map(|message| message.id.0 + 1)
122 .unwrap_or(0),
123 );
124 let tool_use =
125 ToolUseState::from_saved_messages(&saved.messages, |name| name != ScriptingTool::NAME);
126 let scripting_tool_use =
127 ToolUseState::from_saved_messages(&saved.messages, |name| name == ScriptingTool::NAME);
128 let scripting_session = cx.new(|cx| ScriptingSession::new(project.clone(), cx));
129
130 Self {
131 id,
132 updated_at: saved.updated_at,
133 summary: Some(saved.summary),
134 pending_summary: Task::ready(None),
135 messages: saved
136 .messages
137 .into_iter()
138 .map(|message| Message {
139 id: message.id,
140 role: message.role,
141 text: message.text,
142 })
143 .collect(),
144 next_message_id,
145 context: BTreeMap::default(),
146 context_by_message: HashMap::default(),
147 completion_count: 0,
148 pending_completions: Vec::new(),
149 project,
150 tools,
151 tool_use,
152 scripting_session,
153 scripting_tool_use,
154 }
155 }
156
157 pub fn id(&self) -> &ThreadId {
158 &self.id
159 }
160
161 pub fn is_empty(&self) -> bool {
162 self.messages.is_empty()
163 }
164
165 pub fn updated_at(&self) -> DateTime<Utc> {
166 self.updated_at
167 }
168
169 pub fn touch_updated_at(&mut self) {
170 self.updated_at = Utc::now();
171 }
172
173 pub fn summary(&self) -> Option<SharedString> {
174 self.summary.clone()
175 }
176
177 pub fn summary_or_default(&self) -> SharedString {
178 const DEFAULT: SharedString = SharedString::new_static("New Thread");
179 self.summary.clone().unwrap_or(DEFAULT)
180 }
181
182 pub fn set_summary(&mut self, summary: impl Into<SharedString>, cx: &mut Context<Self>) {
183 self.summary = Some(summary.into());
184 cx.emit(ThreadEvent::SummaryChanged);
185 }
186
187 pub fn message(&self, id: MessageId) -> Option<&Message> {
188 self.messages.iter().find(|message| message.id == id)
189 }
190
191 pub fn messages(&self) -> impl Iterator<Item = &Message> {
192 self.messages.iter()
193 }
194
195 pub fn is_streaming(&self) -> bool {
196 !self.pending_completions.is_empty()
197 }
198
199 pub fn tools(&self) -> &Arc<ToolWorkingSet> {
200 &self.tools
201 }
202
203 pub fn context_for_message(&self, id: MessageId) -> Option<Vec<ContextSnapshot>> {
204 let context = self.context_by_message.get(&id)?;
205 Some(
206 context
207 .into_iter()
208 .filter_map(|context_id| self.context.get(&context_id))
209 .cloned()
210 .collect::<Vec<_>>(),
211 )
212 }
213
214 /// Returns whether all of the tool uses have finished running.
215 pub fn all_tools_finished(&self) -> bool {
216 let mut all_pending_tool_uses = self
217 .tool_use
218 .pending_tool_uses()
219 .into_iter()
220 .chain(self.scripting_tool_use.pending_tool_uses());
221
222 // If the only pending tool uses left are the ones with errors, then that means that we've finished running all
223 // of the pending tools.
224 all_pending_tool_uses.all(|tool_use| tool_use.status.is_error())
225 }
226
227 pub fn tool_uses_for_message(&self, id: MessageId) -> Vec<ToolUse> {
228 self.tool_use.tool_uses_for_message(id)
229 }
230
231 pub fn scripting_tool_uses_for_message(&self, id: MessageId) -> Vec<ToolUse> {
232 self.scripting_tool_use.tool_uses_for_message(id)
233 }
234
235 pub fn tool_results_for_message(&self, id: MessageId) -> Vec<&LanguageModelToolResult> {
236 self.tool_use.tool_results_for_message(id)
237 }
238
239 pub fn scripting_tool_results_for_message(
240 &self,
241 id: MessageId,
242 ) -> Vec<&LanguageModelToolResult> {
243 self.scripting_tool_use.tool_results_for_message(id)
244 }
245
246 pub fn scripting_changed_buffers<'a>(
247 &self,
248 cx: &'a App,
249 ) -> impl ExactSizeIterator<Item = &'a Entity<language::Buffer>> {
250 self.scripting_session.read(cx).changed_buffers()
251 }
252
253 pub fn message_has_tool_results(&self, message_id: MessageId) -> bool {
254 self.tool_use.message_has_tool_results(message_id)
255 }
256
257 pub fn message_has_scripting_tool_results(&self, message_id: MessageId) -> bool {
258 self.scripting_tool_use.message_has_tool_results(message_id)
259 }
260
261 pub fn insert_user_message(
262 &mut self,
263 text: impl Into<String>,
264 context: Vec<ContextSnapshot>,
265 cx: &mut Context<Self>,
266 ) -> MessageId {
267 let message_id = self.insert_message(Role::User, text, cx);
268 let context_ids = context.iter().map(|context| context.id).collect::<Vec<_>>();
269 self.context
270 .extend(context.into_iter().map(|context| (context.id, context)));
271 self.context_by_message.insert(message_id, context_ids);
272 message_id
273 }
274
275 pub fn insert_message(
276 &mut self,
277 role: Role,
278 text: impl Into<String>,
279 cx: &mut Context<Self>,
280 ) -> MessageId {
281 let id = self.next_message_id.post_inc();
282 self.messages.push(Message {
283 id,
284 role,
285 text: text.into(),
286 });
287 self.touch_updated_at();
288 cx.emit(ThreadEvent::MessageAdded(id));
289 id
290 }
291
292 pub fn edit_message(
293 &mut self,
294 id: MessageId,
295 new_role: Role,
296 new_text: String,
297 cx: &mut Context<Self>,
298 ) -> bool {
299 let Some(message) = self.messages.iter_mut().find(|message| message.id == id) else {
300 return false;
301 };
302 message.role = new_role;
303 message.text = new_text;
304 self.touch_updated_at();
305 cx.emit(ThreadEvent::MessageEdited(id));
306 true
307 }
308
309 pub fn delete_message(&mut self, id: MessageId, cx: &mut Context<Self>) -> bool {
310 let Some(index) = self.messages.iter().position(|message| message.id == id) else {
311 return false;
312 };
313 self.messages.remove(index);
314 self.context_by_message.remove(&id);
315 self.touch_updated_at();
316 cx.emit(ThreadEvent::MessageDeleted(id));
317 true
318 }
319
320 /// Returns the representation of this [`Thread`] in a textual form.
321 ///
322 /// This is the representation we use when attaching a thread as context to another thread.
323 pub fn text(&self) -> String {
324 let mut text = String::new();
325
326 for message in &self.messages {
327 text.push_str(match message.role {
328 language_model::Role::User => "User:",
329 language_model::Role::Assistant => "Assistant:",
330 language_model::Role::System => "System:",
331 });
332 text.push('\n');
333
334 text.push_str(&message.text);
335 text.push('\n');
336 }
337
338 text
339 }
340
341 pub fn send_to_model(
342 &mut self,
343 model: Arc<dyn LanguageModel>,
344 request_kind: RequestKind,
345 use_tools: bool,
346 cx: &mut Context<Self>,
347 ) {
348 let mut request = self.to_completion_request(request_kind, cx);
349
350 if use_tools {
351 let mut tools = Vec::new();
352 tools.push(LanguageModelRequestTool {
353 name: ScriptingTool::NAME.into(),
354 description: ScriptingTool::DESCRIPTION.into(),
355 input_schema: ScriptingTool::input_schema(),
356 });
357
358 tools.extend(self.tools().enabled_tools(cx).into_iter().map(|tool| {
359 LanguageModelRequestTool {
360 name: tool.name(),
361 description: tool.description(),
362 input_schema: tool.input_schema(),
363 }
364 }));
365
366 request.tools = tools;
367 }
368
369 self.stream_completion(request, model, cx);
370 }
371
372 pub fn to_completion_request(
373 &self,
374 request_kind: RequestKind,
375 _cx: &App,
376 ) -> LanguageModelRequest {
377 let mut request = LanguageModelRequest {
378 messages: vec![],
379 tools: Vec::new(),
380 stop: Vec::new(),
381 temperature: None,
382 };
383
384 let mut referenced_context_ids = HashSet::default();
385
386 for message in &self.messages {
387 if let Some(context_ids) = self.context_by_message.get(&message.id) {
388 referenced_context_ids.extend(context_ids);
389 }
390
391 let mut request_message = LanguageModelRequestMessage {
392 role: message.role,
393 content: Vec::new(),
394 cache: false,
395 };
396
397 match request_kind {
398 RequestKind::Chat => {
399 self.tool_use
400 .attach_tool_results(message.id, &mut request_message);
401 self.scripting_tool_use
402 .attach_tool_results(message.id, &mut request_message);
403 }
404 RequestKind::Summarize => {
405 // We don't care about tool use during summarization.
406 }
407 }
408
409 if !message.text.is_empty() {
410 request_message
411 .content
412 .push(MessageContent::Text(message.text.clone()));
413 }
414
415 match request_kind {
416 RequestKind::Chat => {
417 self.tool_use
418 .attach_tool_uses(message.id, &mut request_message);
419 self.scripting_tool_use
420 .attach_tool_uses(message.id, &mut request_message);
421 }
422 RequestKind::Summarize => {
423 // We don't care about tool use during summarization.
424 }
425 };
426
427 request.messages.push(request_message);
428 }
429
430 if !referenced_context_ids.is_empty() {
431 let mut context_message = LanguageModelRequestMessage {
432 role: Role::User,
433 content: Vec::new(),
434 cache: false,
435 };
436
437 let referenced_context = referenced_context_ids
438 .into_iter()
439 .filter_map(|context_id| self.context.get(context_id))
440 .cloned();
441 attach_context_to_message(&mut context_message, referenced_context);
442
443 request.messages.push(context_message);
444 }
445
446 request
447 }
448
449 pub fn stream_completion(
450 &mut self,
451 request: LanguageModelRequest,
452 model: Arc<dyn LanguageModel>,
453 cx: &mut Context<Self>,
454 ) {
455 let pending_completion_id = post_inc(&mut self.completion_count);
456
457 let task = cx.spawn(|thread, mut cx| async move {
458 let stream = model.stream_completion(request, &cx);
459 let stream_completion = async {
460 let mut events = stream.await?;
461 let mut stop_reason = StopReason::EndTurn;
462
463 while let Some(event) = events.next().await {
464 let event = event?;
465
466 thread.update(&mut cx, |thread, cx| {
467 match event {
468 LanguageModelCompletionEvent::StartMessage { .. } => {
469 thread.insert_message(Role::Assistant, String::new(), cx);
470 }
471 LanguageModelCompletionEvent::Stop(reason) => {
472 stop_reason = reason;
473 }
474 LanguageModelCompletionEvent::Text(chunk) => {
475 if let Some(last_message) = thread.messages.last_mut() {
476 if last_message.role == Role::Assistant {
477 last_message.text.push_str(&chunk);
478 cx.emit(ThreadEvent::StreamedAssistantText(
479 last_message.id,
480 chunk,
481 ));
482 } else {
483 // If we won't have an Assistant message yet, assume this chunk marks the beginning
484 // of a new Assistant response.
485 //
486 // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
487 // will result in duplicating the text of the chunk in the rendered Markdown.
488 thread.insert_message(Role::Assistant, chunk, cx);
489 };
490 }
491 }
492 LanguageModelCompletionEvent::ToolUse(tool_use) => {
493 if let Some(last_assistant_message) = thread
494 .messages
495 .iter()
496 .rfind(|message| message.role == Role::Assistant)
497 {
498 if tool_use.name.as_ref() == ScriptingTool::NAME {
499 thread
500 .scripting_tool_use
501 .request_tool_use(last_assistant_message.id, tool_use);
502 } else {
503 thread
504 .tool_use
505 .request_tool_use(last_assistant_message.id, tool_use);
506 }
507 }
508 }
509 }
510
511 thread.touch_updated_at();
512 cx.emit(ThreadEvent::StreamedCompletion);
513 cx.notify();
514 })?;
515
516 smol::future::yield_now().await;
517 }
518
519 thread.update(&mut cx, |thread, cx| {
520 thread
521 .pending_completions
522 .retain(|completion| completion.id != pending_completion_id);
523
524 if thread.summary.is_none() && thread.messages.len() >= 2 {
525 thread.summarize(cx);
526 }
527 })?;
528
529 anyhow::Ok(stop_reason)
530 };
531
532 let result = stream_completion.await;
533
534 thread
535 .update(&mut cx, |thread, cx| match result.as_ref() {
536 Ok(stop_reason) => match stop_reason {
537 StopReason::ToolUse => {
538 cx.emit(ThreadEvent::UsePendingTools);
539 }
540 StopReason::EndTurn => {}
541 StopReason::MaxTokens => {}
542 },
543 Err(error) => {
544 if error.is::<PaymentRequiredError>() {
545 cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
546 } else if error.is::<MaxMonthlySpendReachedError>() {
547 cx.emit(ThreadEvent::ShowError(ThreadError::MaxMonthlySpendReached));
548 } else {
549 let error_message = error
550 .chain()
551 .map(|err| err.to_string())
552 .collect::<Vec<_>>()
553 .join("\n");
554 cx.emit(ThreadEvent::ShowError(ThreadError::Message(
555 SharedString::from(error_message.clone()),
556 )));
557 }
558
559 thread.cancel_last_completion();
560 }
561 })
562 .ok();
563 });
564
565 self.pending_completions.push(PendingCompletion {
566 id: pending_completion_id,
567 _task: task,
568 });
569 }
570
571 pub fn summarize(&mut self, cx: &mut Context<Self>) {
572 let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
573 return;
574 };
575 let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
576 return;
577 };
578
579 if !provider.is_authenticated(cx) {
580 return;
581 }
582
583 let mut request = self.to_completion_request(RequestKind::Summarize, cx);
584 request.messages.push(LanguageModelRequestMessage {
585 role: Role::User,
586 content: vec![
587 "Generate a concise 3-7 word title for this conversation, omitting punctuation. Go straight to the title, without any preamble and prefix like `Here's a concise suggestion:...` or `Title:`"
588 .into(),
589 ],
590 cache: false,
591 });
592
593 self.pending_summary = cx.spawn(|this, mut cx| {
594 async move {
595 let stream = model.stream_completion_text(request, &cx);
596 let mut messages = stream.await?;
597
598 let mut new_summary = String::new();
599 while let Some(message) = messages.stream.next().await {
600 let text = message?;
601 let mut lines = text.lines();
602 new_summary.extend(lines.next());
603
604 // Stop if the LLM generated multiple lines.
605 if lines.next().is_some() {
606 break;
607 }
608 }
609
610 this.update(&mut cx, |this, cx| {
611 if !new_summary.is_empty() {
612 this.summary = Some(new_summary.into());
613 }
614
615 cx.emit(ThreadEvent::SummaryChanged);
616 })?;
617
618 anyhow::Ok(())
619 }
620 .log_err()
621 });
622 }
623
624 pub fn use_pending_tools(&mut self, cx: &mut Context<Self>) {
625 let pending_tool_uses = self
626 .tool_use
627 .pending_tool_uses()
628 .into_iter()
629 .filter(|tool_use| tool_use.status.is_idle())
630 .cloned()
631 .collect::<Vec<_>>();
632
633 for tool_use in pending_tool_uses {
634 if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
635 let task = tool.run(tool_use.input, self.project.clone(), cx);
636
637 self.insert_tool_output(tool_use.id.clone(), task, cx);
638 }
639 }
640
641 let pending_scripting_tool_uses = self
642 .scripting_tool_use
643 .pending_tool_uses()
644 .into_iter()
645 .filter(|tool_use| tool_use.status.is_idle())
646 .cloned()
647 .collect::<Vec<_>>();
648
649 for scripting_tool_use in pending_scripting_tool_uses {
650 let task = match ScriptingTool::deserialize_input(scripting_tool_use.input) {
651 Err(err) => Task::ready(Err(err.into())),
652 Ok(input) => {
653 let (script_id, script_task) =
654 self.scripting_session.update(cx, move |session, cx| {
655 session.run_script(input.lua_script, cx)
656 });
657
658 let session = self.scripting_session.clone();
659 cx.spawn(|_, cx| async move {
660 script_task.await;
661
662 let message = session.read_with(&cx, |session, _cx| {
663 // Using a id to get the script output seems impractical.
664 // Why not just include it in the Task result?
665 // This is because we'll later report the script state as it runs,
666 session
667 .get(script_id)
668 .output_message_for_llm()
669 .expect("Script shouldn't still be running")
670 })?;
671
672 Ok(message)
673 })
674 }
675 };
676
677 self.insert_scripting_tool_output(scripting_tool_use.id.clone(), task, cx);
678 }
679 }
680
681 pub fn insert_tool_output(
682 &mut self,
683 tool_use_id: LanguageModelToolUseId,
684 output: Task<Result<String>>,
685 cx: &mut Context<Self>,
686 ) {
687 let insert_output_task = cx.spawn(|thread, mut cx| {
688 let tool_use_id = tool_use_id.clone();
689 async move {
690 let output = output.await;
691 thread
692 .update(&mut cx, |thread, cx| {
693 let pending_tool_use = thread
694 .tool_use
695 .insert_tool_output(tool_use_id.clone(), output);
696
697 cx.emit(ThreadEvent::ToolFinished {
698 tool_use_id,
699 pending_tool_use,
700 });
701 })
702 .ok();
703 }
704 });
705
706 self.tool_use
707 .run_pending_tool(tool_use_id, insert_output_task);
708 }
709
710 pub fn insert_scripting_tool_output(
711 &mut self,
712 tool_use_id: LanguageModelToolUseId,
713 output: Task<Result<String>>,
714 cx: &mut Context<Self>,
715 ) {
716 let insert_output_task = cx.spawn(|thread, mut cx| {
717 let tool_use_id = tool_use_id.clone();
718 async move {
719 let output = output.await;
720 thread
721 .update(&mut cx, |thread, cx| {
722 let pending_tool_use = thread
723 .scripting_tool_use
724 .insert_tool_output(tool_use_id.clone(), output);
725
726 cx.emit(ThreadEvent::ToolFinished {
727 tool_use_id,
728 pending_tool_use,
729 });
730 })
731 .ok();
732 }
733 });
734
735 self.scripting_tool_use
736 .run_pending_tool(tool_use_id, insert_output_task);
737 }
738
739 pub fn send_tool_results_to_model(
740 &mut self,
741 model: Arc<dyn LanguageModel>,
742 cx: &mut Context<Self>,
743 ) {
744 // Insert a user message to contain the tool results.
745 self.insert_user_message(
746 // TODO: Sending up a user message without any content results in the model sending back
747 // responses that also don't have any content. We currently don't handle this case well,
748 // so for now we provide some text to keep the model on track.
749 "Here are the tool results.",
750 Vec::new(),
751 cx,
752 );
753 self.send_to_model(model, RequestKind::Chat, true, cx);
754 }
755
756 /// Cancels the last pending completion, if there are any pending.
757 ///
758 /// Returns whether a completion was canceled.
759 pub fn cancel_last_completion(&mut self) -> bool {
760 if let Some(_last_completion) = self.pending_completions.pop() {
761 true
762 } else {
763 false
764 }
765 }
766}
767
768#[derive(Debug, Clone)]
769pub enum ThreadError {
770 PaymentRequired,
771 MaxMonthlySpendReached,
772 Message(SharedString),
773}
774
775#[derive(Debug, Clone)]
776pub enum ThreadEvent {
777 ShowError(ThreadError),
778 StreamedCompletion,
779 StreamedAssistantText(MessageId, String),
780 MessageAdded(MessageId),
781 MessageEdited(MessageId),
782 MessageDeleted(MessageId),
783 SummaryChanged,
784 UsePendingTools,
785 ToolFinished {
786 #[allow(unused)]
787 tool_use_id: LanguageModelToolUseId,
788 /// The pending tool use that corresponds to this tool.
789 pending_tool_use: Option<PendingToolUse>,
790 },
791}
792
793impl EventEmitter<ThreadEvent> for Thread {}
794
795struct PendingCompletion {
796 id: usize,
797 _task: Task<()>,
798}