Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

catchup with main

KCaverlyd2e769027ac9
diff --cc crates/assistant/src/assistant_panel.rs
index 17e5c161c72,b1c6038602b..e8edf70498c
--- a/crates/assistant/src/assistant_panel.rs
+++ b/crates/assistant/src/assistant_panel.rs
@@@ -1,7 -1,7 +1,7 @@@
use crate::{
assistant_settings::{AssistantDockPosition, AssistantSettings, OpenAIModel},
codegen::{self, Codegen, CodegenKind},
-- prompts::generate_content_prompt,
++ prompts::{generate_content_prompt, PromptCodeSnippet},
MessageId, MessageMetadata, MessageStatus, Role, SavedConversation, SavedConversationMetadata,
SavedMessage,
};
@@@ -635,39 -593,7 +649,41 @@@ impl AssistantPanel
let codegen_kind = codegen.read(cx).kind().clone();
let user_prompt = user_prompt.to_string();
- let mut messages = Vec::new();
+ let snippets = if retrieve_context {
+ let Some(project) = project.upgrade(cx) else {
+ return;
+ };
+
+ let search_results = if let Some(semantic_index) = self.semantic_index.clone() {
+ let search_results = semantic_index.update(cx, |this, cx| {
+ this.search_project(project, user_prompt.to_string(), 10, vec![], vec![], cx)
+ });
+
+ cx.background()
+ .spawn(async move { search_results.await.unwrap_or_default() })
+ } else {
+ Task::ready(Vec::new())
+ };
+
+ let snippets = cx.spawn(|_, cx| async move {
+ let mut snippets = Vec::new();
+ for result in search_results.await {
- snippets.push(result.buffer.read_with(&cx, |buffer, _| {
- buffer
- .snapshot()
- .text_for_range(result.range)
- .collect::<String>()
- }));
++ snippets.push(PromptCodeSnippet::new(result, &cx));
++
++ // snippets.push(result.buffer.read_with(&cx, |buffer, _| {
++ // buffer
++ // .snapshot()
++ // .text_for_range(result.range)
++ // .collect::<String>()
++ // }));
+ }
+ snippets
+ });
+ snippets
+ } else {
+ Task::ready(Vec::new())
+ };
+
let mut model = settings::get::<AssistantSettings>(cx)
.default_open_ai_model
.clone();
diff --cc crates/assistant/src/prompts.rs
index a3a2be1a00b,d326a7f4454..3550c4223ca
--- a/crates/assistant/src/prompts.rs
+++ b/crates/assistant/src/prompts.rs
@@@ -1,10 -1,10 +1,65 @@@
use crate::codegen::CodegenKind;
--use language::{BufferSnapshot, OffsetRangeExt, ToOffset};
++use gpui::{AppContext, AsyncAppContext};
++use language::{BufferSnapshot, Language, OffsetRangeExt, ToOffset};
++use semantic_index::SearchResult;
++use std::borrow::Cow;
use std::cmp::{self, Reverse};
use std::fmt::Write;
use std::ops::Range;
++use std::path::PathBuf;
++use std::sync::Arc;
+use tiktoken_rs::ChatCompletionRequestMessage;
+
++pub struct PromptCodeSnippet {
++ path: Option<PathBuf>,
++ language_name: Option<String>,
++ content: String,
++}
++
++impl PromptCodeSnippet {
++ pub fn new(search_result: SearchResult, cx: &AsyncAppContext) -> Self {
++ let (content, language_name, file_path) =
++ search_result.buffer.read_with(cx, |buffer, cx| {
++ let snapshot = buffer.snapshot();
++ let content = snapshot
++ .text_for_range(search_result.range.clone())
++ .collect::<String>();
++
++ let language_name = buffer
++ .language()
++ .and_then(|language| Some(language.name().to_string()));
++
++ let language = buffer.language();
++ let file_path = buffer
++ .file()
++ .and_then(|file| Some(file.path().to_path_buf()));
++
++ (content, language_name, file_path)
++ });
++
++ PromptCodeSnippet {
++ path: file_path,
++ language_name,
++ content,
++ }
++ }
++}
++
++impl ToString for PromptCodeSnippet {
++ fn to_string(&self) -> String {
++ let path = self
++ .path
++ .as_ref()
++ .and_then(|path| Some(path.to_string_lossy().to_string()))
++ .unwrap_or("".to_string());
++ let language_name = self.language_name.clone().unwrap_or("".to_string());
++ let content = self.content.clone();
++
++ format!("The below code snippet may be relevant from file: {path}\n```{language_name}\n{content}\n```")
++ }
++}
+
+ #[allow(dead_code)]
fn summarize(buffer: &BufferSnapshot, selected_range: Range<impl ToOffset>) -> String {
#[derive(Debug)]
struct Match {
@@@ -121,114 -121,82 +176,132 @@@ pub fn generate_content_prompt
buffer: &BufferSnapshot,
range: Range<impl ToOffset>,
kind: CodegenKind,
- search_results: Vec<String>,
++ search_results: Vec<PromptCodeSnippet>,
+ model: &str,
) -> String {
+ const MAXIMUM_SNIPPET_TOKEN_COUNT: usize = 500;
+ const RESERVED_TOKENS_FOR_GENERATION: usize = 1000;
+
+ let mut prompts = Vec::new();
+ let range = range.to_offset(buffer);
- let mut prompt = String::new();
// General Preamble
if let Some(language_name) = language_name {
- writeln!(prompt, "You're an expert {language_name} engineer.\n").unwrap();
+ prompts.push(format!("You're an expert {language_name} engineer.\n"));
} else {
- writeln!(prompt, "You're an expert engineer.\n").unwrap();
+ prompts.push("You're an expert engineer.\n".to_string());
}
+ // Snippets
+ let mut snippet_position = prompts.len() - 1;
+
- let outline = summarize(buffer, range);
- prompts.push("The file you are currently working on has the following outline:".to_string());
+ let mut content = String::new();
+ content.extend(buffer.text_for_range(0..range.start));
+ if range.start == range.end {
+ content.push_str("<|START|>");
+ } else {
+ content.push_str("<|START|");
+ }
+ content.extend(buffer.text_for_range(range.clone()));
+ if range.start != range.end {
+ content.push_str("|END|>");
+ }
+ content.extend(buffer.text_for_range(range.end..buffer.len()));
+
- writeln!(
- prompt,
- "The file you are currently working on has the following content:"
- )
- .unwrap();
++ prompts.push("The file you are currently working on has the following content:\n".to_string());
++
if let Some(language_name) = language_name {
let language_name = language_name.to_lowercase();
- prompts.push(format!("```{language_name}\n{outline}\n```"));
- writeln!(prompt, "```{language_name}\n{content}\n```").unwrap();
++ prompts.push(format!("```{language_name}\n{content}\n```"));
} else {
- prompts.push(format!("```\n{outline}\n```"));
- writeln!(prompt, "```\n{content}\n```").unwrap();
++ prompts.push(format!("```\n{content}\n```"));
}
match kind {
CodegenKind::Generate { position: _ } => {
- writeln!(prompt, "In particular, the user's cursor is current on the '<|START|>' span in the above outline, with no text selected.").unwrap();
- writeln!(
- prompt,
- "Assume the cursor is located where the `<|START|` marker is."
- )
- .unwrap();
- writeln!(
- prompt,
+ prompts.push("In particular, the user's cursor is currently on the '<|START|>' span in the above outline, with no text selected.".to_string());
+ prompts
+ .push("Assume the cursor is located where the `<|START|` marker is.".to_string());
+ prompts.push(
"Text can't be replaced, so assume your answer will be inserted at the cursor."
- )
- .unwrap();
- writeln!(
- prompt,
+ .to_string(),
+ );
+ prompts.push(format!(
"Generate text based on the users prompt: {user_prompt}"
- )
- .unwrap();
+ ));
}
CodegenKind::Transform { range: _ } => {
- writeln!(prompt, "In particular, the user has selected a section of the text between the '<|START|' and '|END|>' spans.").unwrap();
- writeln!(
- prompt,
- "Modify the users code selected text based upon the users prompt: {user_prompt}"
- )
- .unwrap();
- writeln!(
- prompt,
- "You MUST reply with only the adjusted code (within the '<|START|' and '|END|>' spans), not the entire file."
- )
- .unwrap();
+ prompts.push("In particular, the user has selected a section of the text between the '<|START|' and '|END|>' spans.".to_string());
+ prompts.push(format!(
- "Modify the users code selected text based upon the users prompt: {user_prompt}"
++ "Modify the users code selected text based upon the users prompt: '{user_prompt}'"
+ ));
+ prompts.push("You MUST reply with only the adjusted code (within the '<|START|' and '|END|>' spans), not the entire file.".to_string());
}
}
if let Some(language_name) = language_name {
- prompts.push(format!("Your answer MUST always be valid {language_name}"));
- writeln!(prompt, "Your answer MUST always be valid {language_name}").unwrap();
++ prompts.push(format!(
++ "Your answer MUST always and only be valid {language_name}"
++ ));
+ }
- prompts.push("Always wrap your response in a Markdown codeblock".to_string());
+ prompts.push("Never make remarks about the output.".to_string());
++ prompts.push("DO NOT return any text, except the generated code.".to_string());
++ prompts.push("DO NOT wrap your text in a Markdown block".to_string());
+
+ let current_messages = [ChatCompletionRequestMessage {
+ role: "user".to_string(),
+ content: Some(prompts.join("\n")),
+ function_call: None,
+ name: None,
+ }];
+
+ let mut remaining_token_count = if let Ok(current_token_count) =
+ tiktoken_rs::num_tokens_from_messages(model, &current_messages)
+ {
+ let max_token_count = tiktoken_rs::model::get_context_size(model);
+ let intermediate_token_count = max_token_count - current_token_count;
+
+ if intermediate_token_count < RESERVED_TOKENS_FOR_GENERATION {
+ 0
+ } else {
+ intermediate_token_count - RESERVED_TOKENS_FOR_GENERATION
+ }
+ } else {
+ // If tiktoken fails to count token count, assume we have no space remaining.
+ 0
+ };
+
+ // TODO:
+ // - add repository name to snippet
+ // - add file path
+ // - add language
+ if let Ok(encoding) = tiktoken_rs::get_bpe_from_model(model) {
+ let mut template = "You are working inside a large repository, here are a few code snippets that may be useful";
+
+ for search_result in search_results {
+ let mut snippet_prompt = template.to_string();
- writeln!(snippet_prompt, "```\n{search_result}\n```").unwrap();
++ let snippet = search_result.to_string();
++ writeln!(snippet_prompt, "```\n{snippet}\n```").unwrap();
+
+ let token_count = encoding
+ .encode_with_special_tokens(snippet_prompt.as_str())
+ .len();
+ if token_count <= remaining_token_count {
+ if token_count < MAXIMUM_SNIPPET_TOKEN_COUNT {
+ prompts.insert(snippet_position, snippet_prompt);
+ snippet_position += 1;
+ remaining_token_count -= token_count;
+ // If you have already added the template to the prompt, remove the template.
+ template = "";
+ }
+ } else {
+ break;
+ }
+ }
}
- writeln!(prompt, "Always wrap your response in a Markdown codeblock").unwrap();
- writeln!(prompt, "Never make remarks about the output.").unwrap();
+ let prompt = prompts.join("\n");
+ println!("PROMPT: {:?}", prompt);
prompt
}