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