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
353 if self.tools.is_scripting_tool_enabled() {
354 tools.push(LanguageModelRequestTool {
355 name: ScriptingTool::NAME.into(),
356 description: ScriptingTool::DESCRIPTION.into(),
357 input_schema: ScriptingTool::input_schema(),
358 });
359 }
360
361 tools.extend(self.tools().enabled_tools(cx).into_iter().map(|tool| {
362 LanguageModelRequestTool {
363 name: tool.name(),
364 description: tool.description(),
365 input_schema: tool.input_schema(),
366 }
367 }));
368
369 request.tools = tools;
370 }
371
372 self.stream_completion(request, model, cx);
373 }
374
375 pub fn to_completion_request(
376 &self,
377 request_kind: RequestKind,
378 _cx: &App,
379 ) -> LanguageModelRequest {
380 let mut request = LanguageModelRequest {
381 messages: vec![],
382 tools: Vec::new(),
383 stop: Vec::new(),
384 temperature: None,
385 };
386
387 let mut referenced_context_ids = HashSet::default();
388
389 for message in &self.messages {
390 if let Some(context_ids) = self.context_by_message.get(&message.id) {
391 referenced_context_ids.extend(context_ids);
392 }
393
394 let mut request_message = LanguageModelRequestMessage {
395 role: message.role,
396 content: Vec::new(),
397 cache: false,
398 };
399
400 match request_kind {
401 RequestKind::Chat => {
402 self.tool_use
403 .attach_tool_results(message.id, &mut request_message);
404 self.scripting_tool_use
405 .attach_tool_results(message.id, &mut request_message);
406 }
407 RequestKind::Summarize => {
408 // We don't care about tool use during summarization.
409 }
410 }
411
412 if !message.text.is_empty() {
413 request_message
414 .content
415 .push(MessageContent::Text(message.text.clone()));
416 }
417
418 match request_kind {
419 RequestKind::Chat => {
420 self.tool_use
421 .attach_tool_uses(message.id, &mut request_message);
422 self.scripting_tool_use
423 .attach_tool_uses(message.id, &mut request_message);
424 }
425 RequestKind::Summarize => {
426 // We don't care about tool use during summarization.
427 }
428 };
429
430 request.messages.push(request_message);
431 }
432
433 if !referenced_context_ids.is_empty() {
434 let mut context_message = LanguageModelRequestMessage {
435 role: Role::User,
436 content: Vec::new(),
437 cache: false,
438 };
439
440 let referenced_context = referenced_context_ids
441 .into_iter()
442 .filter_map(|context_id| self.context.get(context_id))
443 .cloned();
444 attach_context_to_message(&mut context_message, referenced_context);
445
446 request.messages.push(context_message);
447 }
448
449 request
450 }
451
452 pub fn stream_completion(
453 &mut self,
454 request: LanguageModelRequest,
455 model: Arc<dyn LanguageModel>,
456 cx: &mut Context<Self>,
457 ) {
458 let pending_completion_id = post_inc(&mut self.completion_count);
459
460 let task = cx.spawn(|thread, mut cx| async move {
461 let stream = model.stream_completion(request, &cx);
462 let stream_completion = async {
463 let mut events = stream.await?;
464 let mut stop_reason = StopReason::EndTurn;
465
466 while let Some(event) = events.next().await {
467 let event = event?;
468
469 thread.update(&mut cx, |thread, cx| {
470 match event {
471 LanguageModelCompletionEvent::StartMessage { .. } => {
472 thread.insert_message(Role::Assistant, String::new(), cx);
473 }
474 LanguageModelCompletionEvent::Stop(reason) => {
475 stop_reason = reason;
476 }
477 LanguageModelCompletionEvent::Text(chunk) => {
478 if let Some(last_message) = thread.messages.last_mut() {
479 if last_message.role == Role::Assistant {
480 last_message.text.push_str(&chunk);
481 cx.emit(ThreadEvent::StreamedAssistantText(
482 last_message.id,
483 chunk,
484 ));
485 } else {
486 // If we won't have an Assistant message yet, assume this chunk marks the beginning
487 // of a new Assistant response.
488 //
489 // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
490 // will result in duplicating the text of the chunk in the rendered Markdown.
491 thread.insert_message(Role::Assistant, chunk, cx);
492 };
493 }
494 }
495 LanguageModelCompletionEvent::ToolUse(tool_use) => {
496 if let Some(last_assistant_message) = thread
497 .messages
498 .iter()
499 .rfind(|message| message.role == Role::Assistant)
500 {
501 if tool_use.name.as_ref() == ScriptingTool::NAME {
502 thread
503 .scripting_tool_use
504 .request_tool_use(last_assistant_message.id, tool_use);
505 } else {
506 thread
507 .tool_use
508 .request_tool_use(last_assistant_message.id, tool_use);
509 }
510 }
511 }
512 }
513
514 thread.touch_updated_at();
515 cx.emit(ThreadEvent::StreamedCompletion);
516 cx.notify();
517 })?;
518
519 smol::future::yield_now().await;
520 }
521
522 thread.update(&mut cx, |thread, cx| {
523 thread
524 .pending_completions
525 .retain(|completion| completion.id != pending_completion_id);
526
527 if thread.summary.is_none() && thread.messages.len() >= 2 {
528 thread.summarize(cx);
529 }
530 })?;
531
532 anyhow::Ok(stop_reason)
533 };
534
535 let result = stream_completion.await;
536
537 thread
538 .update(&mut cx, |thread, cx| match result.as_ref() {
539 Ok(stop_reason) => match stop_reason {
540 StopReason::ToolUse => {
541 cx.emit(ThreadEvent::UsePendingTools);
542 }
543 StopReason::EndTurn => {}
544 StopReason::MaxTokens => {}
545 },
546 Err(error) => {
547 if error.is::<PaymentRequiredError>() {
548 cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
549 } else if error.is::<MaxMonthlySpendReachedError>() {
550 cx.emit(ThreadEvent::ShowError(ThreadError::MaxMonthlySpendReached));
551 } else {
552 let error_message = error
553 .chain()
554 .map(|err| err.to_string())
555 .collect::<Vec<_>>()
556 .join("\n");
557 cx.emit(ThreadEvent::ShowError(ThreadError::Message(
558 SharedString::from(error_message.clone()),
559 )));
560 }
561
562 thread.cancel_last_completion();
563 }
564 })
565 .ok();
566 });
567
568 self.pending_completions.push(PendingCompletion {
569 id: pending_completion_id,
570 _task: task,
571 });
572 }
573
574 pub fn summarize(&mut self, cx: &mut Context<Self>) {
575 let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
576 return;
577 };
578 let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
579 return;
580 };
581
582 if !provider.is_authenticated(cx) {
583 return;
584 }
585
586 let mut request = self.to_completion_request(RequestKind::Summarize, cx);
587 request.messages.push(LanguageModelRequestMessage {
588 role: Role::User,
589 content: vec![
590 "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:`"
591 .into(),
592 ],
593 cache: false,
594 });
595
596 self.pending_summary = cx.spawn(|this, mut cx| {
597 async move {
598 let stream = model.stream_completion_text(request, &cx);
599 let mut messages = stream.await?;
600
601 let mut new_summary = String::new();
602 while let Some(message) = messages.stream.next().await {
603 let text = message?;
604 let mut lines = text.lines();
605 new_summary.extend(lines.next());
606
607 // Stop if the LLM generated multiple lines.
608 if lines.next().is_some() {
609 break;
610 }
611 }
612
613 this.update(&mut cx, |this, cx| {
614 if !new_summary.is_empty() {
615 this.summary = Some(new_summary.into());
616 }
617
618 cx.emit(ThreadEvent::SummaryChanged);
619 })?;
620
621 anyhow::Ok(())
622 }
623 .log_err()
624 });
625 }
626
627 pub fn use_pending_tools(&mut self, cx: &mut Context<Self>) {
628 let pending_tool_uses = self
629 .tool_use
630 .pending_tool_uses()
631 .into_iter()
632 .filter(|tool_use| tool_use.status.is_idle())
633 .cloned()
634 .collect::<Vec<_>>();
635
636 for tool_use in pending_tool_uses {
637 if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
638 let task = tool.run(tool_use.input, self.project.clone(), cx);
639
640 self.insert_tool_output(tool_use.id.clone(), task, cx);
641 }
642 }
643
644 let pending_scripting_tool_uses = self
645 .scripting_tool_use
646 .pending_tool_uses()
647 .into_iter()
648 .filter(|tool_use| tool_use.status.is_idle())
649 .cloned()
650 .collect::<Vec<_>>();
651
652 for scripting_tool_use in pending_scripting_tool_uses {
653 let task = match ScriptingTool::deserialize_input(scripting_tool_use.input) {
654 Err(err) => Task::ready(Err(err.into())),
655 Ok(input) => {
656 let (script_id, script_task) =
657 self.scripting_session.update(cx, move |session, cx| {
658 session.run_script(input.lua_script, cx)
659 });
660
661 let session = self.scripting_session.clone();
662 cx.spawn(|_, cx| async move {
663 script_task.await;
664
665 let message = session.read_with(&cx, |session, _cx| {
666 // Using a id to get the script output seems impractical.
667 // Why not just include it in the Task result?
668 // This is because we'll later report the script state as it runs,
669 session
670 .get(script_id)
671 .output_message_for_llm()
672 .expect("Script shouldn't still be running")
673 })?;
674
675 Ok(message)
676 })
677 }
678 };
679
680 self.insert_scripting_tool_output(scripting_tool_use.id.clone(), task, cx);
681 }
682 }
683
684 pub fn insert_tool_output(
685 &mut self,
686 tool_use_id: LanguageModelToolUseId,
687 output: Task<Result<String>>,
688 cx: &mut Context<Self>,
689 ) {
690 let insert_output_task = cx.spawn(|thread, mut cx| {
691 let tool_use_id = tool_use_id.clone();
692 async move {
693 let output = output.await;
694 thread
695 .update(&mut cx, |thread, cx| {
696 let pending_tool_use = thread
697 .tool_use
698 .insert_tool_output(tool_use_id.clone(), output);
699
700 cx.emit(ThreadEvent::ToolFinished {
701 tool_use_id,
702 pending_tool_use,
703 });
704 })
705 .ok();
706 }
707 });
708
709 self.tool_use
710 .run_pending_tool(tool_use_id, insert_output_task);
711 }
712
713 pub fn insert_scripting_tool_output(
714 &mut self,
715 tool_use_id: LanguageModelToolUseId,
716 output: Task<Result<String>>,
717 cx: &mut Context<Self>,
718 ) {
719 let insert_output_task = cx.spawn(|thread, mut cx| {
720 let tool_use_id = tool_use_id.clone();
721 async move {
722 let output = output.await;
723 thread
724 .update(&mut cx, |thread, cx| {
725 let pending_tool_use = thread
726 .scripting_tool_use
727 .insert_tool_output(tool_use_id.clone(), output);
728
729 cx.emit(ThreadEvent::ToolFinished {
730 tool_use_id,
731 pending_tool_use,
732 });
733 })
734 .ok();
735 }
736 });
737
738 self.scripting_tool_use
739 .run_pending_tool(tool_use_id, insert_output_task);
740 }
741
742 pub fn send_tool_results_to_model(
743 &mut self,
744 model: Arc<dyn LanguageModel>,
745 cx: &mut Context<Self>,
746 ) {
747 // Insert a user message to contain the tool results.
748 self.insert_user_message(
749 // TODO: Sending up a user message without any content results in the model sending back
750 // responses that also don't have any content. We currently don't handle this case well,
751 // so for now we provide some text to keep the model on track.
752 "Here are the tool results.",
753 Vec::new(),
754 cx,
755 );
756 self.send_to_model(model, RequestKind::Chat, true, cx);
757 }
758
759 /// Cancels the last pending completion, if there are any pending.
760 ///
761 /// Returns whether a completion was canceled.
762 pub fn cancel_last_completion(&mut self) -> bool {
763 if let Some(_last_completion) = self.pending_completions.pop() {
764 true
765 } else {
766 false
767 }
768 }
769}
770
771#[derive(Debug, Clone)]
772pub enum ThreadError {
773 PaymentRequired,
774 MaxMonthlySpendReached,
775 Message(SharedString),
776}
777
778#[derive(Debug, Clone)]
779pub enum ThreadEvent {
780 ShowError(ThreadError),
781 StreamedCompletion,
782 StreamedAssistantText(MessageId, String),
783 MessageAdded(MessageId),
784 MessageEdited(MessageId),
785 MessageDeleted(MessageId),
786 SummaryChanged,
787 UsePendingTools,
788 ToolFinished {
789 #[allow(unused)]
790 tool_use_id: LanguageModelToolUseId,
791 /// The pending tool use that corresponds to this tool.
792 pending_tool_use: Option<PendingToolUse>,
793 },
794}
795
796impl EventEmitter<ThreadEvent> for Thread {}
797
798struct PendingCompletion {
799 id: usize,
800 _task: Task<()>,
801}