thread.rs

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