renderChatMessage, return ContextItem[] from tools, and other refactoring

This commit is contained in:
Nate 2024-11-21 18:31:50 -08:00
parent a7cd760c3d
commit ee7bea7c19
53 changed files with 498 additions and 319 deletions

View file

@ -1,6 +1,6 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { renderChatMessage } from "../util/messageContent";
import SlashCommands from "./slash";
@ -29,7 +29,8 @@ export function slashFromCustomCommand(
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
const message = messages[i];
const { role, content } = message;
if (role !== "user") {
continue;
}
@ -41,7 +42,7 @@ export function slashFromCustomCommand(
)
) {
messages[i] = {
...messages[i],
...message,
content: content.map((part) => {
return part.text?.startsWith(`/${customCommand.name}`)
? { ...part, text: promptUserInput }
@ -53,13 +54,16 @@ export function slashFromCustomCommand(
typeof content === "string" &&
content.startsWith(`/${customCommand.name}`)
) {
messages[i] = { ...messages[i], content: promptUserInput };
messages[i] = { ...message, content: promptUserInput };
break;
}
}
for await (const chunk of llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};

View file

@ -1,19 +0,0 @@
import { SlashCommand } from "../../";
import EditSlashCommand from "./edit";
const CommentSlashCommand: SlashCommand = {
name: "comment",
description: "Write comments for highlighted code",
run: async function* (sdk) {
for await (const update of EditSlashCommand.run({
...sdk,
input:
"Write comments for this code. Do not change anything about the code itself.",
})) {
yield update;
}
},
};
export default CommentSlashCommand;

View file

@ -1,5 +1,5 @@
import { SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/images.js";
import { renderChatMessage } from "../../util/messageContent.js";
const CommitMessageCommand: SlashCommand = {
name: "commit",
@ -14,10 +14,11 @@ const CommitMessageCommand: SlashCommand = {
}
const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
], new AbortController().signal)) {
yield stripImages(chunk.content);
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};

View file

@ -1,6 +1,6 @@
import { ChatMessage, SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/images.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { renderChatMessage } from "../../util/messageContent.js";
const PROMPT = (
input: string,
@ -30,7 +30,8 @@ const DraftIssueCommand: SlashCommand = {
return;
}
let title = await llm.complete(
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal,
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
new AbortController().signal,
{ maxTokens: 20 },
);
@ -43,9 +44,12 @@ const DraftIssueCommand: SlashCommand = {
{ role: "user", content: PROMPT(input, title) },
];
for await (const chunk of llm.streamChat(messages, new AbortController().signal)) {
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
)) {
body += chunk.content;
yield stripImages(chunk.content);
yield renderChatMessage(chunk);
}
const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent(

View file

@ -1,5 +1,5 @@
import { SlashCommand } from "../..";
import { stripImages } from "../../llm/images";
import { renderChatMessage } from "../../util/messageContent";
const MultiFileEditSlashCommand: SlashCommand = {
name: "multifile-edit",
@ -39,8 +39,11 @@ const MultiFileEditSlashCommand: SlashCommand = {
const content = createPrompt(filesToEditStr, additionalContextStr, input);
for await (const chunk of llm.streamChat([{ role: "user", content }], new AbortController().signal)) {
yield stripImages(chunk.content);
for await (const chunk of llm.streamChat(
[{ role: "user", content }],
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};

View file

@ -9,7 +9,7 @@ import {
defaultIgnoreFile,
gitIgArrayFromFile,
} from "../../indexing/ignore";
import { stripImages } from "../../llm/images";
import { renderChatMessage } from "../../util/messageContent";
const LANGUAGE_DEP_MGMT_FILENAMES = [
"package.json", // JavaScript (Node.js)
@ -45,10 +45,11 @@ const OnboardSlashCommand: SlashCommand = {
const context = await gatherProjectContext(workspaceDir, ide);
const prompt = createOnboardingPrompt(context);
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
], new AbortController().signal)) {
yield stripImages(chunk.content);
for await (const chunk of llm.streamChat(
[{ role: "user", content: prompt }],
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};

View file

@ -1,5 +1,5 @@
import { ChatMessage, SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/images.js";
import { renderChatMessage } from "../../util/messageContent.js";
const prompt = `
Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:
@ -43,10 +43,11 @@ const ReviewMessageCommand: SlashCommand = {
const content = `${prompt} \r\n ${reviewText}`;
for await (const chunk of llm.streamChat([
{ role: "user", content: content },
], new AbortController().signal)) {
yield stripImages(chunk.content);
for await (const chunk of llm.streamChat(
[{ role: "user", content: content }],
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};

View file

@ -4,7 +4,7 @@ import path from "path";
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
import { SlashCommand } from "../../index.js";
import { stripImages } from "../../llm/images.js";
import { renderChatMessage } from "../../util/messageContent.js";
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
function getOffsetDatetime(date: Date): Date {
@ -48,7 +48,7 @@ const ShareSlashCommand: SlashCommand = {
// message in the chat history, this will omit it
for (const msg of history.slice(0, history.length - 1)) {
let msgText = msg.content;
msgText = stripImages(msg.content);
msgText = renderChatMessage(msg);
if (msg.role === "user" && msgText.search("```") > -1) {
msgText = reformatCodeBlocks(msgText);

View file

@ -4,9 +4,9 @@ import Handlebars from "handlebars";
import * as YAML from "yaml";
import { walkDir } from "../indexing/walkDir";
import { stripImages } from "../llm/images";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { getBasename } from "../util/index";
import { renderChatMessage } from "../util/messageContent";
import type {
ChatMessage,
@ -125,8 +125,11 @@ export function slashCommandFromPromptFile(
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
context.llm.systemMessage = originalSystemMessage;
@ -233,7 +236,8 @@ function updateChatHistory(
const messages = [...history];
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
const message = messages[i];
const { role, content } = message;
if (role !== "user") {
continue;
}
@ -251,7 +255,7 @@ function updateChatHistory(
typeof content === "string" &&
content.startsWith(`/${commandName}`)
) {
messages[i] = { ...messages[i], content: renderedPrompt };
messages[i] = { ...message, content: renderedPrompt };
break;
}
}

View file

@ -1,7 +1,7 @@
import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
import { getModelByRole } from "../../config/util";
import { stripImages } from "../../llm/images";
import generateRepoMap from "../../util/generateRepoMap";
import { renderChatMessage } from "../../util/messageContent";
const SUPPORTED_MODEL_TITLE_FAMILIES = [
"claude-3",
@ -58,11 +58,14 @@ After this, your response should begin with a <results> tag, followed by a list
This is the question that you should select relevant files for: "${input}"`;
const response = await llm.chat([
{ role: "user", content: prompt },
{ role: "assistant", content: "<reasoning>" },
], new AbortController().signal);
const content = stripImages(response.content);
const response = await llm.chat(
[
{ role: "user", content: prompt },
{ role: "assistant", content: "<reasoning>" },
],
new AbortController().signal,
);
const content = renderChatMessage(response);
console.debug("Repo map retrieval response: ", content);
if (!content.includes("\n")) {

View file

@ -756,13 +756,13 @@ export class Core {
);
if (!tool) {
return { error: "Tool not found", result: undefined };
throw new Error(`Tool ${toolCall.function.name} not found`);
}
const config = await this.configHandler.loadConfig();
const llm = await this.getSelectedModel();
const result = await tool.action(
const contextItems = await tool.action(
JSON.parse(toolCall.function.arguments || "{}"),
{
ide: this.ide,
@ -771,7 +771,7 @@ export class Core {
fetchwithRequestOptions(url, init, config.requestOptions),
},
);
return { result };
return { contextItems };
});
}

View file

@ -1,7 +1,7 @@
import { distance } from "fastest-levenshtein";
import { ChatMessage } from "../index.js";
import { stripImages } from "../llm/images.js";
import { renderChatMessage } from "../util/messageContent.js";
export type LineStream = AsyncGenerator<string>;
@ -103,7 +103,7 @@ export async function* streamLines(
try {
for await (const update of streamCompletion) {
const chunk =
typeof update === "string" ? update : stripImages(update.content);
typeof update === "string" ? update : renderChatMessage(update);
buffer += chunk;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";

31
core/index.d.ts vendored
View file

@ -293,13 +293,34 @@ export interface ToolCallDelta {
};
}
export interface ChatMessage {
role: ChatMessageRole;
content: MessageContent;
toolCalls?: ToolCallDelta[];
export interface ToolResultChatMessage {
role: "tool";
content: string;
toolCallId?: string;
}
export interface UserChatMessage {
role: "user";
content: MessageContent;
}
export interface AssistantChatMessage {
role: "assistant";
content: MessageContent;
toolCalls?: ToolCallDelta[];
}
export interface SystemChatMessage {
role: "system";
content: string;
}
export type ChatMessage =
| UserChatMessage
| AssistantChatMessage
| SystemChatMessage
| ToolResultChatMessage;
export interface ContextItemId {
providerTitle: string;
itemId: string;
@ -860,7 +881,7 @@ export interface Tool {
parameters?: Record<string, any>;
strict?: boolean | null;
};
action: (parameters: any, extras: ToolExtras) => Promise<any>;
action: (parameters: any, extras: ToolExtras) => Promise<ContextItem[]>;
}
interface BaseCompletionOptions {

View file

@ -1,4 +1,5 @@
import { ChatHistory, ChatMessage, MessagePart } from "../index.js";
import { normalizeToMessageParts } from "../util/messageContent.js";
const SYSTEM_MESSAGE = `When generating new code:
@ -61,17 +62,6 @@ Always follow these guidelines when generating code responses.
Other rules:
- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`;
function hasCodeBlockWithFilename(content: ChatMessage["content"]): boolean {
const contentStr = typeof content === "string" ? content : content[0].text;
if (!contentStr) {
return false;
}
const codeBlockRegex = /```[\w\W]*?\.[\w\W]*/;
return codeBlockRegex.test(contentStr);
}
export function constructMessages(
history: ChatHistory,
model: string,
@ -92,28 +82,27 @@ export function constructMessages(
for (let i = 0; i < history.length; i++) {
const historyItem = history[i];
let content = Array.isArray(historyItem.message.content)
? historyItem.message.content
: [{ type: "text", text: historyItem.message.content } as MessagePart];
if (historyItem.message.role === "user") {
// Gather context items for user messages
let content = normalizeToMessageParts(historyItem.message);
const ctxItems = historyItem.contextItems.map((ctxItem) => {
return { type: "text", text: `${ctxItem.content}\n` } as MessagePart;
});
const ctxItems = historyItem.contextItems.map((ctxItem) => {
return { type: "text", text: `${ctxItem.content}\n` } as MessagePart;
});
content = [...ctxItems, ...content];
msgs.push({
...historyItem.message,
content,
});
// Remove the "id" from all of the messages
msgs.forEach((msg: any) => {
if (msg.id !== undefined) {
delete msg.id;
}
});
content = [...ctxItems, ...content];
msgs.push({
...historyItem.message,
content,
});
} else {
msgs.push(historyItem.message);
}
}
return msgs;
// Remove the "id" from all of the messages
return msgs.map((msg) => {
const { id, ...rest } = msg as any;
return rest;
});
}

View file

@ -2,6 +2,7 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
import { ChatMessage, MessageContent, MessagePart } from "../index.js";
import { renderChatMessage } from "../util/messageContent.js";
import {
AsyncEncoder,
GPTAsyncEncoder,
@ -9,7 +10,6 @@ import {
} from "./asyncEncoder.js";
import { autodetectTemplateType } from "./autodetect.js";
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
import { stripImages } from "./images.js";
import llamaTokenizer from "./llamaTokenizer.js";
interface Encoding {
encode: Tiktoken["encode"];
@ -115,21 +115,28 @@ function countTokens(
}
}
function messageHasToolCalls(msg: ChatMessage): boolean {
return msg.role === "assistant" && !!msg.toolCalls;
}
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
const flattened: ChatMessage[] = [];
for (let i = 0; i < msgs.length; i++) {
const msg = msgs[i];
if (
flattened.length > 0 &&
flattened[flattened.length - 1].role === msg.role &&
!msg.toolCalls &&
!flattened[flattened.length - 1].toolCalls
!messageHasToolCalls(msg) &&
!messageHasToolCalls(flattened[flattened.length - 1])
) {
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
} else {
flattened.push(msg);
}
}
return flattened;
}
@ -224,11 +231,8 @@ function pruneRawPromptFromBottom(
return pruneStringFromBottom(modelName, maxTokens, prompt);
}
function summarize(message: MessageContent): string {
if (Array.isArray(message)) {
return `${stripImages(message).substring(0, 100)}...`;
}
return `${message.substring(0, 100)}...`;
function summarize(message: ChatMessage): string {
return `${renderChatMessage(message).substring(0, 100)}...`;
}
function pruneChatHistory(
@ -259,7 +263,7 @@ function pruneChatHistory(
for (let i = 0; i < longerThanOneThird.length; i++) {
// Prune line-by-line from the top
const message = longerThanOneThird[i];
const content = stripImages(message.content);
const content = renderChatMessage(message);
const deltaNeeded = totalTokens - contextLength;
const delta = Math.min(deltaNeeded, distanceFromThird[i]);
message.content = pruneStringFromTop(
@ -275,8 +279,8 @@ function pruneChatHistory(
while (totalTokens > contextLength && i < chatHistory.length - 5) {
const message = chatHistory[0];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(summarize(message.content), modelName);
message.content = summarize(message.content);
totalTokens += countTokens(summarize(message), modelName);
message.content = summarize(message);
i++;
}
@ -299,8 +303,8 @@ function pruneChatHistory(
) {
const message = chatHistory[i];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(summarize(message.content), modelName);
message.content = summarize(message.content);
totalTokens += countTokens(summarize(message), modelName);
message.content = summarize(message);
i++;
}
@ -316,7 +320,7 @@ function pruneChatHistory(
message.content = pruneRawPromptFromTop(
modelName,
contextLength,
stripImages(message.content),
renderChatMessage(message),
tokensForCompletion,
);
totalTokens = contextLength;
@ -378,7 +382,7 @@ function compileChatMessages(
) {
let content = "";
if (msgs?.[0].role === "system") {
content = stripImages(msgs?.[0].content);
content = renderChatMessage(msgs?.[0]);
}
if (systemMessage && systemMessage.trim() !== "") {
const shouldAddNewLines = content !== "";
@ -413,7 +417,7 @@ function compileChatMessages(
if (!supportsImages) {
for (const msg of msgsCopy) {
if ("content" in msg && Array.isArray(msg.content)) {
const content = stripImages(msg.content);
const content = renderChatMessage(msg);
msg.content = content;
}
}

View file

@ -1,11 +0,0 @@
import { MessageContent } from "../index.js";
export function stripImages(content: MessageContent): string {
if (Array.isArray(content)) {
return content
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n");
}
return content;
}

View file

@ -24,6 +24,7 @@ import mergeJson from "../util/merge.js";
import { Telemetry } from "../util/posthog.js";
import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
import { renderChatMessage } from "../util/messageContent.js";
import {
autodetectPromptTemplates,
autodetectTemplateFunction,
@ -41,7 +42,6 @@ import {
countTokens,
pruneRawPromptFromTop,
} from "./countTokens.js";
import { stripImages } from "./images.js";
import CompletionOptionsForModels from "./templates/options.js";
export abstract class BaseLLM implements ILLM {
@ -372,7 +372,8 @@ export abstract class BaseLLM implements ILLM {
`HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`,
);
} else {
if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here
if (e.name !== "AbortError") {
// Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here
console.debug(
`${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`,
);
@ -414,7 +415,7 @@ export abstract class BaseLLM implements ILLM {
let formatted = "";
for (const msg of msgsCopy) {
if ("content" in msg && Array.isArray(msg.content)) {
const content = stripImages(msg.content);
const content = renderChatMessage(msg);
msg.content = content;
}
formatted += `<${msg.role}>\n${msg.content || ""}\n\n`;
@ -533,7 +534,11 @@ export abstract class BaseLLM implements ILLM {
};
}
async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) {
async complete(
_prompt: string,
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
@ -568,7 +573,11 @@ export abstract class BaseLLM implements ILLM {
return completion;
}
async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) {
async chat(
messages: ChatMessage[],
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
let completion = "";
for await (const chunk of this.streamChat(messages, signal, options)) {
completion += chunk.content;
@ -668,7 +677,11 @@ export abstract class BaseLLM implements ILLM {
}
}
protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) {
protected async _complete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
) {
let completion = "";
for await (const chunk of this._streamComplete(prompt, signal, options)) {
completion += chunk;

View file

@ -4,7 +4,7 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
@ -48,7 +48,7 @@ class Anthropic extends BaseLLM {
{
type: "tool_result",
tool_use_id: message.toolCallId,
content: stripImages(message.content) || undefined,
content: renderChatMessage(message) || undefined,
},
],
};
@ -133,7 +133,7 @@ class Anthropic extends BaseLLM {
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, signal, options)) {
yield stripImages(update.content);
yield renderChatMessage(update);
}
}
@ -144,9 +144,8 @@ class Anthropic extends BaseLLM {
): AsyncGenerator<ChatMessage> {
const shouldCacheSystemMessage =
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const systemMessage: string = stripImages(
messages.filter((m) => m.role === "system")[0]?.content,
);
const systemMessage: string =
messages.filter((m) => m.role === "system")[0]?.content ?? "";
const msgs = this.convertMessages(messages);
const response = await this.fetch(new URL("messages", this.apiBase), {

View file

@ -11,7 +11,7 @@ import {
MessageContent,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
class Bedrock extends BaseLLM {
@ -42,7 +42,7 @@ class Bedrock extends BaseLLM {
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, signal, options)) {
yield stripImages(update.content);
yield renderChatMessage(update);
}
}
@ -86,7 +86,7 @@ class Bedrock extends BaseLLM {
const input = this._generateConverseInput(messages, options);
const command = new ConverseStreamCommand(input);
const response = await client.send(command, { abortSignal: signal});
const response = await client.send(command, { abortSignal: signal });
if (response.stream) {
for await (const chunk of response.stream) {
@ -122,7 +122,9 @@ class Bedrock extends BaseLLM {
// TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback.
// For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes),
// providing meaningful error messages to improve the user experience.
stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4),
stopSequences: options.stop
?.filter((stop) => stop.trim() !== "")
.slice(0, 4),
},
};
}
@ -164,7 +166,7 @@ class Bedrock extends BaseLLM {
try {
return await fromIni({
profile: this.profile,
ignoreCache: true
ignoreCache: true,
})();
} catch (e) {
console.warn(

View file

@ -1,5 +1,5 @@
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
@ -36,7 +36,7 @@ export default class Cloudflare extends BaseLLM {
model: this.model,
...this._convertArgs(options),
}),
signal
signal,
});
for await (const value of streamSse(resp)) {
@ -56,7 +56,7 @@ export default class Cloudflare extends BaseLLM {
signal,
options,
)) {
yield stripImages(chunk.content);
yield renderChatMessage(chunk);
}
}
}

View file

@ -4,7 +4,7 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamJSON } from "../stream.js";
@ -51,7 +51,7 @@ class Cohere extends BaseLLM {
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, signal, options)) {
yield stripImages(update.content);
yield renderChatMessage(update);
}
}
@ -75,7 +75,7 @@ class Cohere extends BaseLLM {
chat_history: this._convertMessages(messages),
preamble: this.systemMessage,
}),
signal
signal,
});
if (options.stream === false) {

View file

@ -6,7 +6,7 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
interface IFlowiseApiOptions {
@ -126,7 +126,7 @@ class Flowise extends BaseLLM {
): AsyncGenerator<string> {
const message: ChatMessage = { role: "user", content: prompt };
for await (const chunk of this._streamChat([message], signal, options)) {
yield stripImages(chunk.content);
yield renderChatMessage(chunk);
}
}
@ -141,7 +141,7 @@ class Flowise extends BaseLLM {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
signal
signal,
}).then((res) => res.json());
while (await socketInfo.hasNextToken()) {

View file

@ -74,7 +74,7 @@ class FreeTrial extends BaseLLM {
prompt,
...args,
}),
signal
signal,
});
let completion = "";
@ -82,10 +82,18 @@ class FreeTrial extends BaseLLM {
yield value;
completion += value;
}
this._countTokens(completion, args.model, false);
void this._countTokens(completion, args.model, false);
}
protected _convertMessage(message: ChatMessage) {
if (message.role === "tool") {
return {
role: "tool",
content: message.content,
tool_call_id: message.toolCallId,
};
}
if (typeof message.content === "string") {
return message;
}
@ -123,7 +131,7 @@ class FreeTrial extends BaseLLM {
messages: messages.map(this._convertMessage),
...args,
}),
signal
signal,
});
let completion = "";
@ -158,7 +166,7 @@ class FreeTrial extends BaseLLM {
suffix,
...args,
}),
signal
signal,
});
let completion = "";

View file

@ -5,7 +5,7 @@ import {
MessagePart,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
@ -19,7 +19,8 @@ class Gemini extends BaseLLM {
};
// Function to convert completion options to Gemini format
public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI
public convertArgs(options: CompletionOptions) {
// should be public for use within VertexAI
const finalOptions: any = {}; // Initialize an empty object
// Map known options
@ -54,17 +55,19 @@ class Gemini extends BaseLLM {
signal,
options,
)) {
yield stripImages(message.content);
yield renderChatMessage(message);
}
}
public removeSystemMessage(messages: ChatMessage[]) { // should be public for use within VertexAI
public removeSystemMessage(messages: ChatMessage[]) {
// should be public for use within VertexAI
const msgs = [...messages];
if (msgs[0]?.role === "system") {
const sysMsg = msgs.shift()?.content;
// @ts-ignore
if (msgs[0]?.role === "user") {
// @ts-ignore
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
}
}
@ -143,6 +146,9 @@ class Gemini extends BaseLLM {
if (msg.role === "system" && !isV1API) {
return null; // Don't include system message in contents
}
if (msg.role === "tool") {
return null;
}
return {
role: msg.role === "assistant" ? "model" : "user",
parts:
@ -165,7 +171,7 @@ class Gemini extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal
signal,
});
let buffer = "";
@ -234,7 +240,7 @@ class Gemini extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal
signal,
});
const data = await response.json();
yield { role: "assistant", content: data.candidates[0].content };

View file

@ -4,13 +4,11 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
interface OllamaChatMessage extends ChatMessage {
images?: string[];
}
type OllamaChatMessage = ChatMessage & { images?: string[] };
// See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter
interface ModelFileParams {
@ -37,31 +35,29 @@ interface ModelFileParams {
// See https://github.com/ollama/ollama/blob/main/docs/api.md
interface BaseOptions {
model: string; // the model name
model: string; // the model name
options?: ModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature
format?: "json"; // the format to return a response in. Currently, the only accepted value is json
stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects
keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m)
format?: "json"; // the format to return a response in. Currently, the only accepted value is json
stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects
keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m)
}
interface GenerateOptions extends BaseOptions {
prompt: string; // the prompt to generate a response for
suffix?: string; // the text after the model response
images?: string[]; // a list of base64-encoded images (for multimodal models such as llava)
system?: string; // system message to (overrides what is defined in the Modelfile)
template?: string; // the prompt template to use (overrides what is defined in the Modelfile)
context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory
raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API
prompt: string; // the prompt to generate a response for
suffix?: string; // the text after the model response
images?: string[]; // a list of base64-encoded images (for multimodal models such as llava)
system?: string; // system message to (overrides what is defined in the Modelfile)
template?: string; // the prompt template to use (overrides what is defined in the Modelfile)
context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory
raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API
}
interface ChatOptions extends BaseOptions {
messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory
messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory
// Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false
// And correspondingly, tool calls in OllamaChatMessage
}
class Ollama extends BaseLLM {
static providerName: ModelProvider = "ollama";
static defaultOptions: Partial<LLMOptions> = {
@ -196,9 +192,11 @@ class Ollama extends BaseLLM {
};
}
private _convertMessage(
message: ChatMessage
) {
private _convertMessage(message: ChatMessage) {
if (message.role === "tool") {
return null;
}
if (typeof message.content === "string") {
return message;
}
@ -214,18 +212,18 @@ class Ollama extends BaseLLM {
return {
role: message.role,
content: stripImages(message.content),
images
content: renderChatMessage(message),
images,
};
}
private _getChatOptions(
options: CompletionOptions,
messages: ChatMessage[]
messages: ChatMessage[],
): ChatOptions {
return {
model: this._getModel(),
messages: messages.map(this._convertMessage),
messages: messages.map(this._convertMessage).filter(Boolean) as any,
options: this._getModelFileParams(options),
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
stream: options.stream,
@ -236,7 +234,7 @@ class Ollama extends BaseLLM {
private _getGenerateOptions(
options: CompletionOptions,
prompt: string,
suffix?: string
suffix?: string,
): GenerateOptions {
return {
model: this._getModel(),
@ -271,7 +269,7 @@ class Ollama extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._getGenerateOptions(options, prompt)),
signal
signal,
});
let buffer = "";
@ -312,7 +310,7 @@ class Ollama extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._getChatOptions(options, messages)),
signal
signal,
});
let buffer = "";
@ -354,7 +352,6 @@ class Ollama extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(this.getEndpoint("api/generate"), {
method: "POST",
headers: {
@ -362,7 +359,7 @@ class Ollama extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)),
signal
signal,
});
let buffer = "";

View file

@ -4,7 +4,7 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
@ -56,6 +56,14 @@ class OpenAI extends BaseLLM {
};
protected _convertMessage(message: ChatMessage) {
if (message.role === "tool") {
return {
role: "tool",
content: message.content,
tool_call_id: message.toolCallId,
};
}
if (typeof message.content === "string") {
return message;
} else if (!message.content.some((item) => item.type !== "text")) {
@ -215,7 +223,7 @@ class OpenAI extends BaseLLM {
signal,
options,
)) {
yield stripImages(chunk.content);
yield renderChatMessage(chunk);
}
}
@ -258,7 +266,7 @@ class OpenAI extends BaseLLM {
options.raw)
) {
for await (const content of this._legacystreamComplete(
stripImages(messages[messages.length - 1]?.content || ""),
renderChatMessage(messages[messages.length - 1]),
signal,
options,
)) {

View file

@ -4,13 +4,11 @@ import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessagePart,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
import { streamResponse } from "../stream.js";
import { streamResponse, streamSse } from "../stream.js";
import Anthropic from "./Anthropic.js";
import Gemini from "./Gemini.js";
@ -40,16 +38,17 @@ class VertexAI extends BaseLLM {
super(_options);
this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options);
this.vertexProvider =
_options.model.includes("mistral") || _options.model.includes("codestral") || _options.model.includes("mixtral")
_options.model.includes("mistral") ||
_options.model.includes("codestral") ||
_options.model.includes("mixtral")
? "mistral"
: _options.model.includes("claude")
? "anthropic"
: _options.model.includes("gemini")
? "gemini" :
"unknown";
? "gemini"
: "unknown";
this.anthropicInstance = new Anthropic(_options);
this.geminiInstance = new Gemini(_options);
}
async fetch(url: RequestInfo | URL, init?: RequestInit) {
@ -82,18 +81,18 @@ class VertexAI extends BaseLLM {
};
}
protected async *StreamChatAnthropic(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const systemMessage: string = stripImages(
messages.filter((m) => m.role === "system")[0]?.content,
const shouldCacheSystemMessage =
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const systemMessage: string = renderChatMessage(
messages.filter((m) => m.role === "system")[0],
);
const apiURL = new URL(
`publishers/anthropic/models/${options.model}:streamRawPredict`,
this.apiBase
this.apiBase,
);
const response = await this.fetch(apiURL, {
@ -108,12 +107,12 @@ class VertexAI extends BaseLLM {
messages: this.anthropicInstance.convertMessages(messages),
system: shouldCacheSystemMessage
? [
{
type: "text",
text: this.systemMessage,
cache_control: { type: "ephemeral" },
},
]
{
type: "text",
text: this.systemMessage,
cache_control: { type: "ephemeral" },
},
]
: systemMessage,
}),
});
@ -125,14 +124,15 @@ class VertexAI extends BaseLLM {
}
for await (const value of streamSse(response)) {
if (value.type == "message_start") {console.log(value);}
if (value.type == "message_start") {
console.log(value);
}
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}
}
}
//Gemini
private async *streamChatGemini(
@ -152,6 +152,10 @@ class VertexAI extends BaseLLM {
if (msg.role === "system" && !isV1API) {
return null; // Don't include system message in contents
}
if (msg.role === "tool") {
return null;
}
return {
role: msg.role === "assistant" ? "model" : "user",
parts:
@ -168,8 +172,8 @@ class VertexAI extends BaseLLM {
// if this.systemMessage is defined, reformat it for Gemini API
...(this.systemMessage &&
!isV1API && {
systemInstruction: { parts: [{ text: this.systemMessage }] },
}),
systemInstruction: { parts: [{ text: this.systemMessage }] },
}),
};
const response = await this.fetch(apiURL, {
method: "POST",
@ -265,7 +269,6 @@ class VertexAI extends BaseLLM {
//Mistral
protected async *StreamChatMistral(
messages: ChatMessage[],
options: CompletionOptions,
@ -330,7 +333,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal
signal,
});
for await (const chunk of streamSse(response)) {
@ -338,8 +341,6 @@ class VertexAI extends BaseLLM {
}
}
//gecko
protected async *streamFimGecko(
prefix: string,
@ -347,15 +348,18 @@ class VertexAI extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase);
const endpoint = new URL(
"publishers/google/models/code-gecko:predict",
this.apiBase,
);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
instances: [
{
prefix: prefix,
suffix: suffix
}
suffix: suffix,
},
],
parameters: {
temperature: options.temperature,
@ -363,10 +367,9 @@ class VertexAI extends BaseLLM {
stopSequences: options.stop?.splice(0, 5),
frequencyPenalty: options.frequencyPenalty,
presencePenalty: options.frequencyPenalty,
}
},
}),
signal
signal,
});
// Streaming is not supported by code-gecko
// TODO: convert to non-streaming fim method when one exist in continue.
@ -409,7 +412,7 @@ class VertexAI extends BaseLLM {
signal,
options,
)) {
yield stripImages(message.content);
yield renderChatMessage(message);
}
}
@ -419,9 +422,6 @@ class VertexAI extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
if (this.model === "code-gecko") {
yield* this.streamFimGecko(prefix, suffix, signal, options);
} else if (this.model.includes("codestral")) {
@ -429,21 +429,15 @@ class VertexAI extends BaseLLM {
} else {
throw new Error(`Unsupported model: ${this.model}`);
}
}
supportsFim(): boolean {
return ["code-gecko", "codestral-latest"].includes(this.model);
}
}
async function delay(seconds: number) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
export default VertexAI;

View file

@ -4,25 +4,22 @@ import {
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
let watsonxToken = {
expiration: 0,
token: ""
expiration: 0,
token: "",
};
class WatsonX extends BaseLLM {
constructor(options: LLMOptions) {
super(options);
}
async getBearerToken(): Promise<{ token: string; expiration: number }> {
if (
this.apiBase?.includes("cloud.ibm.com")
) {
if (this.apiBase?.includes("cloud.ibm.com")) {
// watsonx SaaS
const wxToken = await (
await fetch(
@ -82,11 +79,9 @@ class WatsonX extends BaseLLM {
}
getWatsonxEndpoint(): string {
return (
this.deploymentId ?
`${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`:
`${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`
);
return this.deploymentId
? `${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`
: `${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`;
}
static providerName: ModelProvider = "watsonx";
@ -96,6 +91,10 @@ class WatsonX extends BaseLLM {
return message;
}
if (message.role === "tool") {
return null;
}
const parts = message.content.map((part) => {
const msg: any = {
type: part.type,
@ -119,7 +118,7 @@ class WatsonX extends BaseLLM {
protected _convertArgs(options: any, messages: ChatMessage[]) {
const finalOptions = {
messages: messages.map(this._convertMessage),
messages: messages.map(this._convertMessage).filter(Boolean),
model: this._convertModelName(options.model),
max_tokens: options.maxTokens,
temperature: options.temperature,
@ -133,8 +132,9 @@ class WatsonX extends BaseLLM {
protected _getHeaders() {
return {
"Content-Type": "application/json",
Authorization: `${watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
} ${watsonxToken.token}`,
Authorization: `${
watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
} ${watsonxToken.token}`,
};
}
@ -165,7 +165,7 @@ class WatsonX extends BaseLLM {
signal,
options,
)) {
yield stripImages(chunk.content);
yield renderChatMessage(chunk);
}
}
@ -183,7 +183,8 @@ class WatsonX extends BaseLLM {
watsonxToken = await this.getBearerToken();
} else {
console.log(
`Reusing token (expires in ${(watsonxToken.expiration - now) / 60
`Reusing token (expires in ${
(watsonxToken.expiration - now) / 60
} mins)`,
);
}
@ -191,7 +192,8 @@ class WatsonX extends BaseLLM {
throw new Error("Something went wrong. Check your credentials, please.");
}
const stopSequences =
options.stop?.slice(0,6) ?? (options.model?.includes("granite") ? ["Question:"] : []);
options.stop?.slice(0, 6) ??
(options.model?.includes("granite") ? ["Question:"] : []);
const url = this.getWatsonxEndpoint();
const headers = this._getHeaders();
@ -224,7 +226,7 @@ class WatsonX extends BaseLLM {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
signal
signal,
});
if (!response.ok || response.body === null) {

View file

@ -1,5 +1,5 @@
import { ChatMessage } from "../../index.js";
import { stripImages } from "../images.js";
import { renderChatMessage } from "../../util/messageContent.js";
function templateFactory(
systemMessage: (msg: ChatMessage) => string,
@ -64,7 +64,7 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
let hasSystem = msgs[0].role === "system";
if (hasSystem && stripImages(msgs[0].content).trim() === "") {
if (hasSystem && renderChatMessage(msgs[0]).trim() === "") {
hasSystem = false;
msgs = msgs.slice(1);
}
@ -158,7 +158,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string {
prompt +=
"You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n";
if (msgs[0].role === "system") {
system = stripImages(msgs.shift()!.content);
system = renderChatMessage(msgs.shift()!);
}
for (let i = 0; i < msgs.length; i++) {
@ -245,7 +245,7 @@ function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "<s>";
for (const msg of msgs) {
prompt += `Source: ${msg.role}\n\n ${stripImages(msg.content).trim()}`;
prompt += `Source: ${msg.role}\n\n ${renderChatMessage(msg).trim()}`;
prompt += " <step> ";
}

View file

@ -1,8 +1,8 @@
import * as YAML from "yaml";
import { ContinueSDK, SlashCommand } from "../..";
import { stripImages } from "../../llm/images";
import { getBasename } from "../../util/index";
import { renderChatMessage } from "../../util/messageContent";
import { getContextProviderHelpers } from "./getContextProviderHelpers";
import { renderTemplatedString } from "./renderTemplatedString";
@ -90,8 +90,11 @@ export function slashCommandFromPromptFile(
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
for await (const chunk of context.llm.streamChat(
messages,
new AbortController().signal,
)) {
yield renderChatMessage(chunk);
}
},
};

View file

@ -4,6 +4,7 @@ import { ProfileDescription } from "../config/ConfigHandler";
import type {
BrowserSerializedContinueConfig,
ChatMessage,
ContextItem,
ContextItemWithId,
ContextSubmenuItem,
DiffLine,
@ -160,5 +161,5 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"profiles/switch": [{ id: string }, undefined];
"auth/getAuthUrl": [undefined, { url: string }];
"tools/call": [{ toolCall: ToolCall }, { result: any }];
"tools/call": [{ toolCall: ToolCall }, { contextItems: ContextItem[] }];
};

View file

@ -14,6 +14,7 @@ export const createNewFileTool: Tool = {
}
await extras.ide.writeFile(filepath, args.contents);
await extras.ide.openFile(filepath);
return [];
},
function: {
name: "create_new_file",

View file

@ -3,8 +3,14 @@ import { Tool } from "..";
export const exactSearchTool: Tool = {
type: "function",
action: async (args, extras) => {
const results = await extras.ide.getSearchResults(args.query);
return results;
const content = await extras.ide.getSearchResults(args.query);
return [
{
name: "Search results",
description: "Results from exact search",
content,
},
];
},
function: {
name: "exact_search",

View file

@ -3,7 +3,16 @@ import { Tool } from "..";
export const runTerminalCommandTool: Tool = {
type: "function",
action: async (args, extras) => {
await extras.ide.runCommand(args.command);
const output = await extras.ide.runCommand(args.command);
return [];
// return [
// {
// description: "The contents of the terminal",
// content: output,
// name: "Terminal",
// },
// ];
},
function: {
name: "run_terminal_command",

View file

@ -5,7 +5,7 @@ export const searchWebTool: Tool = {
type: "function",
action: async (args, extras) => {
const webResults = await fetchSearchResults(args.query, 5, extras.fetch);
return webResults.map((result) => result.content).join("\n\n");
return webResults;
},
function: {
name: "search_web",

View file

@ -4,7 +4,13 @@ export const viewDiffTool: Tool = {
type: "function",
action: async (args, extras) => {
const diff = await extras.ide.getDiff(true);
return diff;
return [
{
name: "Diff",
description: "The current git diff",
content: diff,
},
];
},
function: {
name: "view_diff",

View file

@ -5,7 +5,13 @@ export const viewRepoMapTool: Tool = {
type: "function",
action: async (args, extras) => {
const repoMap = await generateRepoMap(extras.llm, extras.ide, {});
return repoMap;
return [
{
name: "Repo map",
description: "Overview of the repository structure",
content: repoMap,
},
];
},
function: {
name: "view_repo_map",

View file

@ -8,7 +8,13 @@ export const viewSubdirectoryTool: Tool = {
const repoMap = await generateRepoMap(extras.llm, extras.ide, {
dirs: [directory_path],
});
return repoMap;
return [
{
name: "Repo map",
description: `Map of ${directory_path}`,
content: repoMap,
},
];
},
function: {
name: "view_subdirectory",

View file

@ -1,5 +1,4 @@
import { ILLM, LLMFullCompletionOptions } from "..";
import { stripImages } from "../llm/images";
import { removeQuotesAndEscapes } from ".";
@ -35,7 +34,6 @@ export class ChatDescriber {
}
// Clean up and distill the message we want to send to the LLM
message = stripImages(message);
message = removeCodeBlocksAndTrim(message);
if (!message) {

View file

@ -0,0 +1,45 @@
import {
ChatMessage,
ContextItem,
MessageContent,
MessagePart,
} from "../index.js";
export function stripImages(messageContent: MessageContent): string {
if (typeof messageContent === "string") {
return messageContent;
}
return messageContent
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n");
}
export function renderChatMessage(message: ChatMessage): string {
switch (message.role) {
case "user":
case "assistant":
case "system":
return stripImages(message.content);
case "tool":
return message.content;
}
}
export function renderContextItems(contextItems: ContextItem[]): string {
return contextItems.map((item) => item.content).join("\n\n");
}
export function normalizeToMessageParts(message: ChatMessage): MessagePart[] {
switch (message.role) {
case "user":
case "assistant":
case "system":
return Array.isArray(message.content)
? message.content
: [{ type: "text", text: message.content }];
case "tool":
return [{ type: "text", text: message.content }];
}
}

View file

@ -4,7 +4,6 @@ import * as path from "node:path";
import { ConfigHandler } from "core/config/ConfigHandler";
import { getModelByRole } from "core/config/util";
import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock";
import { stripImages } from "core/llm/images";
import {
FromCoreProtocol,
FromWebviewProtocol,
@ -22,6 +21,7 @@ import { InProcessMessenger, Message } from "core/util/messenger";
import { getConfigJsonPath } from "core/util/paths";
import * as vscode from "vscode";
import { stripImages } from "core/util/messageContent";
import { VerticalDiffManager } from "../diff/vertical/manager";
import EditDecorationManager from "../quickEdit/EditDecorationManager";
import {

View file

@ -1,10 +1,11 @@
import { ChatHistoryItem } from "core";
import { useSelector } from "react-redux";
import { RootState } from "../../redux/store";
import AcceptRejectAllButtons from "./AcceptRejectAllButtons";
import FeedbackButtons from "./FeedbackButtons";
import UndoAndRedoButtons from "./UndoAndRedoButtons";
import { ChatHistoryItem } from "core";
import { stripImages } from "core/llm/images";
import { renderChatMessage } from "core/util/messageContent";
import { CopyIconButton } from "../gui/CopyIconButton";
export interface MultifileEditActionsProps {
@ -53,7 +54,7 @@ export default function MultifileEditActions({
<div className="flex flex-1 justify-end">
<CopyIconButton
tabIndex={-1}
text={stripImages(item.message.content)}
text={renderChatMessage(item.message)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
checkIconClassName="h-3.5 w-3.5 text-green-400"
/>

View file

@ -1,6 +1,6 @@
import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline";
import { ChatHistoryItem } from "core";
import { stripImages } from "core/llm/images";
import { renderChatMessage } from "core/util/messageContent";
import { useSelector } from "react-redux";
import { RootState } from "../../redux/store";
import { CopyIconButton } from "../gui/CopyIconButton";
@ -54,7 +54,7 @@ export default function ResponseActions({
<CopyIconButton
tabIndex={-1}
text={stripImages(item.message.content)}
text={renderChatMessage(item.message)}
clipboardIconClassName="h-3.5 w-3.5 text-gray-500"
checkIconClassName="h-3.5 w-3.5 text-green-400"
/>

View file

@ -1,5 +1,5 @@
import { ChatHistoryItem } from "core";
import { stripImages } from "core/llm/images";
import { renderChatMessage } from "core/util/messageContent";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
@ -42,7 +42,7 @@ export default function StepContainer(props: StepContainerProps) {
useEffect(() => {
if (!active) {
const content = stripImages(props.item.message.content).trim();
const content = renderChatMessage(props.item.message).trim();
const endingPunctuation = [".", "?", "!", "```", ":"];
// If not ending in punctuation or emoji, we assume the response got truncated
@ -88,12 +88,12 @@ export default function StepContainer(props: StepContainerProps) {
className="max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4"
style={{ fontSize: getFontSize() - 2 }}
>
{stripImages(props.item.message.content)}
{renderChatMessage(props.item.message)}
</pre>
) : (
<StyledMarkdownPreview
isRenderingInStepContainer
source={stripImages(props.item.message.content)}
source={renderChatMessage(props.item.message)}
/>
)}
</ContentDiv>

View file

@ -7,7 +7,7 @@ import {
MessagePart,
RangeInFile,
} from "core";
import { stripImages } from "core/llm/images";
import { stripImages } from "core/util/messageContent";
import { IIdeMessenger } from "../../context/IdeMessenger";
interface MentionAttrs {

View file

@ -4,6 +4,7 @@ import {
ChatHistory,
ChatHistoryItem,
ChatMessage,
ContextItem,
ContextItemWithId,
InputModifiers,
MessageContent,
@ -12,8 +13,11 @@ import {
SlashCommandDescription,
} from "core";
import { constructMessages } from "core/llm/constructMessages";
import { stripImages } from "core/llm/images";
import { getBasename, getRelativePath } from "core/util";
import {
renderChatMessage,
renderContextItems,
} from "core/util/messageContent";
import { usePostHog } from "posthog-js/react";
import { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
@ -122,7 +126,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
}
// Convert to actual slash command object with runnable function
return [slashCommand, stripImages(input)];
return [slashCommand, renderChatMessage({ role: "user", content: input })];
};
async function _streamSlashCommand(
@ -352,14 +356,14 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) {
async function streamResponseAfterToolCall(
toolCallId: string,
toolOutput: string,
toolOutput: ContextItem[],
) {
await handleErrors(async () => {
resetStateForNewMessage();
const newMessage: ChatMessage = {
role: "tool",
content: toolOutput,
content: renderContextItems(toolOutput),
toolCallId,
};

View file

@ -1,7 +1,6 @@
import { Dispatch } from "@reduxjs/toolkit";
import { PersistedSessionInfo, SessionInfo } from "core";
import { stripImages } from "core/llm/images";
import { useCallback, useContext } from "react";
import { useSelector } from "react-redux";
import { IdeMessengerContext } from "../context/IdeMessenger";
@ -10,6 +9,7 @@ import { defaultModelSelector } from "../redux/selectors/modelSelectors";
import { newSession } from "../redux/slices/stateSlice";
import { RootState } from "../redux/store";
import { getLocalStorage, setLocalStorage } from "../util/localStorage";
import { renderChatMessage } from "core/util/messageContent";
const MAX_TITLE_LENGTH = 100;
@ -79,7 +79,7 @@ function useHistory(dispatch: Dispatch) {
let title =
stateCopy.title === "New Session"
? truncateText(
stripImages(stateCopy.history[0].message.content)
renderChatMessage(stateCopy.history[0].message)
.split("\n")
.filter((l) => l.trim() !== "")
.slice(-1)[0] || "",

View file

@ -1,7 +1,7 @@
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import { Editor, JSONContent } from "@tiptap/core";
import { InputModifiers } from "core";
import { stripImages } from "core/llm/images";
import { renderChatMessage } from "core/util/messageContent";
import { useContext, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
@ -178,7 +178,10 @@ function Edit() {
const prompt = [
...contextItems.map((item) => item.content),
stripImages(userInstructions),
renderChatMessage({
role: "user",
content: userInstructions,
}),
].join("\n\n");
ideMessenger.post("edit/sendPrompt", {
prompt,

View file

@ -6,7 +6,7 @@ import {
} from "@heroicons/react/24/outline";
import { JSONContent } from "@tiptap/react";
import { InputModifiers } from "core";
import { stripImages } from "core/llm/images";
import { renderChatMessage } from "core/util/messageContent";
import { usePostHog } from "posthog-js/react";
import {
Fragment,
@ -350,7 +350,7 @@ export function Chat() {
/>
) : item.message.role === "tool" ? (
<ToolOutput
output={stripImages(item.message.content)}
output={renderChatMessage(item.message)}
toolCallId={item.message.toolCallId}
/>
) : item.message.role === "assistant" &&

View file

@ -10,22 +10,33 @@ export function FunctionSpecificHeader(props: FunctionSpecificHeaderProps) {
props.toolCall.function.arguments,
);
let message;
switch (props.toolCall.function.name) {
case "create_new_file":
return "Continue wants to create a new file";
message = "Continue wants to create a new file";
break;
case "run_terminal_command":
return "Continue wants to run a terminal command.";
message = "Continue wants to run a terminal command.";
break;
case "exact_search":
return "Continue wants to search your codebase";
message = "Continue wants to search your codebase";
break;
case "search_web":
return "Continue wants to search the internet";
message = "Continue wants to search the internet";
break;
case "view_diff":
return "Continue wants to view the current git diff";
message = "Continue wants to view the current git diff";
break;
case "view_repo_map":
return "Continue wants to view a map of your repository";
message = "Continue wants to view a map of your repository";
break;
case "view_subdirectory":
return `Continue wants to view the contents of ${incrementalJson.directory_path ?? "a subdirectory"}`;
message = `Continue wants to view the contents of ${incrementalJson.directory_path ?? "a subdirectory"}`;
break;
default:
return `Continue wants to use the ${props.toolCall.function.name} function.`;
message = `Continue wants to use the ${props.toolCall.function.name} function.`;
}
return <div>{message}</div>;
}

View file

@ -85,11 +85,9 @@ export function ToolCallButtons(props: ToolCallButtonsProps) {
clearTimeout(timer);
if (result.status === "success") {
const contextItems = result.content.contextItems;
// Send to the LLM to continue the conversation
streamResponseAfterToolCall(
toolCallState.toolCall.id,
result.content.result,
);
streamResponseAfterToolCall(toolCallState.toolCall.id, contextItems);
}
}

View file

@ -11,8 +11,8 @@ import {
} from "core";
import { BrowserSerializedContinueConfig } from "core/config/load";
import { ConfigValidationError } from "core/config/validation";
import { stripImages } from "core/llm/images";
import { ApplyState } from "core/protocol/ideWebview";
import { renderChatMessage } from "core/util/messageContent";
import { v4 as uuidv4, v4 } from "uuid";
import { ToolState } from "../../pages/gui/ToolCallDiv/types";
@ -30,9 +30,15 @@ type ChatHistoryItemWithMessageId = ChatHistoryItem & {
type State = {
currentToolCallState: CurrentToolCallState;
history: ChatHistoryItemWithMessageId[];
ttsActive: boolean;
active: boolean;
isGatheringContext: boolean;
checkpoints: Checkpoint[];
applyStates: ApplyState[];
nextCodeBlockToApplyIndex: number;
streamAborter: AbortController;
curCheckpointIndex: number;
ttsActive: boolean;
config: BrowserSerializedContinueConfig;
title: string;
sessionId: string;
@ -40,11 +46,6 @@ type State = {
mainEditorContent?: JSONContent;
selectedProfileId: string;
configError: ConfigValidationError[] | undefined;
checkpoints: Checkpoint[];
curCheckpointIndex: number;
applyStates: ApplyState[];
nextCodeBlockToApplyIndex: number;
streamAborter: AbortController;
isMultifileEdit: boolean;
};
@ -227,7 +228,7 @@ export const stateSlice = createSlice({
message: { ...payload.message, id: uuidv4() },
editorState: {
type: "doc",
content: stripImages(payload.message.content)
content: renderChatMessage(payload.message)
.split("\n")
.map((line) => ({
type: "paragraph",
@ -281,6 +282,7 @@ export const stateSlice = createSlice({
(lastMessage.message.role !== action.payload.role ||
// This is when a tool call comes after assistant text
(lastMessage.message.content !== "" &&
action.payload.role === "assistant" &&
action.payload.toolCalls?.length))
) {
// Create a new message
@ -292,8 +294,12 @@ export const stateSlice = createSlice({
// Add to the existing message
const msg = state.history[state.history.length - 1].message;
if (action.payload.content) {
msg.content += stripImages(action.payload.content);
} else if (action.payload.toolCalls) {
msg.content += renderChatMessage(action.payload);
} else if (
action.payload.role === "assistant" &&
action.payload.toolCalls &&
msg.role === "assistant"
) {
if (!msg.toolCalls) {
msg.toolCalls = [];
}

View file

@ -0,0 +1,41 @@
class Calculator {
private result: number;
constructor() {
this.result = 0;
}
add(number: number): Calculator {
this.result += number;
return this;
}
subtract(number: number): Calculator {
this.result -= number;
return this;
}
multiply(number: number): Calculator {
this.result *= number;
return this;
}
divide(number: number): Calculator {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
this.result /= number;
return this;
}
getResult(): number {
return this.result;
}
reset(): Calculator {
this.result = 0;
return this;
}
}
export default Calculator;