From af6b1b5d8dfba14d06f29f3eead8fad67a774bf0 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 9 Jan 2024 21:49:15 -0800 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20improve=20prompting=20for?= =?UTF-8?q?=20codebase=20context?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../providers/CodebaseContextProvider.ts | 26 +++++++++----- .../embeddings/OpenAIEmbeddingsProvider.ts | 34 ++++++++++++++----- core/llm/countTokens.ts | 21 +++++++++--- gui/src/components/mainInput/resolveInput.ts | 4 ++- 4 files changed, 62 insertions(+), 23 deletions(-) diff --git a/core/context/providers/CodebaseContextProvider.ts b/core/context/providers/CodebaseContextProvider.ts index 73c67c939..ae983afab 100644 --- a/core/context/providers/CodebaseContextProvider.ts +++ b/core/context/providers/CodebaseContextProvider.ts @@ -44,15 +44,23 @@ class CodebaseContextProvider extends BaseContextProvider { // TODO } - return results.map((r) => { - const name = `${getBasename(r.filepath)} (${r.startLine}-${r.endLine})`; - const description = `${r.filepath} (${r.startLine}-${r.endLine})`; - return { - name, - description, - content: `\`\`\`${name}\n${r.content}\n\`\`\``, - }; - }); + return [ + ...results.map((r) => { + const name = `${getBasename(r.filepath)} (${r.startLine}-${r.endLine})`; + const description = `${r.filepath} (${r.startLine}-${r.endLine})`; + return { + name, + description, + content: `\`\`\`${name}\n${r.content}\n\`\`\``, + }; + }), + { + name: "Instructions", + description: "Instructions", + content: + "Use the above code to answer the following question. You should not reference any files outside of what is shown, unless they are commonly known files, like a .gitignore or package.json. Reference the filenames whenever possible. If there isn't enough information to answer the question, suggest where the user might look to learn more.", + }, + ]; } async load(): Promise {} } diff --git a/core/index/embeddings/OpenAIEmbeddingsProvider.ts b/core/index/embeddings/OpenAIEmbeddingsProvider.ts index 645394be5..c5fe51420 100644 --- a/core/index/embeddings/OpenAIEmbeddingsProvider.ts +++ b/core/index/embeddings/OpenAIEmbeddingsProvider.ts @@ -4,17 +4,35 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider"; class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider { static defaultOptions: Partial | undefined = { apiBase: "https://api.openai.com", + model: "text-embedding-ada-002", }; async embed(chunks: string[]) { - const resp = await fetch(`${this.options.apiBase}/v1/embeddings`, { - method: "POST", - body: JSON.stringify({}), - headers: { - Authorization: `Bearer: ${this.options.apiKey}`, - }, - }); - return [] as number[][]; + let apiBase = this.options.apiBase; + if (apiBase?.endsWith("/")) { + apiBase = apiBase.slice(0, -1); + } + if (apiBase?.endsWith("/v1")) { + apiBase = apiBase.slice(0, -3); + } + + return await Promise.all( + chunks.map(async (chunk) => { + const resp = await fetch(`${apiBase}/v1/embeddings`, { + method: "POST", + body: JSON.stringify({ + input: chunk, + model: this.options.model, + }), + headers: { + Authorization: `Bearer ${this.options.apiKey}`, + "Content-Type": "application/json", + }, + }); + const data = await resp.json(); + return data.data[0].embedding; + }) + ); } } diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 6ded26f1e..014a5a72b 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -62,7 +62,7 @@ function pruneStringFromBottom( return prompt; } - return encoding.decode(tokens.slice(-maxTokens)); + return encoding.decode(tokens.slice(0, maxTokens)); } function pruneStringFromTop( @@ -77,7 +77,7 @@ function pruneStringFromTop( return prompt; } - return encoding.decode(tokens.slice(-maxTokens)); + return encoding.decode(tokens.slice(tokens.length - maxTokens)); } function pruneRawPromptFromTop( @@ -91,6 +91,17 @@ function pruneRawPromptFromTop( return pruneStringFromTop(modelName, maxTokens, prompt); } +function pruneRawPromptFromBottom( + modelName: string, + contextLength: number, + prompt: string, + tokensForCompletion: number +): string { + const maxTokens = + contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; + return pruneStringFromBottom(modelName, maxTokens, prompt); +} + function summarize(message: string): string { return message.substring(0, 100) + "..."; } @@ -121,7 +132,7 @@ function pruneChatHistory( ); for (let i = 0; i < longerThanOneThird.length; i++) { - // Prune line-by-line + // Prune line-by-line from the top const message = longerThanOneThird[i]; let lines = message.content.split("\n"); let tokensRemoved = 0; @@ -130,7 +141,7 @@ function pruneChatHistory( totalTokens > contextLength && lines.length > 0 ) { - const delta = countTokens("\n" + lines.pop()!, modelName); + const delta = countTokens("\n" + lines.shift()!, modelName); tokensRemoved += delta; totalTokens -= delta; } @@ -232,7 +243,7 @@ function compileChatMessages( if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) { throw new Error( - `max_tokens (${maxTokens}) is too close to context_length (${contextLength}), which doesn't leave room for chat. This would cause incoherent responses. Try increasing the context_length parameter of the model in your config file.` + `maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.` ); } diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index c6f517c5a..c8a02492c 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -91,7 +91,9 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] { if (child.type === "text") { text += child.text; } else if (child.type === "mention") { - text += `@${child.attrs.label}`; + if (!["codebase"].includes(child.attrs.id)) { + text += child.attrs.label; + } contextItems.push(child.attrs); } else if (child.type === "slashcommand") { if (typeof slashCommand === "undefined") {