diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 3c33bfe1c..f629f9331 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -5,6 +5,7 @@ on: branches: - main paths: + - "extensions/intellij/**" - "extensions/vscode/**" - "core/**" - "gui/**" @@ -96,7 +97,7 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} install-gui: - needs: [install-root, install-core] + needs: [ install-root, install-core ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -157,7 +158,7 @@ jobs: npx tsc --noEmit binary-checks: - needs: [install-root, install-core] + needs: [ install-root, install-core ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -193,7 +194,7 @@ jobs: npx tsc --noEmit install-vscode: - needs: [install-root, install-core] + needs: [ install-root, install-core ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -282,7 +283,7 @@ jobs: vscode-get-test-file-matrix: runs-on: ubuntu-latest - needs: [install-root, install-vscode] + needs: [ install-root, install-vscode ] outputs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: @@ -311,7 +312,7 @@ jobs: vscode-package-extension: runs-on: ubuntu-latest - needs: [install-vscode, install-core] + needs: [ install-vscode, install-core ] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -343,7 +344,7 @@ jobs: vscode-download-e2e-dependencies: runs-on: ubuntu-latest - needs: [install-vscode, install-core] + needs: [ install-vscode, install-core ] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -389,7 +390,7 @@ jobs: fail-fast: false matrix: test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }} - command: ["e2e:ci:run", "e2e:ci:run-yaml"] + command: [ "e2e:ci:run", "e2e:ci:run-yaml" ] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -439,7 +440,6 @@ jobs: run: | cd extensions/vscode TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} - env: DISPLAY: :99 @@ -451,7 +451,7 @@ jobs: path: extensions/vscode/e2e/storage/screenshots gui-tests: - needs: [install-gui, install-core] + needs: [ install-gui, install-core ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -482,7 +482,7 @@ jobs: npm test jetbrains-tests: - needs: [install-root, core-checks] + needs: [ install-root, core-checks ] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -552,7 +552,7 @@ jobs: with: url: http://127.0.0.1:8082 max-attempts: 15 - retry-delay: 5s + retry-delay: 30s - name: Run tests run: | @@ -578,4 +578,4 @@ jobs: with: name: jb-failure-report path: | - ${{ github.workspace }}/extensions/intellij/build/reports + ${{ github.workspace }}/extensions/intellij/build/reports \ No newline at end of file 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/binary/build.js b/binary/build.js index 045fb64f2..11aaf5c59 100644 --- a/binary/build.js +++ b/binary/build.js @@ -118,6 +118,22 @@ 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 at build time + fs.writeFileSync( + "out/package.json", + JSON.stringify( + { + name: "binary", + version: "1.0.0", + author: "Continue Dev, Inc", + license: "Apache-2.0", + }, + undefined, + 2, + ), + ); + console.log("[info] Downloading prebuilt lancedb..."); for (const target of targets) { if (targetToLanceDb[target]) { @@ -263,9 +279,12 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { // Informs the `continue-binary` of where to look for node_sqlite3.node // https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found - fs.writeFileSync(`${targetDir}/package.json`, ""); + // fs.writeFileSync(`${targetDir}/package.json`, ""); } + // Cleanup - this is needed when running locally + fs.rmSync("out/package.json"); + const pathsToVerify = []; for (const target of targets) { const exe = target.startsWith("win") ? ".exe" : ""; diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md deleted file mode 100644 index ab6e9adfb..000000000 --- a/core/autocomplete/README.md +++ /dev/null @@ -1,158 +0,0 @@ -# Tab Autocomplete (beta) - -Continue now provides support for tab autocomplete in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains IDEs](https://plugins.jetbrains.com/plugin/22707-continue/edit). We will be greatly improving the experience over the next few releases, and it is always helpful to hear feedback. If you have any problems or suggestions, please let us know in our [Discord](https://discord.gg/vapESyrFmJ). - -## Setting up with Ollama (default) - -We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model: - -```bash -ollama run qwen2.5-coder:1.5b-base -``` - -Once it has been downloaded, you should begin to see completions in VS Code. - -## Setting up with LM Studio - -You can also set up tab-autocomplete with a local LM Studio instance by following these steps: - -1. Download the latest version of LM Studio from [here](https://lmstudio.ai/) -2. Download a model (e.g. search for `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF` and choose one of the options there) -3. Go to the server section (button is on the left), select your model from the dropdown at the top, and click "Start Server" -4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`); this will be used as the "model" attribute in Continue -5. Go to Continue and modify the configurations for a [custom model](#setting-up-a-custom-model) -6. Set the "provider" to `lmstudio` and the "model" to the path copied earlier - -Example: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5b", - "model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF", - "provider": "lmstudio" - } -} -``` - -## Setting up a custom model - -All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote vLLM instance you would edit your `config.json` like this (note that it is not inside the models array), filling in the correct model name and vLLM endpoint: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "openai", - "model": "", - "apiBase": "" - }, - ... -} -``` - -As another example, say you want to use a different model, `deepseek-coder:6.7b-base`, with Ollama: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "deepseek-coder:6.7b-base" - }, - ... -} -``` - -If you aren't yet familiar with the available options, you can learn more in our [overview](../setup/overview.md). - -### What model should I use? - -If you are running the model locally, we recommend `qwen2.5-coder:1.5b`. - -If you have a bit more compute, or are running a model in the cloud, you can upgrade to `qwen2.5-coder:7b`. - -Regardless of what you are willing to spend, we do not recommend using GPT or Claude for autocomplete. Learn why [below](#i-want-better-completions-should-i-use-gpt-4). - -## Configuration Options - -The following can be configured in `config.json`: - -### `tabAutocompleteModel` - -This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `qwen2.5-coder:1.5b`, or `starcoder-3b`. - -### `tabAutocompleteOptions` - -This object allows you to customize the behavior of tab-autocomplete. The available options are: - -- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) -- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) -- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) -- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) -- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) -- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String) -- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". - -### Full example - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "qwen2.5-coder:1.5b-base", - "apiBase": "https://" - }, - "tabAutocompleteOptions": { - "maxPromptTokens": 400, - "prefixPercentage": 0.5 - } -} -``` - -## Troubleshooting - -### I want better completions, should I use GPT-4? - -Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance. - -### I'm not seeing any completions - -Follow these steps to ensure that everything is set up correctly: - -1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar). -2. Make sure you have downloaded Ollama. -3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded. -4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. -5. If you are using another Ollama model for chat and your resources are limited, this will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. A resolution for this could be using the same model for chat and autocomplete. -6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). -7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. - -### Completions are slow - -Depending on your hardware, you may want to try a smaller, faster model. If 3b isn't working for you we recommend trying `deepseek-coder:1.3b-base`. - -### Completions don't know about my code - -We are working on this! Right now Continue uses the Language Server Protocol to add definitions to the prompt, as well as using similarity search over recently edited files. We will be improving the accuracy of this system greatly over the next few weeks. - -### Completions contain formatting errors - -If you're seeing a common pattern of mistake that might be helpful to report, please share in Discord. We will do our best to fix it as soon as possible. - -## How to turn off autocomplete - -### VS Code - -Click the "Continue" button in the status panel at the bottom right of the screen. The checkmark will become a "cancel" symbol and you will no longer see completions. You can click again to turn it back on. - -Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete". - -### JetBrains - -Open Settings -> Tools -> Continue and uncheck the box for "Enable Tab Autocomplete". - -### Feedback - -If you're turning off autocomplete, we'd love to hear how we can improve! Please let us know in our [Discord](https://discord.gg/vapESyrFmJ) or file an issue on GitHub. 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/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 3e90b8c4f..626e237db 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -15,7 +15,6 @@ import { GlobalContext } from "../util/GlobalContext.js"; import { getConfigJsonPath } from "../util/paths.js"; import { ConfigResult } from "@continuedev/config-yaml"; -import { pathToFileURL } from "url"; import { controlPlaneEnv } from "../control-plane/env.js"; import { usePlatform } from "../control-plane/flags.js"; import { @@ -29,6 +28,7 @@ import { ProfileDescription, ProfileLifecycleManager, } from "./ProfileLifecycleManager.js"; +import { localPathToUri } from "../util/pathToUri.js"; export type { ProfileDescription }; @@ -95,7 +95,7 @@ export class ConfigHandler { async openConfigProfile(profileId?: string) { let openProfileId = profileId || this.selectedProfileId; if (openProfileId === "local") { - await this.ide.openFile(pathToFileURL(getConfigJsonPath()).toString()); + await this.ide.openFile(localPathToUri(getConfigJsonPath())); } else { await this.ide.openUrl(`${controlPlaneEnv.APP_URL}${openProfileId}`); } diff --git a/core/config/load.ts b/core/config/load.ts index 6aaf31046..689f53ca5 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -73,6 +73,7 @@ import { import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; // import { isSupportedLanceDbCpuTarget } from "./util"; import { validateConfig } from "./validation.js"; +import { localPathToUri } from "../util/pathToUri"; function resolveSerializedConfig(filepath: string): SerializedContinueConfig { let content = fs.readFileSync(filepath, "utf8"); @@ -813,7 +814,7 @@ async function loadFullConfigNode( "Could not load config.ts as absolute path, retrying as file url ...", ); try { - module = await import(`file://${configJsPath}`); + module = await import(localPathToUri(configJsPath)); } catch (e) { throw new Error("Could not load config.ts as file url either", { cause: e, diff --git a/core/core.ts b/core/core.ts index dde3091ee..c74f2e539 100644 --- a/core/core.ts +++ b/core/core.ts @@ -43,7 +43,15 @@ 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 { usePlatform } from "./control-plane/flags"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -396,7 +404,7 @@ export class Core { configHandler: ConfigHandler, abortedMessageIds: Set, msg: Message, - ) { + ): AsyncGenerator { const { config } = await configHandler.loadConfig(); if (!config) { throw new Error("Config not loaded"); @@ -432,7 +440,7 @@ export class Core { const chunk = next.value; - yield { content: chunk }; + yield chunk; next = await gen.next(); } @@ -449,7 +457,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) => @@ -459,9 +471,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, @@ -483,11 +494,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) => @@ -549,7 +562,7 @@ export class Core { abortedMessageIds: Set, msg: Message, messenger: IMessenger, - ) { + ): AsyncGenerator { const { input, history, @@ -614,7 +627,7 @@ export class Core { break; } if (content) { - yield { content }; + yield content; } } } catch (e) { @@ -622,7 +635,6 @@ export class Core { } finally { clearInterval(checkActiveInterval); } - yield { done: true, content: "" }; } on("command/run", (msg) => runNodeJsSlashCommand( @@ -653,7 +665,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( @@ -668,10 +680,8 @@ export class Core { abortedMessageIds.delete(msg.messageId); break; } - yield { content: diffLine }; + yield diffLine; } - - return { done: true }; } on("streamDiffLines", (msg) => diff --git a/core/index.d.ts b/core/index.d.ts index 3fc820354..098628c0f 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -300,11 +300,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[]; diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index 211bc3732..517298597 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -14,12 +14,12 @@ import { } from "../test/testDir.js"; import { getIndexSqlitePath } from "../util/paths.js"; -import { pathToFileURL } from "node:url"; import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; import { CodebaseIndex } from "./types.js"; import { walkDir } from "./walkDir.js"; +import { localPathToUri } from "../util/pathToUri.js"; jest.useFakeTimers(); @@ -159,7 +159,7 @@ describe("CodebaseIndexer", () => { test("should have created index folder with all necessary files", async () => { const exists = await testIde.fileExists( - pathToFileURL(getIndexSqlitePath()).toString(), + localPathToUri(getIndexSqlitePath()), ); expect(exists).toBe(true); }); 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..f3b445df4 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 as TextMessagePart).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..c0940dbfd 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,12 +1,23 @@ +import { r } from "tar"; import { + AssistantChatMessage, 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"; +import { findLast } from "../../util/findLast.js"; class Gemini extends BaseLLM { static providerName = "gemini"; @@ -19,7 +30,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 +53,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 +70,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 +103,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 +112,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 +122,7 @@ class Gemini extends BaseLLM { } } - continuePartToGeminiPart(part: MessagePart) { + continuePartToGeminiPart(part: MessagePart): GeminiChatContentPart { return part.type === "text" ? { text: part.text, @@ -135,39 +146,129 @@ 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); + // Convert chat messages to contents + const body: GeminiChatRequestBody = { + contents: messages + .filter((msg) => !(msg.role === "system" && isV1API)) + .map((msg) => { + if (msg.role === "tool") { + let fn_name = ""; + const lastToolCallMessage = findLast( + messages, + (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: fn_name || "unknown", + response: { + output: msg.content, // "output" key is opinionated - not all functions will output objects + }, + }, + }, + ], + }; + } + const assistantMsg = { + role: + msg.role === "assistant" ? ("model" as const) : ("user" as const), + parts: + typeof msg.content === "string" + ? [{ 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), + }, + }); + } + }); + } - const body = { - ...this.convertArgs(options), - contents, - // if this.systemMessage is defined, reformat it for Gemini API - ...(this.systemMessage && - !isV1API && { - systemInstruction: { parts: [{ text: this.systemMessage }] }, + return assistantMsg; }), }; + 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 + // && 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 + 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 +293,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..b9734acb9 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; }; } @@ -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/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 839efda4e..4ed8be1c4 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,55 @@ 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") + .map((part) => part as TextMessagePart), // can remove with newer typescript version + }; + + 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/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index 2998b5f8f..d991d140a 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -16,11 +16,11 @@ export async function getPromptFilesFromDir( return []; } - const paths = await walkDir(dir, ide, { ignoreFiles: [] }); - const promptFilePaths = paths.filter((p) => p.endsWith(".prompt")); - const results = promptFilePaths.map(async (path) => { - const content = await ide.readFile(path); // make a try catch - return { path, content }; + const uris = await walkDir(dir, ide, { ignoreFiles: [] }); + const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); + const results = promptFilePaths.map(async (uri) => { + const content = await ide.readFile(uri); // make a try catch + return { path: uri, content }; }); return Promise.all(results); } catch (e) { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 27f1c92ad..b48b11398 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,6 +1,3 @@ -import { AutocompleteInput } from "../autocomplete/util/types"; -import { ProfileDescription } from "../config/ConfigHandler"; - import { ConfigResult } from "@continuedev/config-yaml"; import type { BrowserSerializedContinueConfig, @@ -15,6 +12,7 @@ import type { LLMFullCompletionOptions, ModelDescription, ModelRoles, + PromptLog, RangeInFile, SerializedContinueConfig, Session, @@ -22,27 +20,8 @@ import type { SiteIndexingConfig, ToolCall, } from "../"; - -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; +import { AutocompleteInput } from "../autocomplete/util/types"; +import { ProfileDescription } from "../config/ConfigHandler"; export type OnboardingModes = | "Local" @@ -120,7 +99,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { historyIndex: number; selectedCode: RangeInFile[]; }, - ProtocolGeneratorType, + AsyncGenerator, ]; "llm/complete": [ { @@ -137,7 +116,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { completionOptions: LLMFullCompletionOptions; title: string; }, - ProtocolGeneratorType, + AsyncGenerator, ]; "llm/streamChat": [ { @@ -145,7 +124,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { completionOptions: LLMFullCompletionOptions; title: string; }, - ProtocolGeneratorType, + AsyncGenerator, ]; streamDiffLines: [ { @@ -156,7 +135,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { language: string | undefined; modelTitle: string | undefined; }, - ProtocolGeneratorType, + AsyncGenerator, ]; "chatDescriber/describe": [ { diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index c4b999521..a638eafb4 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -66,6 +66,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", + "configError", "getDefaultModelTitle", "indexProgress", // Codebase "indexing/statusUpdate", // Docs, etc. diff --git a/core/protocol/util.ts b/core/protocol/util.ts index c9fe3af1b..ab2225c84 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/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/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/core/util/pathToUri.ts b/core/util/pathToUri.ts index 804b4fa99..67a249d74 100644 --- a/core/util/pathToUri.ts +++ b/core/util/pathToUri.ts @@ -4,7 +4,7 @@ import * as URI from "uri-js"; // CAN ONLY BE USED IN CORE -// Converts a local path to a file:// URI +// Converts a local path to a file:/// URI export function localPathToUri(path: string) { const url = pathToFileURL(path); return URI.normalize(url.toString()); diff --git a/extensions/intellij/.run/Start Core Dev Server (CE).run.xml b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml index 7469eb5e8..11b362c2f 100644 --- a/extensions/intellij/.run/Start Core Dev Server (CE).run.xml +++ b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml @@ -5,7 +5,7 @@