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