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