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