From 3b25f7813246f1ecf0d441af2316e39b5c9af646 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 12 Jan 2025 16:47:25 -0800 Subject: [PATCH 01/33] gemini types and general better type support --- core/commands/index.ts | 15 +- core/index.d.ts | 22 +- core/llm/countTokens.ts | 11 +- core/llm/llms/Asksage.ts | 18 +- core/llm/llms/FreeTrial.ts | 12 +- core/llm/llms/Gemini.ts | 199 ++++++++++---- core/llm/llms/Ollama.ts | 6 +- core/llm/llms/VertexAI.ts | 8 +- core/llm/llms/WatsonX.ts | 15 +- core/llm/llms/gemini-types.ts | 268 +++++++++++++++++++ core/llm/openaiTypeConverters.ts | 88 +++--- core/llm/toolSupport.ts | 4 + extensions/vscode/package-lock.json | 4 +- gui/src/components/mainInput/resolveInput.ts | 10 +- gui/src/redux/thunks/gatherContext.ts | 2 +- 15 files changed, 556 insertions(+), 126 deletions(-) create mode 100644 core/llm/llms/gemini-types.ts diff --git a/core/commands/index.ts b/core/commands/index.ts index 492b7f90a..723a4d247 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -37,16 +37,21 @@ export function slashFromCustomCommand( if ( Array.isArray(content) && - content.some((part) => - part.text?.startsWith(`/${customCommand.name}`), + content.some( + (part) => + "text" in part && part.text?.startsWith(`/${customCommand.name}`), ) ) { messages[i] = { ...message, content: content.map((part) => { - return part.text?.startsWith(`/${customCommand.name}`) - ? { ...part, text: promptUserInput } - : part; + if ( + "text" in part && + part.text.startsWith(`/${customCommand.name}`) + ) { + return { type: "text", text: promptUserInput }; + } + return part; }), }; break; diff --git a/core/index.d.ts b/core/index.d.ts index cd6510f19..9fd64bb89 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -306,11 +306,17 @@ export interface CompletionOptions extends BaseCompletionOptions { export type ChatMessageRole = "user" | "assistant" | "system" | "tool"; -export interface MessagePart { - type: "text" | "imageUrl"; - text?: string; - imageUrl?: { url: string }; -} +export type TextMessagePart = { + type: "text"; + text: string; +}; + +export type ImageMessagePart = { + type: "imageUrl"; + imageUrl: { url: string }; +}; + +export type MessagePart = TextMessagePart | ImageMessagePart; export type MessageContent = string | MessagePart[]; @@ -1235,9 +1241,9 @@ export type PackageDocsResult = { } & ( | { error: string; details?: never } | { details: PackageDetailsSuccess; error?: never } - ); +); export interface TerminalOptions { - reuseTerminal?: boolean, - terminalName?: string, + reuseTerminal?: boolean; + terminalName?: string; } diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 1f5ab4c4a..5f88c13eb 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -106,9 +106,12 @@ function countTokens( const encoding = encodingForModel(modelName); if (Array.isArray(content)) { return content.reduce((acc, part) => { - return acc + part.type === "imageUrl" - ? countImageTokens(part) - : encoding.encode(part.text ?? "", "all", []).length; + return ( + acc + + (part.type === "text" + ? encoding.encode(part.text ?? "", "all", []).length + : countImageTokens(part)) + ); }, 0); } else { return encoding.encode(content ?? "", "all", []).length; @@ -335,7 +338,7 @@ function messageIsEmpty(message: ChatMessage): boolean { } if (Array.isArray(message.content)) { return message.content.every( - (item) => !item.imageUrl && item.text?.trim() === "", + (item) => item.type === "text" && item.text?.trim() === "", ); } return false; diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 544b947c2..aa8125e4d 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -1,4 +1,9 @@ -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { + ChatMessage, + CompletionOptions, + LLMOptions, + TextMessagePart, +} from "../../index.js"; import { BaseLLM } from "../index.js"; class Asksage extends BaseLLM { @@ -14,8 +19,8 @@ class Asksage extends BaseLLM { "gpt4-gov": "gpt4-gov", // Works "gpt-gov": "gpt-gov", // Works "gpt-4o": "gpt-4o", // Works - "gpt-4o-mini": "gpt-4o-mini", // Works - "gpt4": "gpt4", // Works + "gpt-4o-mini": "gpt-4o-mini", // Works + gpt4: "gpt4", // Works "gpt4-32k": "gpt4-32k", "gpt-o1": "gpt-o1", // Works "gpt-o1-mini": "gpt-o1-mini", // Works @@ -25,7 +30,7 @@ class Asksage extends BaseLLM { "claude-3-opus-20240229": "claude-3-opus", // Works "claude-3-sonnet-20240229": "claude-3-sonnet", // Works "grok-beta": "xai-grok", - "groq-llama33": "groq-llama33", + "groq-llama33": "groq-llama33", "groq-70b": "groq-70b", "mistral-large-latest": "mistral-large", // Works "llama3-70b": "llma3", // Works @@ -50,7 +55,10 @@ class Asksage extends BaseLLM { message: typeof message.content === "string" ? message.content - : message.content.map((part) => part.text).join(""), + : message.content + .filter((part) => part.type === "text") + .map((part) => part.text) + .join(""), }; } diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 34b916346..c092a1ecb 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -113,10 +113,18 @@ class FreeTrial extends BaseLLM { } const parts = message.content.map((part) => { + if (part.type === "imageUrl") { + return { + type: "image_url", + image_url: { + url: part.imageUrl.url, + detail: "low", + }, + }; + } return { - type: part.type, + type: "text", text: part.text, - image_url: { ...part.imageUrl, detail: "low" }, }; }); return { diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 02abd8bf9..0cc470df3 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,12 +1,21 @@ +import { r } from "tar"; import { ChatMessage, CompletionOptions, LLMOptions, MessagePart, + ToolCallDelta, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; +import { + GeminiChatContentPart, + GeminiChatRequestBody, + GeminiChatResponse, + GeminiGenerationConfig, + GeminiToolFunctionDeclaration, +} from "./gemini-types.js"; class Gemini extends BaseLLM { static providerName = "gemini"; @@ -19,7 +28,7 @@ class Gemini extends BaseLLM { }; // Function to convert completion options to Gemini format - public convertArgs(options: CompletionOptions) { + public convertArgs(options: CompletionOptions): GeminiGenerationConfig { // should be public for use within VertexAI const finalOptions: any = {}; // Initialize an empty object @@ -42,7 +51,7 @@ class Gemini extends BaseLLM { .slice(0, this.maxStopWords ?? Gemini.defaultOptions.maxStopWords); } - return { generationConfig: finalOptions }; // Wrap options under 'generationConfig' + return finalOptions; } protected async *_streamComplete( @@ -59,7 +68,7 @@ class Gemini extends BaseLLM { } } - public removeSystemMessage(messages: ChatMessage[]) { + public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] { // should be public for use within VertexAI const msgs = [...messages]; @@ -92,8 +101,8 @@ class Gemini extends BaseLLM { ? this.removeSystemMessage(messages) : messages; - if (options.model.includes("gemini")) { - for await (const message of this.streamChatGemini( + if (options.model.includes("bison")) { + for await (const message of this.streamChatBison( convertedMsgs, signal, options, @@ -101,7 +110,7 @@ class Gemini extends BaseLLM { yield message; } } else { - for await (const message of this.streamChatBison( + for await (const message of this.streamChatGemini( convertedMsgs, signal, options, @@ -111,7 +120,7 @@ class Gemini extends BaseLLM { } } - continuePartToGeminiPart(part: MessagePart) { + continuePartToGeminiPart(part: MessagePart): GeminiChatContentPart { return part.type === "text" ? { text: part.text, @@ -135,39 +144,93 @@ class Gemini extends BaseLLM { ); // This feels hacky to repeat code from above function but was the quickest // way to ensure system message re-formatting isn't done if user has specified v1 - const apiBase = - this.apiBase || - Gemini.defaultOptions?.apiBase || - "https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase + const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase const isV1API = apiBase.includes("/v1/"); - const contents = messages - .map((msg) => { - 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: - typeof msg.content === "string" - ? [{ text: msg.content }] - : msg.content.map(this.continuePartToGeminiPart), - }; - }) - .filter((c) => c !== null); - - const body = { - ...this.convertArgs(options), - contents, - // if this.systemMessage is defined, reformat it for Gemini API - ...(this.systemMessage && - !isV1API && { - systemInstruction: { parts: [{ text: this.systemMessage }] }, + // Convert chat messages to contents + const body: GeminiChatRequestBody = { + contents: messages + .filter((msg) => !(msg.role === "system" && isV1API)) + .map((msg) => { + if (msg.role === "tool") { + return { + role: "user", + parts: [ + { + functionResponse: { + name: msg.toolCallId, // FIX SHOULD BE NAME NOT ID + response: { + output: msg.content, // "output" key is opinionated - not all functions will output objects + }, + }, + }, + ], + }; + } + return { + role: + msg.role === "assistant" ? ("model" as const) : ("user" as const), + parts: + typeof msg.content === "string" + ? [{ text: msg.content }] + : msg.content.map(this.continuePartToGeminiPart), + }; }), }; + if (options) { + body.generationConfig = this.convertArgs(options); + } + + // https://ai.google.dev/gemini-api/docs/api-versions + if (!isV1API) { + if (this.systemMessage) { + body.systemInstruction = { parts: [{ text: this.systemMessage }] }; + } + // Convert and add tools if present + if (options.tools?.length) { + // Choosing to map all tools to the functionDeclarations of one tool + // Rather than map each tool to its own tool + functionDeclaration + // Same difference + const functions: GeminiToolFunctionDeclaration[] = []; + options.tools.forEach((tool) => { + if (tool.function.description && tool.function.name) { + const fn: GeminiToolFunctionDeclaration = { + description: tool.function.description, + name: tool.function.name, + }; + + if ( + tool.function.parameters && + "type" in tool.function.parameters + ) { + if (tool.function.parameters.type === "object") { + // Gemini can't take an empty object + // So if empty object param is present just don't add parameters + if ( + JSON.stringify(tool.function.parameters.properties) === "{}" + ) { + functions.push(fn); + return; + } + } + fn.parameters = { + type: tool.function.parameters.type.toUpperCase(), + ...tool.function.parameters, + }; + } + functions.push(fn); + } + }); + if (functions.length) { + body.tools = [ + { + functionDeclarations: functions, + }, + ]; + } + } + } + const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), @@ -192,24 +255,68 @@ class Gemini extends BaseLLM { let foundIncomplete = false; for (let i = 0; i < parts.length; i++) { const part = parts[i]; - let data; + let data: GeminiChatResponse; try { - data = JSON.parse(part); + data = JSON.parse(part) as GeminiChatResponse; } catch (e) { foundIncomplete = true; continue; // yo! } - if (data.error) { + + if ("error" in data) { throw new Error(data.error.message); } + // Check for existence of each level before accessing the final 'text' property - if (data?.candidates?.[0]?.content?.parts?.[0]?.text) { - // Incrementally stream the content to make it smoother - const content = data.candidates[0].content.parts[0].text; - yield { - role: "assistant", - content, - }; + const content = data?.candidates?.[0]?.content; + if (content) { + const supportedParts: MessagePart[] = []; + const toolCalls: ToolCallDelta[] = []; + + for (const part of content.parts) { + if ("text" in part) { + supportedParts.push({ type: "text", text: part.text }); + } else if ("inlineData" in part) { + // TODO does this image url conversion actually work? + supportedParts.push({ + type: "imageUrl", + imageUrl: { + url: `data:image/jpeg;base64,${part.inlineData.data}`, + }, + }); + } else if ("functionCall" in part) { + // Handle function call + toolCalls.push({ + type: "function", + id: "", // Not supported by gemini + function: { + name: part.functionCall.name, + arguments: + typeof part.functionCall.args === "string" + ? part.functionCall.args + : JSON.stringify(part.functionCall.args), + }, + }); + } else if ("functionResponse" in part) { + // TODO hypothetically order could be off here + // Where function response is in the middle of something + yield { + role: "tool", + content: part.functionResponse.response.output as string, + toolCallId: part.functionResponse.name, + }; + } else { + console.warn("Unsupported gemini part type received", part); + } + } + if (supportedParts.length || toolCalls.length) { + // Incrementally stream the content to make it smoother + yield { + role: "assistant", + content: supportedParts.length ? supportedParts : "", + ...(toolCalls.length ? { toolCalls } : {}), + }; + } } else { // Handle the case where the expected data structure is not found console.warn("Unexpected response format:", data); diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index caa00e923..bbe54e130 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,4 +1,4 @@ -import { JSONSchema7Object, JSONSchema7Type } from "json-schema"; +import { JSONSchema7, JSONSchema7Object } from "json-schema"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; @@ -12,7 +12,7 @@ type OllamaChatMessage = { tool_calls?: { function: { name: string; - arguments: Record; + arguments: JSONSchema7Object; }; }[]; }; @@ -119,7 +119,7 @@ interface OllamaTool { function: { name: string; description?: string; - parameters?: JSONSchema7Object; + parameters?: JSONSchema7; }; } diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 43aa4d6ac..8d20c3212 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -124,7 +124,7 @@ class VertexAI extends BaseLLM { } for await (const value of streamSse(response)) { - if (value.type == "message_start") { + if (value.type === "message_start") { console.log(value); } if (value.delta?.text) { @@ -389,11 +389,11 @@ class VertexAI extends BaseLLM { const convertedMsgs = isV1API ? this.geminiInstance.removeSystemMessage(messages) : messages; - if (this.vertexProvider == "gemini") { + if (this.vertexProvider === "gemini") { yield* this.streamChatGemini(convertedMsgs, options); - } else if (this.vertexProvider == "mistral") { + } else if (this.vertexProvider === "mistral") { yield* this.StreamChatMistral(messages, options); - } else if (this.vertexProvider == "anthropic") { + } else if (this.vertexProvider === "anthropic") { yield* this.StreamChatAnthropic(messages, options); } else { if (options.model.includes("bison")) { diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index bbc967519..17c8b1d4b 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -95,15 +95,16 @@ class WatsonX extends BaseLLM { } const parts = message.content.map((part) => { - const msg: any = { - type: part.type, + if (part.type === "imageUrl") { + return { + type: "image_url", + image_url: { ...part.imageUrl, detail: "low" }, + }; + } + return { + type: "text", text: part.text, }; - if (part.type === "imageUrl") { - msg.image_url = { ...part.imageUrl, detail: "low" }; - msg.type = "image_url"; - } - return msg; }); return { ...message, diff --git a/core/llm/llms/gemini-types.ts b/core/llm/llms/gemini-types.ts new file mode 100644 index 000000000..b9fb52c1d --- /dev/null +++ b/core/llm/llms/gemini-types.ts @@ -0,0 +1,268 @@ +import { JSONSchema7Object } from "json-schema"; + +// https://ai.google.dev/api/generate-content +export interface GeminiGenerationConfig { + stopSequences?: string[]; + responseMimeType?: string; + candidateCount?: number; + maxOutputTokens?: number; + temperature?: number; + topP?: number; + topK?: number; + presencePenalty?: number; + frequencyPenalty?: number; + responseLogprobs?: boolean; + logprobs?: number; + // responseSchema?: object; // https://ai.google.dev/api/caching#Schema +} + +export interface GeminiFunctionSchema { + type: + | "TYPE_UNSPECIFIED" + | "STRING" + | "NUMBER" + | "INTEGER" + | "BOOLEAN" + | "ARRAY" + | "OBJECT"; + format?: string; + description?: string; + nullable?: boolean; + enum?: string[]; + maxItems?: string; + minItems?: string; + properties?: Record; + required?: string[]; + items?: GeminiFunctionSchema; +} + +export type GeminiChatContentPart = + | { + text: string; + } + | { + inlineData: { + mimeType: string; + data: string; + }; + } + | { + functionCall: { + name: string; + args: JSONSchema7Object; + }; + } + | { + functionResponse: { + name: string; + response: JSONSchema7Object; + }; + } + | { + fileData: { + fileUri: string; + mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata + }; + } + | { + executableCode: { + language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; + code: string; + }; + } + | { + codeExecutionResult: { + outcome: + | "OUTCOME_UNSPECIFIED" + | "OUTCOME_OK" + | "OUTCOME_FAILED" + | "OUTCOME_DEADLINE_EXCEEDED"; + output: string; + }; + }; +export interface GeminiChatContent { + role?: "user" | "model"; + parts: GeminiChatContentPart[]; +} + +export interface GeminiToolFunctionDeclaration { + name: string; + description: string; + parameters?: GeminiFunctionSchema; +} +export interface GeminiTool { + functionDeclarations?: GeminiToolFunctionDeclaration[]; + googleSearchRetrieval?: { + dynamicRetrievalConfig: { + mode?: "MODE_DYNAMIC" | "MODE_UNSPECIFIED"; + dynamicThreshold?: number; + }; + }; + codeExecution?: {}; +} + +export interface GeminiToolConfig { + functionCallingConfig?: { + mode?: "NONE" | "ANY" | "AUTO"; + allowedFunctionNames?: string[]; + }; +} + +// https://ai.google.dev/api/generate-content#request-body +export interface GeminiChatRequestBody { + contents: GeminiChatContent[]; + tools?: GeminiTool[]; + toolConfig?: GeminiToolConfig; + systemInstruction?: GeminiChatContent; + generationConfig?: GeminiGenerationConfig; + // cachedContent?: string; +} + +export interface GeminiChatResponseSuccess { + candidates: Candidate[]; + promptFeedback: PromptFeedback; + usageMetadata: UsageMetadata; +} + +export interface GeminiChatResponseError { + error: { + message: string; + }; +} + +export type GeminiChatResponse = + | GeminiChatResponseError + | GeminiChatResponseSuccess; + +interface PromptFeedback { + blockReason?: BlockReason; + safetyRatings: SafetyRating[]; +} + +enum BlockReason { + BLOCK_REASON_UNSPECIFIED = "BLOCK_REASON_UNSPECIFIED", + SAFETY = "SAFETY", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", +} + +interface SafetyRating { + harmCategory: HarmCategory; + harmProbability: HarmProbability; + blocked: boolean; +} + +enum HarmCategory { + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + HARM_CATEGORY_DEROGATORY = "HARM_CATEGORY_DEROGATORY", + HARM_CATEGORY_TOXICITY = "HARM_CATEGORY_TOXICITY", + HARM_CATEGORY_VIOLENCE = "HARM_CATEGORY_VIOLENCE", + HARM_CATEGORY_SEXUAL = "HARM_CATEGORY_SEXUAL", + HARM_CATEGORY_MEDICAL = "HARM_CATEGORY_MEDICAL", + HARM_CATEGORY_DANGEROUS = "HARM_CATEGORY_DANGEROUS", + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", +} + +enum HarmProbability { + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + NEGLIGIBLE = "NEGLIGIBLE", + LOW = "LOW", + MEDIUM = "MEDIUM", + HIGH = "HIGH", +} + +interface UsageMetadata { + promptTokenCount: number; + cachedContentTokenCount: number; + candidatesTokenCount: number; + totalTokenCount: number; +} + +interface Candidate { + content: GeminiChatContent; + finishReason: FinishReason; + safetyRatings: SafetyRating[]; + tokenCount: number; + groundingAttribution?: GroundingAttribution; + groundingMetadata?: GroundingMetadata; + avgLogprobs?: number; + logprobs?: LogprobsResult; + index: number; +} + +enum FinishReason { + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + STOP = "STOP", + MAX_TOKENS = "MAX_TOKENS", + SAFETY = "SAFETY", + RECITATION = "RECITATION", + LANGUAGE = "LANGUAGE", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + SPII = "SPII", + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", +} + +interface GroundingAttribution { + attributionSourceId: AttributionSourceId; + groundingSourceContent: string; +} + +interface AttributionSourceId { + groundingPassage?: GroundingPassageId; + semanticRetrieverChunk?: SemanticRetrieverChunk; +} + +interface GroundingPassageId { + passageId: string; + partIndex: number; +} + +interface SemanticRetrieverChunk { + source: string; + chunk: string; +} + +interface GroundingMetadata { + groundingSupport?: GroundingSupport[]; + webSearchQueries?: string[]; + searchEntryPoint?: SearchEntryPoint; + retrievalMetadata?: RetrievalMetadata; +} + +interface SearchEntryPoint { + renderedContent?: string; + sdkBlob?: string; +} + +interface RetrievalMetadata { + googleSearchDynamicRetrievalScore?: number; +} + +interface GroundingSupport { + groundingChunkIndices: number[]; + confidenceScores: number[]; + segment: Segment; +} + +interface Segment { + partIndex: number; + startIndex: number; + endIndex: number; + text: string; +} + +interface LogprobsResult { + topCandidates: TopCandidates[]; + chosenCandidates: Candidate[]; +} + +interface TopCandidates { + candidates: Candidate[]; +} diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index 057219beb..c3477dc84 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -1,13 +1,21 @@ import { FimCreateParamsStreaming } from "@continuedev/openai-adapters/dist/apis/base"; import { + Chat, ChatCompletion, + ChatCompletionAssistantMessageParam, ChatCompletionChunk, ChatCompletionCreateParams, ChatCompletionMessageParam, + ChatCompletionUserMessageParam, CompletionCreateParams, } from "openai/resources/index"; -import { ChatMessage, CompletionOptions } from ".."; +import { + ChatMessage, + CompletionOptions, + MessageContent, + TextMessagePart, +} from ".."; export function toChatMessage( message: ChatMessage, @@ -26,43 +34,53 @@ export function toChatMessage( }; } - let msg: ChatCompletionMessageParam = { - role: message.role, - content: - typeof message.content === "string" - ? message.content || " " // LM Studio (and other providers) don't accept empty content - : !message.content.some((item) => item.type !== "text") - ? // If no multi-media is in the message, just send as text + if (message.role === "assistant") { + const msg: ChatCompletionAssistantMessageParam = { + role: "assistant", + content: + typeof message.content === "string" + ? message.content || " " // LM Studio (and other providers) don't accept empty content + : message.content.filter((part) => part.type === "text"), + }; + + if (message.toolCalls) { + msg.tool_calls = message.toolCalls.map((toolCall) => ({ + id: toolCall.id!, + type: toolCall.type!, + function: { + name: toolCall.function?.name!, + arguments: toolCall.function?.arguments!, + }, + })); + } + return msg; + } else { + return { + role: "user", + content: + typeof message.content === "string" + ? message.content || " " // LM Studio (and other providers) don't accept empty content + : // If no multi-media is in the message, just send as text // for compatibility with OpenAI-"compatible" servers // that don't support multi-media format - message.content.map((item) => item.text).join("") || " " - : message.content.map((part) => { - const msg: any = { - type: part.type, - text: part.text, - }; - if (part.type === "imageUrl") { - msg.image_url = { ...part.imageUrl, detail: "auto" }; - msg.type = "image_url"; - } - return msg; - }), - }; - if ( - msg.role === "assistant" && - message.role === "assistant" && - message.toolCalls - ) { - msg.tool_calls = message.toolCalls.map((toolCall) => ({ - id: toolCall.id!, - type: toolCall.type!, - function: { - name: toolCall.function?.name!, - arguments: toolCall.function?.arguments!, - }, - })); + message.content.some((item) => item.type !== "text") + ? message.content + .map((item) => (item as TextMessagePart).text) + .join("") || " " + : message.content.map((part) => { + if (part.type === "imageUrl") { + return { + type: "image_url" as const, + image_url: { + url: part.imageUrl.url, + detail: "auto" as const, + }, + }; + } + return part; + }), + }; } - return msg; } export function toChatBody( diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 889c98c91..dd8f72fb0 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -17,6 +17,10 @@ export const PROVIDER_TOOL_SUPPORT: Record< return true; } }, + gemini: (model) => { + // All gemini models support function calling + return model.toLowerCase().includes("gemini"); + }, // https://ollama.com/search?c=tools ollama: (model) => { if ( diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 110229e03..26d319d83 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.250", + "version": "0.9.251", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.250", + "version": "0.9.251", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 535a3074f..c58628cf0 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -6,6 +6,7 @@ import { MessageContent, MessagePart, RangeInFile, + TextMessagePart, } from "core"; import { stripImages } from "core/util/messageContent"; import { IIdeMessenger } from "../../context/IdeMessenger"; @@ -65,7 +66,7 @@ async function resolveEditorContent({ } if (parts[parts.length - 1]?.type === "text") { - parts[parts.length - 1].text += "\n" + text; + (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; } else { parts.push({ type: "text", text }); } @@ -88,7 +89,7 @@ async function resolveEditorContent({ contextItem.content + "\n```"; if (parts[parts.length - 1]?.type === "text") { - parts[parts.length - 1].text += "\n" + text; + (parts[parts.length - 1] as TextMessagePart).text += "\n" + text; } else { parts.push({ type: "text", @@ -181,9 +182,10 @@ async function resolveEditorContent({ if (slashCommand) { let lastTextIndex = findLastIndex(parts, (part) => part.type === "text"); - const lastPart = `${slashCommand} ${parts[lastTextIndex]?.text || ""}`; + const lastTextPart = parts[lastTextIndex] as TextMessagePart; + const lastPart = `${slashCommand} ${lastTextPart?.text || ""}`; if (parts.length > 0) { - parts[lastTextIndex].text = lastPart; + lastTextPart.text = lastPart; } else { parts = [{ type: "text", text: lastPart }]; } diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 7bfc73470..0883ec3eb 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -96,7 +96,7 @@ export const gatherContext = createAsyncThunk< if (promptPreamble) { if (typeof content === "string") { content = promptPreamble + content; - } else { + } else if (content[0].type === "text") { content[0].text = promptPreamble + content[0].text; } } From b88f795036999782e166fa701407d4fb0a457136 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 12 Jan 2025 21:57:26 -0800 Subject: [PATCH 02/33] gemini tool support working --- core/llm/llms/Gemini.ts | 40 ++++++++++++++++++++++++++-- core/tools/definitions/searchWeb.ts | 2 +- gui/src/redux/slices/sessionSlice.ts | 4 ++- 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 0cc470df3..2eae9aca2 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,5 +1,6 @@ import { r } from "tar"; import { + AssistantChatMessage, ChatMessage, CompletionOptions, LLMOptions, @@ -153,12 +154,24 @@ class Gemini extends BaseLLM { .filter((msg) => !(msg.role === "system" && isV1API)) .map((msg) => { if (msg.role === "tool") { + let fn_name = ""; + const lastToolCallMessage = messages.findLast( + (msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name, + ) as AssistantChatMessage; + if (lastToolCallMessage) { + fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!; + } + if (!fn_name) { + console.warn( + "Sending tool call response for unidentified tool call", + ); + } return { role: "user", parts: [ { functionResponse: { - name: msg.toolCallId, // FIX SHOULD BE NAME NOT ID + name: fn_name || "unknown", response: { output: msg.content, // "output" key is opinionated - not all functions will output objects }, @@ -167,7 +180,7 @@ class Gemini extends BaseLLM { ], }; } - return { + const assistantMsg = { role: msg.role === "assistant" ? ("model" as const) : ("user" as const), parts: @@ -175,6 +188,20 @@ class Gemini extends BaseLLM { ? [{ text: msg.content }] : msg.content.map(this.continuePartToGeminiPart), }; + if (msg.role === "assistant" && msg.toolCalls) { + msg.toolCalls.forEach((toolCall) => { + if (toolCall.function?.name && toolCall.function?.arguments) { + assistantMsg.parts.push({ + functionCall: { + name: toolCall.function.name, + args: JSON.parse(toolCall.function.arguments), + }, + }); + } + }); + } + + return assistantMsg; }), }; if (options) { @@ -202,7 +229,16 @@ class Gemini extends BaseLLM { if ( tool.function.parameters && "type" in tool.function.parameters + // && typeof tool.function.parameters.type === "string" ) { + // const paramType = "TYPE_UNSPECIFIED" + // | "STRING" + // | "NUMBER" + // | "INTEGER" + // | "BOOLEAN" + // | "ARRAY" + // | "OBJECT" + if (tool.function.parameters.type === "object") { // Gemini can't take an empty object // So if empty object param is present just don't add parameters diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index eb8e58c99..e5f2844cd 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -13,7 +13,7 @@ export const searchWebTool: Tool = { "Performs a web search, returning top results. This tool should only be called for questions that require external knowledge. Common programming questions do not require web search.", parameters: { type: "object", - required: ["query"], + required: ["repo_url"], properties: { repo_url: { type: "string", diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 0fbfa3bfe..c605934aa 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -323,13 +323,13 @@ export const sessionSlice = createSlice({ const historyItem: ChatHistoryItemWithMessageId = { message: { ...message, + content: renderChatMessage(message), id: uuidv4(), }, contextItems: [], }; if (message.role === "assistant" && message.toolCalls?.[0]) { const toolCallDelta = message.toolCalls[0]; - if ( toolCallDelta.id && toolCallDelta.function?.arguments && @@ -347,6 +347,8 @@ export const sessionSlice = createSlice({ } else { // Add to the existing message if (message.content) { + // Note this only works because new message above + // was already rendered from parts to string lastMessage.content += renderChatMessage(message); } else if ( message.role === "assistant" && From de9e25c7e0e04d434abec88c1afe0978cbafb5da Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 12 Jan 2025 22:28:02 -0800 Subject: [PATCH 03/33] fix type bugs --- .vscode/settings.json | 3 ++- core/llm/llms/Asksage.ts | 2 +- core/llm/llms/Gemini.ts | 4 +++- core/llm/openaiTypeConverters.ts | 4 +++- core/util/findLast.ts | 11 +++++++++++ core/util/messageContent.ts | 3 ++- gui/src/redux/thunks/streamResponse.ts | 13 +++++++++++-- 7 files changed, 33 insertions(+), 7 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 97782cdcc..dd446726a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -42,5 +42,6 @@ "extensions/.continue-debug": true // "sync/**": true }, - "eslint.workingDirectories": ["./core"] + "eslint.workingDirectories": ["./core"], + "typescript.tsdk": "node_modules/typescript/lib" } diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index aa8125e4d..f3b445df4 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -57,7 +57,7 @@ class Asksage extends BaseLLM { ? message.content : message.content .filter((part) => part.type === "text") - .map((part) => part.text) + .map((part) => (part as TextMessagePart).text) .join(""), }; } diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 2eae9aca2..c0940dbfd 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -17,6 +17,7 @@ import { GeminiGenerationConfig, GeminiToolFunctionDeclaration, } from "./gemini-types.js"; +import { findLast } from "../../util/findLast.js"; class Gemini extends BaseLLM { static providerName = "gemini"; @@ -155,7 +156,8 @@ class Gemini extends BaseLLM { .map((msg) => { if (msg.role === "tool") { let fn_name = ""; - const lastToolCallMessage = messages.findLast( + const lastToolCallMessage = findLast( + messages, (msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name, ) as AssistantChatMessage; if (lastToolCallMessage) { diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index c3477dc84..79a259ce0 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -40,7 +40,9 @@ export function toChatMessage( content: typeof message.content === "string" ? message.content || " " // LM Studio (and other providers) don't accept empty content - : message.content.filter((part) => part.type === "text"), + : message.content + .filter((part) => part.type === "text") + .map((part) => part as TextMessagePart), // can remove with newer typescript version }; if (message.toolCalls) { diff --git a/core/util/findLast.ts b/core/util/findLast.ts index fb39829e7..9e99fd473 100644 --- a/core/util/findLast.ts +++ b/core/util/findLast.ts @@ -12,3 +12,14 @@ export function findLastIndex( } return lastIndex; } + +export function findLast( + arr: T[], + criterion: (item: T) => any, +): T | undefined { + for (let i = arr.length - 1; i >= 0; i--) { + if (criterion(arr[i])) { + return arr[i]; + } + } +} diff --git a/core/util/messageContent.ts b/core/util/messageContent.ts index b1c91ca17..89462a1bf 100644 --- a/core/util/messageContent.ts +++ b/core/util/messageContent.ts @@ -3,6 +3,7 @@ import { ContextItem, MessageContent, MessagePart, + TextMessagePart, } from "../index"; export function stripImages(messageContent: MessageContent): string { @@ -12,7 +13,7 @@ export function stripImages(messageContent: MessageContent): string { return messageContent .filter((part) => part.type === "text") - .map((part) => part.text) + .map((part) => (part as TextMessagePart).text) .join("\n"); } diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index fdea6d8fb..1c191b662 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -1,6 +1,11 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; import { JSONContent } from "@tiptap/core"; -import { InputModifiers, MessageContent, SlashCommandDescription } from "core"; +import { + InputModifiers, + MessageContent, + SlashCommandDescription, + TextMessagePart, +} from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderChatMessage } from "core/util/messageContent"; import posthog from "posthog-js"; @@ -28,7 +33,11 @@ const getSlashCommandForInput = ( let lastText = typeof input === "string" ? input - : input.filter((part) => part.type === "text").slice(-1)[0]?.text || ""; + : ( + input.filter((part) => part.type === "text").slice(-1)[0] as + | TextMessagePart + | undefined + )?.text || ""; if (lastText.startsWith("/")) { slashCommandName = lastText.split(" ")[0].substring(1); From cd637e6282d7554b18bab2808e637ca9a4aecb67 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 14 Jan 2025 13:25:41 -0800 Subject: [PATCH 04/33] streamline... streaming --- core/core.ts | 41 +++++++++------ core/llm/llms/Ollama.ts | 6 +-- core/protocol/core.ts | 32 +++--------- core/protocol/util.ts | 52 ++++++++++++++++--- extensions/vscode/src/webviewProtocol.ts | 26 ++++++---- gui/src/context/IdeMessenger.ts | 63 ++++++++++++----------- gui/src/redux/thunks/streamNormalInput.ts | 5 +- 7 files changed, 129 insertions(+), 96 deletions(-) diff --git a/core/core.ts b/core/core.ts index 7316f9aac..454af68ee 100644 --- a/core/core.ts +++ b/core/core.ts @@ -43,7 +43,14 @@ import { Telemetry } from "./util/posthog"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; -import { type ContextItemId, type IDE, type IndexingProgressUpdate } from "."; +import { + ChatMessage, + DiffLine, + PromptLog, + type ContextItemId, + type IDE, + type IndexingProgressUpdate, +} from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -395,7 +402,7 @@ export class Core { configHandler: ConfigHandler, abortedMessageIds: Set, msg: Message, - ) { + ): AsyncGenerator { const { config } = await configHandler.loadConfig(); if (!config) { throw new Error("Config not loaded"); @@ -431,7 +438,7 @@ export class Core { const chunk = next.value; - yield { content: chunk }; + yield chunk; next = await gen.next(); } @@ -448,7 +455,11 @@ export class Core { true, ); - return { done: true, content: next.value }; + if (!next.done) { + throw new Error("Will never happen"); + } + + return next.value; } on("llm/streamChat", (msg) => @@ -458,9 +469,8 @@ export class Core { async function* llmStreamComplete( configHandler: ConfigHandler, abortedMessageIds: Set, - msg: Message, - ) { + ): AsyncGenerator { const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamComplete( msg.data.prompt, @@ -482,11 +492,13 @@ export class Core { }); break; } - yield { content: next.value }; + yield next.value; next = await gen.next(); } - - return { done: true, content: next.value }; + if (!next.done) { + throw new Error("This will never happen"); + } + return next.value; } on("llm/streamComplete", (msg) => @@ -548,7 +560,7 @@ export class Core { abortedMessageIds: Set, msg: Message, messenger: IMessenger, - ) { + ): AsyncGenerator { const { input, history, @@ -613,7 +625,7 @@ export class Core { break; } if (content) { - yield { content }; + yield content; } } } catch (e) { @@ -621,7 +633,6 @@ export class Core { } finally { clearInterval(checkActiveInterval); } - yield { done: true, content: "" }; } on("command/run", (msg) => runNodeJsSlashCommand( @@ -652,7 +663,7 @@ export class Core { configHandler: ConfigHandler, abortedMessageIds: Set, msg: Message, - ) { + ): AsyncGenerator { const data = msg.data; const llm = await configHandler.llmFromTitle(msg.data.modelTitle); for await (const diffLine of streamDiffLines( @@ -667,10 +678,8 @@ export class Core { abortedMessageIds.delete(msg.messageId); break; } - yield { content: diffLine }; + yield diffLine; } - - return { done: true }; } on("streamDiffLines", (msg) => diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index caa00e923..57d2121f9 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -273,10 +273,8 @@ class Ollama extends BaseLLM { content: "", }; - if (typeof message.content === "string") { - ollamaMessage.content = message.content; - } else { - ollamaMessage.content = renderChatMessage(message); + ollamaMessage.content = renderChatMessage(message); + if (Array.isArray(message.content)) { const images: string[] = []; message.content.forEach((part) => { if (part.type === "imageUrl" && part.imageUrl) { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 9495dc3b2..5fa84456a 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,5 +1,6 @@ import { AutocompleteInput } from "../autocomplete/util/types"; import { ProfileDescription } from "../config/ConfigHandler"; +import { ConfigResult } from "../config/load"; import type { BrowserSerializedContinueConfig, @@ -14,6 +15,7 @@ import type { LLMFullCompletionOptions, ModelDescription, ModelRoles, + PromptLog, RangeInFile, SerializedContinueConfig, Session, @@ -21,28 +23,6 @@ import type { SiteIndexingConfig, ToolCall, } from "../"; -import { ConfigResult } from "../config/load"; - -export type ProtocolGeneratorYield = { - done?: boolean; - content: T; -}; -export type ProtocolGeneratorType = AsyncGenerator< - ProtocolGeneratorYield ->; - -export type AsyncGeneratorYieldType = - T extends AsyncGenerator - ? Y extends ProtocolGeneratorYield - ? PR - : never - : never; -// export type AsyncGeneratorReturnType = -// T extends AsyncGenerator -// ? R extends ProtocolGeneratorYield -// ? PR -// : never -// : never; export type OnboardingModes = | "Local" @@ -120,7 +100,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { historyIndex: number; selectedCode: RangeInFile[]; }, - ProtocolGeneratorType, + AsyncGenerator, ]; "llm/complete": [ { @@ -137,7 +117,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { completionOptions: LLMFullCompletionOptions; title: string; }, - ProtocolGeneratorType, + AsyncGenerator, ]; "llm/streamChat": [ { @@ -145,7 +125,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { completionOptions: LLMFullCompletionOptions; title: string; }, - ProtocolGeneratorType, + AsyncGenerator, ]; streamDiffLines: [ { @@ -156,7 +136,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { language: string | undefined; modelTitle: string | undefined; }, - ProtocolGeneratorType, + AsyncGenerator, ]; "chatDescriber/describe": [ { diff --git a/core/protocol/util.ts b/core/protocol/util.ts index c9fe3af1b..8b5477249 100644 --- a/core/protocol/util.ts +++ b/core/protocol/util.ts @@ -1,17 +1,53 @@ import { FromWebviewProtocol } from "."; -interface ErrorWebviewMessengerResult { - done: boolean; +export interface ErrorWebviewMessage { status: "error"; error: string; + done: true; } -interface SuccessWebviewMessengerResult { - done: boolean; +export interface SuccessWebviewSingleMessage { + done: true; status: "success"; - content: FromWebviewProtocol[T][1]; + content: T; } -export type WebviewMessengerResult = - | ErrorWebviewMessengerResult - | SuccessWebviewMessengerResult; +export type WebviewSingleMessage = + | ErrorWebviewMessage + | SuccessWebviewSingleMessage; + +export type WebviewSingleProtocolMessage = + WebviewSingleMessage; + +// Generators +export type GeneratorYieldType = + T extends AsyncGenerator ? Yield : never; +export type GeneratorReturnType = + T extends AsyncGenerator ? Return : never; + +type SuccessWebviewGeneratorMessage = + | { + status: "success"; + done: false; + content: T; + } + | { + status: "success"; + done: true; + content: R; + }; + +export type WebviewGeneratorMessage = + | SuccessWebviewGeneratorMessage + | ErrorWebviewMessage; + +export type WebviewProtocolGeneratorMessage< + T extends keyof FromWebviewProtocol, +> = WebviewGeneratorMessage< + GeneratorYieldType, + GeneratorReturnType +>; + +export type WebviewMessage = + | WebviewSingleMessage + | WebviewGeneratorMessage; diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index bfbb37ce6..c64338705 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -1,6 +1,5 @@ import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; import { Message } from "core/protocol/messenger"; -import { WebviewMessengerResult } from "core/protocol/util"; import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; import { Telemetry } from "core/util/posthog"; import { v4 as uuidv4 } from "uuid"; @@ -51,34 +50,40 @@ export class VsCodeWebviewProtocol this._webview = webView; this._webviewListener?.dispose(); - this._webviewListener = this._webview.onDidReceiveMessage(async (msg) => { - if (!msg.messageType || !msg.messageId) { + const handleMessage = async (msg: Message): Promise => { + if (!("messageType" in msg) || !("messageId" in msg)) { throw new Error(`Invalid webview protocol msg: ${JSON.stringify(msg)}`); } - const respond = (message: WebviewMessengerResult) => + const respond = (message: any) => this.send(msg.messageType, message, msg.messageId); - const handlers = this.listeners.get(msg.messageType) || []; + const handlers = + this.listeners.get(msg.messageType as keyof FromWebviewProtocol) || []; for (const handler of handlers) { try { const response = await handler(msg); + // For generator types e.g. llm/streamChat if ( response && typeof response[Symbol.asyncIterator] === "function" ) { let next = await response.next(); while (!next.done) { - respond(next.value); + respond({ + done: false, + content: next.value, + status: "success", + }); next = await response.next(); } respond({ done: true, - content: next.value?.content, + content: next.value, status: "success", }); } else { - respond({ done: true, content: response ?? {}, status: "success" }); + respond({ content: response, status: "success" }); } } catch (e: any) { respond({ done: true, error: e.message, status: "error" }); @@ -92,7 +97,6 @@ export class VsCodeWebviewProtocol stringified.includes("llm/streamChat") || stringified.includes("chatDescriber/describe") ) { - // handle these errors in the GUI return; } @@ -143,7 +147,9 @@ export class VsCodeWebviewProtocol } } } - }); + }; + + this._webviewListener = this._webview.onDidReceiveMessage(handleMessage); } constructor(private readonly reloadConfig: () => void) {} diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index 1955f4f4c..745c4b431 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -1,16 +1,19 @@ import { ChatMessage, IDE, LLMFullCompletionOptions, PromptLog } from "core"; import type { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; -import { WebviewMessengerResult } from "core/protocol/util"; +import { + GeneratorReturnType, + GeneratorYieldType, + WebviewMessage, + WebviewProtocolGeneratorMessage, + WebviewSingleMessage, + WebviewSingleProtocolMessage, +} from "core/protocol/util"; import { MessageIde } from "core/protocol/messenger/messageIde"; import { Message } from "core/protocol/messenger"; import { createContext } from "react"; import { v4 as uuidv4 } from "uuid"; import "vscode-webview"; import { isJetBrains } from "../util"; -import { - AsyncGeneratorYieldType, - ProtocolGeneratorYield, -} from "core/protocol/core"; interface vscode { postMessage(message: any): vscode; @@ -35,20 +38,23 @@ export interface IIdeMessenger { request( messageType: T, data: FromWebviewProtocol[T][0], - ): Promise>; + ): Promise>; streamRequest( messageType: T, data: FromWebviewProtocol[T][0], cancelToken?: AbortSignal, - ): AsyncGenerator; + ): AsyncGenerator< + GeneratorYieldType[], + GeneratorReturnType | undefined + >; llmStreamChat( modelTitle: string, cancelToken: AbortSignal | undefined, messages: ChatMessage[], options?: LLMFullCompletionOptions, - ): AsyncGenerator; + ): AsyncGenerator; ide: IDE; } @@ -140,14 +146,14 @@ export class IdeMessenger implements IIdeMessenger { request( messageType: T, data: FromWebviewProtocol[T][0], - ): Promise> { + ): Promise> { const messageId = uuidv4(); return new Promise((resolve) => { const handler = (event: any) => { if (event.data.messageId === messageId) { window.removeEventListener("message", handler); - resolve(event.data.data as WebviewMessengerResult); + resolve(event.data.data as WebviewSingleMessage); } }; window.addEventListener("message", handler); @@ -168,24 +174,30 @@ export class IdeMessenger implements IIdeMessenger { messageType: T, data: FromWebviewProtocol[T][0], cancelToken?: AbortSignal, - ): AsyncGenerator[], any> { - type GenYield = AsyncGeneratorYieldType; - // type GenReturn = AsyncGeneratorReturnType; - + ): AsyncGenerator< + GeneratorYieldType[], + GeneratorReturnType | undefined + > { const messageId = uuidv4(); this.post(messageType, data, messageId); - const buffer: GenYield[] = []; + const buffer: GeneratorYieldType[] = []; let index = 0; let done = false; - let returnVal = undefined; + let returnVal: GeneratorReturnType | undefined = + undefined; + // This handler receieves individual WebviewMessengerResults + // And pushes them to buffer const handler = (event: { - data: Message>; + data: Message>; }) => { if (event.data.messageId === messageId) { const responseData = event.data.data; + if ("error" in responseData) { + throw new Error(responseData.error); + } if (responseData.done) { window.removeEventListener("message", handler); done = true; @@ -217,6 +229,9 @@ export class IdeMessenger implements IIdeMessenger { yield chunks; } + if (!returnVal) { + return undefined; + } return returnVal; } catch (e) { throw e; @@ -230,7 +245,7 @@ export class IdeMessenger implements IIdeMessenger { cancelToken: AbortSignal | undefined, messages: ChatMessage[], options: LLMFullCompletionOptions = {}, - ): AsyncGenerator { + ): AsyncGenerator { const gen = this.streamRequest( "llm/streamChat", { @@ -246,17 +261,7 @@ export class IdeMessenger implements IIdeMessenger { yield next.value; next = await gen.next(); } - - if (!next.done) { - throw new Error(); - } - - return { - modelTitle: next.value.content?.modelTitle, - prompt: next.value.content?.prompt, - completion: next.value.content?.completion, - completionOptions: next.value.content?.completionOptions, - }; + return next.value; } } diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 229140c8e..9a19a471c 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -52,13 +52,12 @@ export const streamNormalInput = createAsyncThunk< break; } - const updates = next.value; - dispatch(streamUpdate(updates)); + dispatch(streamUpdate(next.value)); next = await gen.next(); } // Attach prompt log - if (next.done) { + if (next.done && next.value) { dispatch(addPromptCompletionPair([next.value])); } From 9d77aef89e9a91a58b7ac4c693bd70a6bfe62cba Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 14 Jan 2025 13:30:01 -0800 Subject: [PATCH 05/33] streaming content bug fix p2 --- gui/src/context/IdeMessenger.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.ts index 745c4b431..885d30fbe 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.ts @@ -187,6 +187,7 @@ export class IdeMessenger implements IIdeMessenger { let done = false; let returnVal: GeneratorReturnType | undefined = undefined; + let error: string | null = null; // This handler receieves individual WebviewMessengerResults // And pushes them to buffer @@ -196,7 +197,9 @@ export class IdeMessenger implements IIdeMessenger { if (event.data.messageId === messageId) { const responseData = event.data.data; if ("error" in responseData) { - throw new Error(responseData.error); + error = responseData.error; + return; + // throw new Error(responseData.error); } if (responseData.done) { window.removeEventListener("message", handler); @@ -216,6 +219,9 @@ export class IdeMessenger implements IIdeMessenger { try { while (!done) { + if (error) { + throw error; + } if (buffer.length > index) { const chunks = buffer.slice(index); index = buffer.length; From 36277801508e67f33d4f1a764ff440c284620795 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 14 Jan 2025 14:47:20 -0800 Subject: [PATCH 06/33] protocol type error --- core/protocol/util.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/protocol/util.ts b/core/protocol/util.ts index 8b5477249..ab2225c84 100644 --- a/core/protocol/util.ts +++ b/core/protocol/util.ts @@ -17,7 +17,7 @@ export type WebviewSingleMessage = | SuccessWebviewSingleMessage; export type WebviewSingleProtocolMessage = - WebviewSingleMessage; + WebviewSingleMessage; // Generators export type GeneratorYieldType = From a80a27720bdc61effda7a43cd5d22fa3d55b562b Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 14 Jan 2025 15:53:37 -0800 Subject: [PATCH 07/33] bugfix: binary build issues --- binary/build.js | 4 ++++ .../intellij/.run/Start GUI Dev Server.run.xml | 2 +- extensions/intellij/CONTRIBUTING.md | 17 +++++++++++++++-- extensions/intellij/build.gradle.kts | 12 +++++------- .../e2e/Autocomplete.kt | 2 +- .../continueintellijextension/e2e/GUI.kt | 2 +- .../continueintellijextension/e2e/Onboarding.kt | 2 +- 7 files changed, 28 insertions(+), 13 deletions(-) diff --git a/binary/build.js b/binary/build.js index 045fb64f2..e01358cfa 100644 --- a/binary/build.js +++ b/binary/build.js @@ -118,6 +118,10 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { } (async () => { + // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found + // This is only needed for our `pkg` command + fs.writeFileSync("out/package.json", ""); + console.log("[info] Downloading prebuilt lancedb..."); for (const target of targets) { if (targetToLanceDb[target]) { diff --git a/extensions/intellij/.run/Start GUI Dev Server.run.xml b/extensions/intellij/.run/Start GUI Dev Server.run.xml index bd98d3f57..5f574019a 100644 --- a/extensions/intellij/.run/Start GUI Dev Server.run.xml +++ b/extensions/intellij/.run/Start GUI Dev Server.run.xml @@ -5,7 +5,7 @@