Merge branch 'dev' into patch-1

This commit is contained in:
Nate Sesti 2024-10-31 12:27:08 -07:00 • committed by GitHub
commit cbf2c6e714
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
226 changed files with 10732 additions and 5754 deletions

36
.eslintrc.shared.json Normal file
View file

@ -0,0 +1,36 @@
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"plugins": ["@typescript-eslint", "import"],
"rules": {
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off",
"import/order": [
"warn",
{
"groups": [
"builtin",
"external",
"internal",
"parent",
"sibling",
"index",
"object",
"type"
],
"alphabetize": {
"order": "asc",
"caseInsensitive": true
},
"newlines-between": "always"
}
]
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}

View file

@ -4,8 +4,8 @@
## Checklist
- [ ] The base branch of this PR is `dev`, rather than `main`
- [ ] The relevant docs, if any, have been updated or created
- [] The base branch of this PR is `dev`, rather than `main`
- [] The relevant docs, if any, have been updated or created
## Screenshots

View file

@ -20,6 +20,12 @@ jobs:
with:
node-version-file: ".nvmrc"
- name: Cache root node_modules
uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
- name: Cache extension node_modules
uses: actions/cache@v3
with:
@ -44,6 +50,10 @@ jobs:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
- name: root install
run: |
npm ci
- name: extensions/vscode install
run: |
cd extensions/vscode
@ -71,6 +81,7 @@ jobs:
run: |
cd extensions/vscode
npx tsc --noEmit
npm run lint
- name: core checks
run: |

View file

@ -97,7 +97,6 @@ jobs:
with:
node-version-file: ".nvmrc"
# Cache node_modules
- name: Cache core node_modules
uses: actions/cache@v3
with:

View file

@ -255,11 +255,3 @@ jobs:
# with:
# github_token: ${{ secrets.GITHUB_TOKEN }}
# branch: ${{ github.ref }}
# 5 Send to Discord Webhook
- name: Discord Commits
uses: Sniddl/discord-commits@1.7
with:
webhook: ${{ secrets.DISCORD_WEBHOOK }}
template: "avatar-with-link"
include-extras: true

View file

@ -21,6 +21,12 @@ jobs:
with:
node-version-file: ".nvmrc"
- name: Cache root node_modules
uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
- name: Cache extension node_modules
uses: actions/cache@v3
with:
@ -45,6 +51,10 @@ jobs:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
- name: Install Root Dependencies
run: |
npm ci
- name: Install extension Dependencies
run: |
cd extensions/vscode
@ -72,11 +82,13 @@ jobs:
run: |
cd core
npx tsc --noEmit
npm run lint
- name: tsc extensions/vscode
run: |
cd extensions/vscode
npx tsc --noEmit
npm run lint
- name: tsc binary
run: |

3
.gitignore vendored
View file

@ -166,3 +166,6 @@ extensions/intellij/.idea/**
**/.idea/workspace.xml
**/.idea/usage.statistics.xml
**/.idea/shelf/
extensions/intellij/bin
extensions/.continue-debug/

2
.idea/.name generated
View file

@ -1 +1 @@
Continue IntelliJ Extension
continue-intellij-extension

2
.idea/misc.xml generated
View file

@ -4,7 +4,7 @@
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$/extensions/intellij" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="19" project-jdk-type="JavaSDK" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK" />
<component name="SuppressKotlinCodeStyleNotification">
<option name="disableForAll" value="true" />
</component>

10
.idea/modules.xml generated
View file

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.iml" filepath="$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.main.iml" filepath="$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.main.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.test.iml" filepath="$PROJECT_DIR$/.idea/modules/com.github.continuedev.continueintellijextension.continue-intellij-extension.test.iml" />
</modules>
</component>
</project>

View file

@ -1,3 +1,3 @@
<component name="DependencyValidationManager">
<scope name="Continue" pattern="!file[com.github.continuedev.continueintellijextension.continue-intellij-extension]:gui/dist//*&amp;&amp;!file[com.github.continuedev.continueintellijextension.continue-intellij-extension]:extensions/vscode/gui//*&amp;&amp;!file[com.github.continuedev.continueintellijextension.continue-intellij-extension]:core/vendor//*" />
<scope name="Continue" pattern="file[continue-intellij-extension]:*/&amp;&amp;!file[continue-intellij-extension]:binary/bin//*&amp;&amp;!file[continue-intellij-extension]:binary/build//*&amp;&amp;!file[continue-intellij-extension]:binary/out//*&amp;&amp;!file[continue-intellij-extension]:gui/dist//*&amp;&amp;!file[continue-intellij-extension]:extensions/intellij/build//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/bin//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/build//*&amp;&amp;!file[continue-intellij-extension]:extensions/vscode/out//*" />
</component>

24
.vscode/launch.json vendored
View file

@ -20,7 +20,8 @@
"outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
"preLaunchTask": "vscode-extension:build",
"env": {
// "staging" for the preview deployment
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
// "staging" for the preview deployment "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
// "local" for entirely local development of control plane/proxy
// "CONTROL_PLANE_ENV": "staging"
}
@ -38,7 +39,7 @@
"cwd": "${workspaceFolder}/binary",
"env": {
"CONTINUE_DEVELOPMENT": "true",
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/binary/.continue"
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"
}
},
{
@ -137,24 +138,5 @@
"NODE_OPTIONS": "--experimental-vm-modules"
}
}
// {
// "name": "[openai-adapters] Jest Test Debugger, Current Open File",
// "type": "node",
// "request": "launch",
// "runtimeArgs": [
// "--inspect-brk",
// "${workspaceRoot}/packages/openai-adapters/node_modules/jest/bin/jest.js",
// "--runInBand",
// "--config",
// "${workspaceRoot}/packages/openai-adapters/jest.config.mjs",
// "${relativeFile}"
// ],
// "cwd": "${workspaceRoot}/packages/openai-adapters",
// "console": "integratedTerminal",
// "internalConsoleOptions": "neverOpen",
// "env": {
// "NODE_OPTIONS": "--experimental-vm-modules"
// }
// }
]
}

View file

@ -17,7 +17,8 @@
"**/core/vendor/**": true,
"**/gui/dist": true,
"**/extensions/vscode/gui/**": true,
"**/extensions/vscode/out/**": true
"**/extensions/vscode/out/**": true,
"**/extensions/intellij/build/**": true
},
"eslint.workingDirectories": ["./core"]
}

7
.vscode/tasks.json vendored
View file

@ -5,7 +5,7 @@
{
"label": "vscode-extension:build",
"dependsOn": [
// To detect compile errors
// To detect compile errors and output extensions.js
"vscode-extension:tsc",
// To build the React app that is used in the extension
"vscode-extension:continue-ui:build",
@ -21,7 +21,10 @@
},
{
"label": "vscode-extension:esbuild",
"dependsOn": ["vscode-extension:continue-ui:build"],
"dependsOn": [
"vscode-extension:continue-ui:build",
"vscode-extension:tsc"
],
"type": "npm",
"script": "esbuild-watch",
"path": "extensions/vscode",

View file

@ -200,10 +200,9 @@ Continue has support for more than a dozen different LLM "providers", making it
While any model that works with a supported provider can be used with Continue, we keep a list of recommended models that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a model:
- [config_schema.json](./extensions/vscode/config_schema.json) - This is the JSON Schema definition that is used to validate `config.json`. You'll notice a number of rules defined in "definitions.ModelDescription.allOf". Here is where you write rules that can specify something like "for the provider 'anthropic', only models 'claude-2' and 'claude-instant-1' are allowed. Look through all of these rules and make sure that your model is included for providers that support it.
- [modelData.ts](./gui/src/util/modelData.ts) - This file defines that information that is shown in the model selection UI in the side bar. To add a new model:
1. create a `ModelPackage` object, following the lead of the many examples near the top of the file
2. add the `ModelPackage` to the `MODEL_INFO` array if you would like it to be displayed in the "Models" tab
3. if you would like it to be displayed as an option under any of the providers, go to the `PROVIDER_INFO` object and add it to the `packages` array for each provider that you want it to be displayed under. If it is an OS model that should be valid for most providers offering OS models, you might just be able to add it to the `osModels` array as shorthand.
- [AddNewModel page](./gui/src/pages/AddNewModel) - This directory defines which model options are shown in the side bar model selection UI. To add a new model:
1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file
2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed)
- [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this.
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
- [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.

View file

@ -47,12 +47,11 @@
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/config-types": "^1.0.13",
"@continuedev/llm-info": "^1.0.2",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
@ -124,7 +123,6 @@
"cross-env": "^7.0.3",
"esbuild": "0.17.19",
"eslint": "^8",
"eslint-plugin-import": "^2.29.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"myers-diff": "^2.1.0",

View file

@ -1,21 +1,12 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"extends": ["../.eslintrc.shared.json"],
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint", "import"],
"rules": {
"quotes": ["warn", "double", {}],
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/semi": "warn",
"curly": "warn",
"eqeqeq": "warn",
"no-throw-literal": "warn",
"semi": "off",
"@typescript-eslint/no-floating-promises": "warn"
},
"ignorePatterns": ["out", "dist", "**/*.d.ts"]
}
}

View file

@ -1,18 +1,14 @@
import { Mutex } from "async-mutex";
import { open } from "sqlite";
import sqlite3 from "sqlite3";
import { DatabaseConnection } from "../indexing/refreshIndex.js";
import { DatabaseConnection, truncateSqliteLikePattern } from "../indexing/refreshIndex.js";
import { getTabAutocompleteCacheSqlitePath } from "../util/paths.js";
export class AutocompleteLruCache {
private static capacity = 1000;
private mutex = new Mutex();
db: DatabaseConnection;
constructor(db: DatabaseConnection) {
this.db = db;
}
constructor(private db: DatabaseConnection) { }
static async get(): Promise<AutocompleteLruCache> {
const db = await open({
@ -41,7 +37,7 @@ export class AutocompleteLruCache {
// Have to make sure we take the key with shortest length
const result = await this.db.get(
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
prefix,
truncateSqliteLikePattern(prefix),
);
// Validate that the cached compeltion is a valid completion for the prefix

View file

@ -36,7 +36,6 @@ import { RecentlyEditedRange } from "./recentlyEdited.js";
import { RootPathContextService } from "./services/RootPathContextService.js";
import {
avoidPathLineAndEmptyComments,
noTopLevelKeywordsMidline,
skipPrefixes,
stopAtLines,
stopAtRepeatingLines,
@ -50,11 +49,7 @@ import Handlebars from "handlebars";
import { getConfigJsonPath } from "../util/paths.js";
import { BracketMatchingService } from "./services/BracketMatchingService.js";
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
import {
noFirstCharNewline,
onlyWhitespaceAfterEndOfLine,
stopAtStopTokens,
} from "./streamTransforms/charStream.js";
import { stopAtStopTokens } from "./streamTransforms/charStream.js";
export interface AutocompleteInput {
completionId: string;
@ -95,6 +90,7 @@ const autocompleteCache = AutocompleteLruCache.get();
const DOUBLE_NEWLINE = "\n\n";
const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n";
// TODO: Do we want to stop completions when reaching a `/src/` string?
const SRC_DIRECTORY = "/src/";
// Starcoder2 tends to output artifacts starting with the letter "t"
const STARCODER2_T_ARTIFACTS = ["t.", "\nt", "<file_sep>"];
@ -111,6 +107,14 @@ const ERRORS_TO_IGNORE = [
"unexpected server status",
];
const LOCAL_PROVIDERS: ModelProvider[] = [
"ollama",
"lmstudio",
"llama.cpp",
"llamafile",
"text-gen-webui",
];
function formatExternalSnippet(
filepath: string,
snippet: string,
@ -128,14 +132,6 @@ function formatExternalSnippet(
return lines.join("\n");
}
let shownGptClaudeWarning = false;
const nonAutocompleteModels = [
// "gpt",
// "claude",
"mistral",
"instruct",
];
export type GetLspDefinitionsFunction = (
filepath: string,
contents: string,
@ -268,7 +264,10 @@ export class CompletionProvider {
const workspaceDirs = await this.ide.getWorkspaceDirs();
let filepath = input.filepath;
for (const workspaceDir of workspaceDirs) {
if (filepath.startsWith(workspaceDir)) {
const relativePath = path.relative(workspaceDir, filepath);
const relativePathBase = relativePath.split(path.sep).at(0);
const isInWorkspace = !path.isAbsolute(relativePath) && relativePathBase !== "..";
if (isInWorkspace) {
filepath = path.relative(workspaceDir, filepath);
break;
}
@ -334,14 +333,6 @@ export class CompletionProvider {
llm.completionOptions.temperature = 0.01;
}
// Set model-specific options
const LOCAL_PROVIDERS: ModelProvider[] = [
"ollama",
"lmstudio",
"llama.cpp",
"llamafile",
"text-gen-webui",
];
if (
!config.tabAutocompleteOptions?.maxPromptTokens &&
LOCAL_PROVIDERS.includes(llm.providerName)
@ -360,7 +351,7 @@ export class CompletionProvider {
* elsewhere in the code. That said, I'm not yet confident enough to
* remove this.
*/
if (isOnlyWhitespace(outcome.completion)) {
if (options.transform && isOnlyWhitespace(outcome.completion)) {
return undefined;
}
@ -388,11 +379,23 @@ export class CompletionProvider {
// Wait 10 seconds, then assume it wasn't accepted
outcome.accepted = false;
logDevData("autocomplete", outcome);
const { prompt, completion, ...restOfOutcome } = outcome;
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
void Telemetry.capture(
"autocomplete",
{
...restOfOutcome,
accepted: restOfOutcome.accepted,
cacheHit: restOfOutcome.cacheHit,
completionId: restOfOutcome.completionId,
completionOptions: restOfOutcome.completionOptions,
debounceDelay: restOfOutcome.debounceDelay,
fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0],
maxPromptTokens: restOfOutcome.maxPromptTokens,
modelName: restOfOutcome.modelName,
modelProvider: restOfOutcome.modelProvider,
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
useRootPathContext: restOfOutcome.useRootPathContext,
},
true,
);
@ -430,6 +433,33 @@ export class CompletionProvider {
};
}
private isMultiline({
language,
prefix,
suffix,
selectedCompletionInfo,
multilineCompletions,
completeMultiline,
}: {
language: AutocompleteLanguageInfo;
prefix: string;
suffix: string;
selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"];
multilineCompletions: TabAutocompleteOptions["multilineCompletions"];
completeMultiline: boolean;
}) {
let langMultilineDecision = language.useMultiline?.({ prefix, suffix });
if (langMultilineDecision) {
return langMultilineDecision;
} else {
return (
!selectedCompletionInfo && // Only ever single-line if using intellisense selected value
multilineCompletions !== "never" &&
(multilineCompletions === "always" || completeMultiline)
);
}
}
async getTabCompletion(
token: AbortSignal,
options: TabAutocompleteOptions,
@ -453,10 +483,13 @@ export class CompletionProvider {
// Filter
const lang = languageForFilepath(filepath);
const line = fileLines[pos.line] ?? "";
for (const endOfLine of lang.endOfLine) {
if (line.endsWith(endOfLine) && pos.character >= line.length) {
return undefined;
if (options.transform) {
const line = fileLines[pos.line] ?? "";
for (const endOfLine of lang.endOfLine) {
if (line.endsWith(endOfLine) && pos.character >= line.length) {
return undefined;
}
}
}
@ -473,18 +506,6 @@ export class CompletionProvider {
llm.model = TRIAL_FIM_MODEL;
}
if (
!shownGptClaudeWarning &&
nonAutocompleteModels.some((model) => llm.model.includes(model)) &&
!llm.model.toLowerCase().includes("deepseek") &&
!llm.model.toLowerCase().includes("codestral")
) {
shownGptClaudeWarning = true;
throw new Error(
`Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/features/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`,
);
}
// Prompt
let fullPrefix =
getRangeInString(fileContents, {
@ -494,11 +515,10 @@ export class CompletionProvider {
if (input.injectDetails) {
const lines = fullPrefix.split("\n");
fullPrefix = `${lines.slice(0, -1).join("\n")}\n${
lang.singleLineComment
} ${input.injectDetails
.split("\n")
.join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`;
fullPrefix = `${lines.slice(0, -1).join("\n")}\n${lang.singleLineComment
} ${input.injectDetails
.split("\n")
.join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`;
}
const fullSuffix = getRangeInString(fileContents, {
@ -519,17 +539,17 @@ export class CompletionProvider {
let extrasSnippets = options.useOtherFiles
? ((await Promise.race([
this.getDefinitionsFromLsp(
filepath,
fullPrefix + fullSuffix,
fullPrefix.length,
this.ide,
lang,
),
new Promise((resolve) => {
setTimeout(() => resolve([]), 100);
}),
])) as AutocompleteSnippet[])
this.getDefinitionsFromLsp(
filepath,
fullPrefix + fullSuffix,
fullPrefix.length,
this.ide,
lang,
),
new Promise((resolve) => {
setTimeout(() => resolve([]), 100);
}),
])) as AutocompleteSnippet[])
: [];
const workspaceDirs = await this.ide.getWorkspaceDirs();
@ -568,8 +588,8 @@ export class CompletionProvider {
completionOptions,
compilePrefixSuffix = undefined,
} = options.template
? { template: options.template, completionOptions: {} }
: getTemplateForModel(llm.model);
? { template: options.template, completionOptions: {} }
: getTemplateForModel(llm.model);
let prompt: string;
const filename = getBasename(filepath);
@ -640,25 +660,25 @@ export class CompletionProvider {
} else {
const stop = [
...(completionOptions?.stop || []),
...multilineStops,
// ...multilineStops,
...commonStops,
...(llm.model.toLowerCase().includes("starcoder2")
? STARCODER2_T_ARTIFACTS
: []),
...(lang.stopWords ?? []),
...lang.topLevelKeywords.map((word) => `\n${word}`),
// ...lang.topLevelKeywords.map((word) => `\n${word}`),
];
let langMultilineDecision = lang.useMultiline?.({ prefix, suffix });
let multiline: boolean = false;
if (langMultilineDecision) {
multiline = langMultilineDecision;
} else {
multiline =
!input.selectedCompletionInfo && // Only ever single-line if using intellisense selected value
options.multilineCompletions !== "never" &&
(options.multilineCompletions === "always" || completeMultiline);
}
const multiline =
!options.transform ||
this.isMultiline({
multilineCompletions: options.multilineCompletions,
language: lang,
selectedCompletionInfo: input.selectedCompletionInfo,
prefix,
suffix,
completeMultiline,
});
// Try to reuse pending requests if what the user typed matches start of completion
const generator = this.generatorReuseManager.getGenerator(
@ -666,14 +686,14 @@ export class CompletionProvider {
() =>
llm.supportsFim()
? llm.streamFim(prefix, suffix, {
...completionOptions,
stop,
})
...completionOptions,
stop,
})
: llm.streamComplete(prompt, {
...completionOptions,
raw: true,
stop,
}),
...completionOptions,
raw: true,
stop,
}),
multiline,
);
@ -693,46 +713,52 @@ export class CompletionProvider {
}
};
let charGenerator = generatorWithCancellation();
charGenerator = noFirstCharNewline(charGenerator);
charGenerator = onlyWhitespaceAfterEndOfLine(
charGenerator,
lang.endOfLine,
fullStop,
);
charGenerator = stopAtStopTokens(charGenerator, stop);
charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket(
charGenerator,
prefix,
suffix,
filepath,
multiline,
);
let lineGenerator = streamLines(charGenerator);
lineGenerator = stopAtLines(lineGenerator, fullStop);
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
lineGenerator = avoidPathLineAndEmptyComments(
lineGenerator,
lang.singleLineComment,
);
lineGenerator = skipPrefixes(lineGenerator);
lineGenerator = noTopLevelKeywordsMidline(
lineGenerator,
lang.topLevelKeywords,
fullStop,
);
for (const lineFilter of lang.lineFilters ?? []) {
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
if (options.transform) {
// charGenerator = noFirstCharNewline(charGenerator);
// charGenerator = onlyWhitespaceAfterEndOfLine(
// charGenerator,
// lang.endOfLine,
// fullStop,
// );
charGenerator = stopAtStopTokens(charGenerator, stop);
charGenerator =
this.bracketMatchingService.stopOnUnmatchedClosingBracket(
charGenerator,
prefix,
suffix,
filepath,
multiline,
);
}
lineGenerator = streamWithNewLines(lineGenerator);
let lineGenerator = streamLines(charGenerator);
if (options.transform) {
lineGenerator = stopAtLines(lineGenerator, fullStop);
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
lineGenerator = avoidPathLineAndEmptyComments(
lineGenerator,
lang.singleLineComment,
);
lineGenerator = skipPrefixes(lineGenerator);
const finalGenerator = stopAtSimilarLine(
lineGenerator,
lineBelowCursor,
fullStop,
);
// lineGenerator = noTopLevelKeywordsMidline(
// lineGenerator,
// lang.topLevelKeywords,
// fullStop,
// );
for (const lineFilter of lang.lineFilters ?? []) {
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
}
lineGenerator = stopAtSimilarLine(
lineGenerator,
lineBelowCursor,
fullStop,
);
}
const finalGenerator = streamWithNewLines(lineGenerator);
try {
for await (const update of finalGenerator) {
@ -749,12 +775,14 @@ export class CompletionProvider {
return undefined;
}
const processedCompletion = postprocessCompletion({
completion,
prefix,
suffix,
llm,
});
const processedCompletion = options.transform
? postprocessCompletion({
completion,
prefix,
suffix,
llm,
})
: completion;
if (!processedCompletion) {
return undefined;

View file

@ -84,9 +84,13 @@ export class BracketMatchingService {
// Add corresponding open brackets from suffix to stack
// because we overwrite them and the diff is displayed, and this allows something to be edited after that
for (let i = 0; i < suffix.length; i++) {
if (suffix[i] === " ") {continue;}
if (suffix[i] === " ") {
continue;
}
const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]];
if (!openBracket) {break;}
if (!openBracket) {
break;
}
stack.unshift(openBracket);
}

View file

@ -3,33 +3,6 @@ import { AutocompleteLanguageInfo } from "./languages";
const BLOCK_TYPES = ["body", "statement_block"];
function shouldCompleteMultilineAst(
treePath: AstPath,
cursorLine: number,
): boolean {
// If at the base of the file, do multiline
if (treePath.length === 1) {
return true;
}
// If at the first line of an otherwise empty funtion body, do multiline
for (let i = treePath.length - 1; i >= 0; i--) {
const node = treePath[i];
if (
BLOCK_TYPES.includes(node.type) &&
Math.abs(node.startPosition.row - cursorLine) <= 1
) {
let text = node.text;
text = text.slice(text.indexOf("{") + 1);
text = text.slice(0, text.lastIndexOf("}"));
text = text.trim();
return text.split("\n").length === 1;
}
}
return false;
}
function isMidlineCompletion(prefix: string, suffix: string): boolean {
return !suffix.startsWith("\n");
}
@ -56,20 +29,5 @@ export async function shouldCompleteMultiline(
return false;
}
// First, if the line before ends with an opening bracket, then assume multi-line
if (
["{", "(", "["].includes(
fullPrefix.split("\n").slice(-2)[0]?.trim().slice(-1)[0],
)
) {
return true;
}
// Use AST to determine whether to complete multiline
let completeMultiline = false;
if (treePath) {
const cursorLine = fullPrefix.split("\n").length - 1;
completeMultiline = shouldCompleteMultilineAst(treePath, cursorLine);
}
return completeMultiline;
return true;
}

View file

@ -0,0 +1,51 @@
##### Prompt #####
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
subtract(number) {
this.result -= number;
return this;
}
multiply(number) {
this.result *= number;
return this;
}
divide(number) {
if (number === 0) {
throw new Error("Cannot divide by zero");
}
<FIM>
this.result /= number;
return this;
}
getResult() {
return this.result;
}
reset() {
this.result = 0;
return this;
}
}
==========================================================================
==========================================================================
Completion:
this.result /= number;
return this;
}
}
module.exports = Calculator;

View file

@ -0,0 +1,30 @@
import {
AutocompleteFileringTestInput,
testAutocompleteFiltering,
} from "./util";
import { TEST_CASES } from "./testCases";
const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
if (tests.some((test) => test.options?.only)) {
return tests.filter((test) => test.options?.only);
}
return tests;
};
describe("llms/Mock", () => {
describe("Autocomplete Filtering Tests", () => {
beforeEach(async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
});
describe("Should return unmodified LLM output", () => {
it.each(filterTestCases(TEST_CASES))("$description", async (testCase) => {
await testAutocompleteFiltering(testCase);
});
});
// TODO: Add test cases where modifying LLM output is desirable
describe.skip("Should return modified LLM output", () => {});
});
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,74 @@
import fs from "node:fs";
import path from "node:path";
import Mock from "../../llm/llms/Mock";
import { testConfigHandler, testIde } from "../../test/util/fixtures";
import { AutocompleteInput, CompletionProvider } from "../completionProvider";
const FIM_DELIMITER = "<|fim|>";
function parseFimExample(text: string): { prefix: string; suffix: string } {
const [prefix, suffix] = text.split(FIM_DELIMITER);
return { prefix, suffix };
}
export interface AutocompleteFileringTestInput {
description: string;
filename: string;
input: string;
llmOutput: string;
expectedCompletion: string | null;
options?: {
only?: boolean;
};
}
export async function testAutocompleteFiltering(
test: AutocompleteFileringTestInput,
) {
const { prefix, suffix } = parseFimExample(test.input);
// Setup necessary objects
const llm = new Mock({
model: "mock",
});
llm.completion = test.llmOutput;
const ide = testIde;
const configHandler = testConfigHandler;
// Create a real file
const [workspaceDir] = await ide.getWorkspaceDirs();
const filepath = path.join(workspaceDir, test.filename);
fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, ""));
// Prepare completion input and provider
const completionProvider = new CompletionProvider(
configHandler,
ide,
async () => llm,
() => {},
async () => [],
);
const line = prefix.split("\n").length - 1;
const character = prefix.split("\n")[line].length;
const autocompleteInput: AutocompleteInput = {
clipboardText: "",
completionId: "test-completion-id",
filepath,
pos: {
line,
character,
},
recentlyEditedFiles: [],
recentlyEditedRanges: [],
};
// Generate a completion
const result = await completionProvider.provideInlineCompletionItems(
autocompleteInput,
undefined,
);
// Ensure that we return the text that is wanted to be displayed
expect(result?.completion).toEqual(test.expectedCompletion);
}

View file

@ -95,10 +95,10 @@ export async function getPromptParts(
}
let filePrefix = fullFileContentsList
.slice(curStartLine, maxStartLine)
.slice(curStartLine, maxStartLine - 1)
.join("\n");
let fileSuffix = fullFileContentsList
.slice(minEndLine, curEndLine - 1)
.slice(minEndLine, curEndLine + 1)
.join("\n");
if (rif.contents.length > 0) {

View file

@ -6,9 +6,9 @@ import {
IdeSettings,
SerializedContinueConfig,
} from "../../index.js";
import { ConfigResult } from "../load.js";
import { IProfileLoader } from "./IProfileLoader.js";
import doLoadConfig from "./doLoadConfig.js";
import { ConfigResult } from "../load.js";
export default class ControlPlaneProfileLoader implements IProfileLoader {
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes
@ -45,7 +45,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
)) as any);
const serializedConfig: SerializedContinueConfig = settings;
return doLoadConfig(
const results = await doLoadConfig(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
@ -53,6 +53,11 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
serializedConfig,
this.workspaceId,
);
return {
...results,
errors: [], // Don't do config validation here, it happens in admin panel
};
}
setIsActive(isActive: boolean): void {}

View file

@ -338,11 +338,7 @@ declare global {
capabilities?: ModelCapability;
// IBM watsonx options
watsonxUrl?: string;
watsonxCreds?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
deploymentId?: string;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -602,7 +598,8 @@ declare global {
| "watsonx"
| "openrouter"
| "sambanova"
| "nvidia";
| "nvidia"
| "nebius";
export type ModelName =
| "AUTODETECT"
@ -768,7 +765,9 @@ declare global {
| "gemini"
| "continue-proxy"
| "deepinfra"
| "voyage";
| "voyage"
| "watsonx"
| "nebius";
export interface EmbedOptions {
apiBase?: string;
@ -779,6 +778,7 @@ declare global {
apiVersion?: string;
requestOptions?: RequestOptions;
maxChunkSize?: number;
projectId?: string;
}
export interface EmbeddingsProviderDescription extends EmbedOptions {

View file

@ -1,4 +1,4 @@
import { SerializedContinueConfig } from "../";
import { ModelDescription, SerializedContinueConfig } from "../";
import { Telemetry } from "../util/posthog";
export interface ConfigValidationError {
@ -14,11 +14,11 @@ export interface ConfigValidationError {
export function validateConfig(config: SerializedContinueConfig) {
const errors: ConfigValidationError[] = [];
// Validate models
if (!Array.isArray(config.models) || config.models.length === 0) {
// Validate chat models
if (!Array.isArray(config.models)) {
errors.push({
fatal: true,
message: "The 'models' field should be a non-empty array.",
message: "The 'models' field should be an array.",
});
} else {
config.models.forEach((model, index) => {
@ -37,6 +37,36 @@ export function validateConfig(config: SerializedContinueConfig) {
});
}
// Validate tab autocomplete model(s)
if (config.tabAutocompleteModel) {
function validateTabAutocompleteModel(modelDescription: ModelDescription) {
const modelName = modelDescription.model.toLowerCase();
const nonAutocompleteModels = [
// "gpt",
// "claude",
"mistral",
"instruct",
];
if (
nonAutocompleteModels.some((m) => modelName.includes(m)) &&
!modelName.includes("deepseek") &&
!modelName.includes("codestral")
) {
errors.push({
fatal: false,
message: `${modelDescription.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/features/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`,
});
}
}
if (Array.isArray(config.tabAutocompleteModel)) {
config.tabAutocompleteModel.forEach(validateTabAutocompleteModel);
} else {
validateTabAutocompleteModel(config.tabAutocompleteModel);
}
}
// Validate slashCommands
if (config.slashCommands) {
if (!Array.isArray(config.slashCommands)) {

View file

@ -8,10 +8,7 @@ import type {
} from "../../";
class CustomContextProviderClass implements IContextProvider {
custom: CustomContextProvider;
constructor(custom: CustomContextProvider) {
this.custom = custom;
}
constructor(private custom: CustomContextProvider) {}
get description(): ContextProviderDescription {
return {

View file

@ -1,3 +1,4 @@
import { BaseContextProvider } from "../";
import {
ContextItem,
ContextProviderDescription,
@ -11,7 +12,6 @@ import {
getUniqueFilePath,
groupByLastNPathParts,
} from "../../util/";
import { BaseContextProvider } from "../";
const MAX_SUBMENU_ITEMS = 10_000;
@ -21,7 +21,6 @@ class FileContextProvider extends BaseContextProvider {
displayTitle: "Files",
description: "Type to search",
type: "submenu",
dependsOnIndexing: true,
};
async getContextItems(

View file

@ -34,7 +34,6 @@ class FileTreeContextProvider extends BaseContextProvider {
description: "Attach a representation of the file tree",
type: "normal",
renderInlineAs: "",
dependsOnIndexing: true,
};
async getContextItems(

View file

@ -7,9 +7,9 @@ import {
LoadSubmenuItemsArgs,
} from "../../";
import {
groupByLastNPathParts,
getBasename,
getUniqueFilePath,
groupByLastNPathParts,
} from "../../util";
import generateRepoMap from "../../util/generateRepoMap";
@ -25,7 +25,6 @@ class RepoMapContextProvider extends BaseContextProvider {
displayTitle: "Repository Map",
description: "Select a folder",
type: "submenu",
dependsOnIndexing: true,
};
async getContextItems(

View file

@ -14,13 +14,13 @@ export interface RetrievalPipelineOptions {
llm: ILLM;
config: ContinueConfig;
ide: IDE;
input: string;
nRetrieve: number;
nFinal: number;
tags: BranchAndDir[];
pathSep: string;
filterDirectory?: string;
includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model
}
export interface IRetrievalPipeline {
@ -29,6 +29,7 @@ export interface IRetrievalPipeline {
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
private lanceDbIndex: LanceDbIndex;
constructor(protected readonly options: RetrievalPipelineOptions) {
this.lanceDbIndex = new LanceDbIndex(
options.config.embeddingsProvider,
@ -71,7 +72,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
}
}
return chunks;
return chunks.slice(0, n);
}
protected async retrieveFts(input: string, n: number): Promise<Chunk[]> {

View file

@ -5,7 +5,7 @@ import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js";
export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
async run(): Promise<Chunk[]> {
const { input, nFinal, filterDirectory } = this.options;
const { input, nFinal, filterDirectory, includeEmbeddings } = this.options;
// We give 1/4 weight to recently edited files, 1/4 to full text search,
// and the remaining 1/2 to embeddings
@ -17,10 +17,9 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
const ftsChunks = await this.retrieveFts(input, ftsNFinal);
const embeddingsChunks = await this.retrieveEmbeddings(
input,
embeddingsNFinal,
);
const embeddingsChunks = includeEmbeddings
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];
const recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);

View file

@ -6,12 +6,15 @@ import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js";
export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
private async _retrieveInitial(): Promise<Chunk[]> {
const { input, nRetrieve, filterDirectory } = this.options;
const { input, nRetrieve, filterDirectory, includeEmbeddings } =
this.options;
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(input, nRetrieve);
const embeddingsChunks = await this.retrieveEmbeddings(input, nRetrieve);
const embeddingsChunks = includeEmbeddings
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
const recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);

View file

@ -6,6 +6,7 @@ import generateRepoMap from "../../util/generateRepoMap";
const SUPPORTED_MODEL_TITLE_FAMILIES = [
"claude-3",
"llama3.1",
"llama3.2",
"gemini-1.5",
"gpt-4",
];

View file

@ -1,8 +1,10 @@
import path from "path";
import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider";
import { resolveRelativePathInWorkspace } from "../../util/ideUtils";
import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils";
import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline";
import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline";
import RerankerRetrievalPipeline from "./pipelines/RerankerRetrievalPipeline";
@ -21,15 +23,17 @@ export async function retrieveContextItemsFromEmbeddings(
// transformers.js not supported in JetBrains IDEs right now
const isJetBrainsAndTransformersJs =
extras.embeddingsProvider.id === TransformersJsEmbeddingsProvider.model &&
extras.embeddingsProvider.providerName ===
TransformersJsEmbeddingsProvider.providerName &&
(await extras.ide.getIdeInfo()).ideType === "jetbrains";
if (isJetBrainsAndTransformersJs) {
throw new Error(
"The 'transformers.js' context provider is not currently supported in JetBrains. " +
"For now, you can use Ollama to set up local embeddings, or use our 'free-trial' " +
"embeddings provider. See here to learn more: " +
"https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers",
void extras.ide.showToast(
"warning",
"Codebase retrieval is limited when `embeddingsProvider` is empty or set to `transformers.js` in JetBrains. " +
"You can use Ollama to set up local embeddings, use our 'free-trial', " +
"or configure your own. See here to learn more: " +
"https://docs.continue.dev/customize/model-types/embeddings",
);
}
@ -85,6 +89,7 @@ export async function retrieveContextItemsFromEmbeddings(
input: extras.fullInput,
llm: extras.llm,
config: extras.config,
includeEmbeddings: !isJetBrainsAndTransformersJs,
};
const pipeline = new pipelineType(pipelineOptions);

View file

@ -16,6 +16,7 @@ const modelDescriptionSchema = z.object({
"sagemaker",
"cloudflare",
"azure",
"nebius",
]),
model: z.string(),
apiKey: z.string().optional(),
@ -81,6 +82,7 @@ const embeddingsProviderSchema = z.object({
"cohere",
"free-trial",
"gemini",
"nebius",
]),
apiBase: z.string().optional(),
apiKey: z.string().optional(),

View file

@ -20,15 +20,15 @@ import DocsService from "./indexing/docs/DocsService";
import Ollama from "./llm/llms/Ollama";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { GlobalContext } from "./util/GlobalContext";
import { ChatDescriber } from "./util/chatDescriber";
import { logDevData } from "./util/devdata";
import { DevDataSqliteDb } from "./util/devdataSqlite";
import { fetchwithRequestOptions } from "./util/fetchWithOptions";
import historyManager from "./util/history";
import type { IMessenger, Message } from "./util/messenger";
import { editConfigJson } from "./util/paths";
import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { TTS } from "./util/tts";
import { ChatDescriber } from "./util/chatDescriber";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -79,6 +79,9 @@ export class Core {
private readonly ide: IDE,
private readonly onWrite: (text: string) => Promise<void> = async () => {},
) {
// Ensure .continue directory is created
setupInitialDotContinueDirectory();
this.indexingState = { status: "loading", desc: "loading", progress: 0 };
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
@ -483,7 +486,7 @@ export class Core {
on("tts/kill", async () => {
void TTS.kill();
});
on("chatDescriber/describe", async (msg) => {
const currentModel = await this.getSelectedModel();
return await ChatDescriber.describe(currentModel, {}, msg.data);

View file

@ -110,6 +110,11 @@ export async function* streamLines(
yield line;
allLines.push(line);
}
// if (buffer === "" && chunk.endsWith("\n")) {
// yield "";
// allLines.push("");
// }
}
if (buffer.length > 0) {
yield buffer;

View file

@ -43,7 +43,7 @@ export async function* streamLazyApply(
let lazyCompletionLines = streamLines(lazyCompletion, true);
// Process line output
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => { }, ["```"]);
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
// Fill in unchanged code

View file

@ -60,7 +60,7 @@ export async function* streamDiffLines(
language: string | undefined,
onlyOneInsertion?: boolean,
): AsyncGenerator<DiffLine> {
Telemetry.capture(
void Telemetry.capture(
"inlineEdit",
{
model: llm.model,
@ -94,7 +94,6 @@ export async function* streamDiffLines(
);
const inept = modelIsInept(llm.model);
const options: LLMFullCompletionOptions = {};
const completion =
typeof prompt === "string"
? llm.streamComplete(prompt, { raw: true })

49
core/index.d.ts vendored
View file

@ -48,9 +48,9 @@ export interface IndexingProgressUpdate {
export type PromptTemplate =
| string
| ((
history: ChatMessage[],
otherData: Record<string, string>,
) => string | ChatMessage[]);
history: ChatMessage[],
otherData: Record<string, string>,
) => string | ChatMessage[]);
export interface ILLM extends LLMOptions {
get providerName(): ModelProvider;
@ -363,16 +363,13 @@ export interface LLMOptions {
region?: string;
// GCP Options
projectId?: string;
capabilities?: ModelCapability;
// IBM watsonx options
watsonxUrl?: string;
watsonxCreds?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
watsonxFullUrl?: string;
// GCP and Watsonx Options
projectId?: string;
// IBM watsonx Options
deploymentId?: string;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -606,13 +603,13 @@ type TemplateType =
| "codellama-70b"
| "llava"
| "gemma"
| "granite"
| "llama3";
type ModelProvider =
| "openai"
| "free-trial"
| "anthropic"
| "anthropic-vertexai"
| "cohere"
| "together"
| "ollama"
@ -625,9 +622,7 @@ type ModelProvider =
| "lmstudio"
| "llamafile"
| "gemini"
| "gemini-vertexai"
| "mistral"
| "mistral-vertexai"
| "bedrock"
| "bedrockimport"
| "sagemaker"
@ -648,7 +643,10 @@ type ModelProvider =
| "nvidia"
| "vllm"
| "mock"
| "cerebras";
| "cerebras"
| "askSage"
| "vertexai"
| "nebius";
export type ModelName =
| "AUTODETECT"
@ -663,6 +661,8 @@ export type ModelName =
| "gpt-4-turbo"
| "gpt-4-turbo-preview"
| "gpt-4-vision-preview"
| "o1-preview"
| "o1-mini"
// Mistral
| "codestral-latest"
| "open-mistral-7b"
@ -690,6 +690,12 @@ export type ModelName =
// Llama 3.1
| "llama3.1-8b"
| "llama3.1-70b"
| "llama3.1-405b"
// Llama 3.2
| "llama3.2-1b"
| "llama3.2-3b"
| "llama3.2-11b"
| "llama3.2-90b"
// Other Open-source
| "phi2"
| "phind-codellama-34b"
@ -822,7 +828,9 @@ export type EmbeddingsProviderName =
| "nvidia"
| "voyage"
| "mistral"
| "vertex";
| "nebius"
| "vertexai"
| "watsonx";
export interface EmbedOptions {
apiBase?: string;
@ -840,7 +848,7 @@ export interface EmbedOptions {
// AWS and GCP Options
region?: string;
// GCP Options
// GCP and Watsonx Options
projectId?: string;
}
@ -881,6 +889,7 @@ export interface TabAutocompleteOptions {
debounceDelay: number;
maxSuffixPercentage: number;
prefixPercentage: number;
transform?: boolean;
template?: string;
multilineCompletions: "always" | "never" | "auto";
slidingWindowPrefixPercentage: number;
@ -1044,9 +1053,9 @@ export interface Config {
embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider;
/** The model that Continue will use for tab autocompletions. */
tabAutocompleteModel?:
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
| CustomLLM
| ModelDescription
| (CustomLLM | ModelDescription)[];
/** Options for tab autocomplete */
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
/** UI styles customization */

View file

@ -14,7 +14,7 @@ import {
getParserForFile,
getQueryForFile,
} from "../util/treeSitter";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import { DatabaseConnection, SqliteDb, tagToString, truncateSqliteLikePattern } from "./refreshIndex";
import {
IndexResultType,
MarkCompleteCallback,
@ -28,7 +28,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 1;
artifactId = "codeSnippets";
constructor(private readonly ide: IDE) {}
constructor(private readonly ide: IDE) { }
private static async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets (
@ -383,7 +383,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
const db = await SqliteDb.get();
await CodeSnippetsCodebaseIndex._createTables(db);
const likePatterns = workspaceDirs.map((dir) => `${dir}%`);
const likePatterns = workspaceDirs.map((dir) => truncateSqliteLikePattern(`${dir}%`));
const placeholders = likePatterns.map(() => "?").join(" OR path LIKE ");
const query = `

View file

@ -23,9 +23,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
private readonly pathSep: string,
private readonly continueServerClient: IContinueServerClient,
private readonly maxChunkSize: number,
) {
this.readFile = readFile;
}
) {}
async *update(
tag: IndexTag,

View file

@ -6,11 +6,14 @@ import { fromIni } from "@aws-sdk/credential-providers";
import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
interface ModelConfig {
formatPayload: (text: string) => any;
extractEmbeddings: (responseBody: any) => number[][];
}
class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "bedrock";
static defaultOptions: Partial<EmbedOptions> | undefined = {
static defaultOptions: Partial<EmbedOptions> = {
model: "amazon.titan-embed-text-v2:0",
region: "us-east-1"
};
@ -18,6 +21,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
constructor(options: EmbedOptions, fetch: FetchFunction) {
super(options, fetch);
this.options.model = this.options.model || BedrockEmbeddingsProvider.defaultOptions.model!;
if (!options.apiBase) {
options.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
@ -29,7 +33,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
}
}
async embed(chunks: string[]) {
async embed(chunks: string[]): Promise<number[][]> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.options.region,
@ -43,41 +47,64 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
return (
await Promise.all(
chunks.map(async (chunk) => {
const input = this._generateInvokeModelCommandInput(chunk, this.options);
const input = this._generateInvokeModelCommandInput(chunk);
const command = new InvokeModelCommand(input);
const response = await client.send(command);
if (response.body) {
const responseBody = JSON.parse(new TextDecoder().decode(response.body));
return [responseBody.embedding];
return this._extractEmbeddings(responseBody);
}
return [];
}),
)
).flat();
}
private _generateInvokeModelCommandInput(
prompt: string,
options: EmbedOptions,
): any {
const payload = {
"inputText": prompt,
"dimensions": 512,
"normalize": true
};
private _generateInvokeModelCommandInput(text: string): any {
const modelConfig = this._getModelConfig();
const payload = modelConfig.formatPayload(text);
return {
body: JSON.stringify(payload),
modelId: this.options.model,
accept: "application/json",
contentType: "application/json"
accept: "*/*",
contentType: "application/json",
};
}
private _extractEmbeddings(responseBody: any): number[][] {
const modelConfig = this._getModelConfig();
return modelConfig.extractEmbeddings(responseBody);
}
private _getModelConfig() {
const modelConfigs: { [key: string]: ModelConfig } = {
'cohere': {
formatPayload: (text: string) => ({
texts: [text],
input_type: "search_document",
truncate: "END",
}),
extractEmbeddings: (responseBody: any) => responseBody.embeddings || [],
},
'amazon.titan-embed': {
formatPayload: (text: string) => ({
inputText: text,
}),
extractEmbeddings: (responseBody: any) => responseBody.embedding ? [responseBody.embedding] : [],
},
};
const modelPrefix = Object.keys(modelConfigs).find(prefix => this.options.model!.startsWith(prefix));
if (!modelPrefix) {
throw new Error(`Unsupported model: ${this.options.model}`);
}
return modelConfigs[modelPrefix];
}
private async _getCredentials() {
try {
return await
fromIni({
return await fromIni({
profile: this.profile,
ignoreCache: true
})();
@ -88,7 +115,6 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
return await fromIni()();
}
}
}
export default BedrockEmbeddingsProvider;

View file

@ -0,0 +1,13 @@
import { EmbeddingsProviderName, EmbedOptions } from "../..";
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
class NebiusEmbeddingsProvider extends OpenAIEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "nebius";
static defaultOptions: Partial<EmbedOptions> | undefined = {
apiBase: "https://api.studio.nebius.ai/v1/",
model: "BAAI/bge-en-icl",
};
}
export default NebiusEmbeddingsProvider;

View file

@ -1,114 +1,114 @@
import {
InvokeEndpointCommand,
SageMakerRuntimeClient,
} from "@aws-sdk/client-sagemaker-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import {
EmbeddingsProviderName,
EmbedOptions,
FetchFunction,
} from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class SageMakerEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "sagemaker";
static defaultOptions: Partial<EmbedOptions> | undefined = {
region: "us-west-2",
maxBatchSize: 1,
};
profile?: string | undefined;
constructor(options: EmbedOptions, fetch: FetchFunction) {
super(options, fetch);
if (!options.apiBase) {
options.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`;
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "sagemaker";
}
InvokeEndpointCommand,
SageMakerRuntimeClient,
} from "@aws-sdk/client-sagemaker-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import {
EmbeddingsProviderName,
EmbedOptions,
FetchFunction,
} from "../../index.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class SageMakerEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "sagemaker";
static defaultOptions: Partial<EmbedOptions> | undefined = {
region: "us-west-2",
maxBatchSize: 1,
};
profile?: string | undefined;
constructor(options: EmbedOptions, fetch: FetchFunction) {
super(options, fetch);
if (!options.apiBase) {
options.apiBase = `https://runtime.sagemaker.${options.region}.amazonaws.com`;
}
async embed(chunks: string[]) {
const credentials = await this._getCredentials();
const client = new SageMakerRuntimeClient({
region: this.options.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const batchedChunks = this.getBatchedChunks(chunks);
return (
await Promise.all(
batchedChunks.map(async (batch) => {
const input = this._generateInvokeModelCommandInput(
batch,
this.options,
);
const command = new InvokeEndpointCommand(input);
const response = await client.send(command);
if (response.Body) {
const responseBody = JSON.parse(
new TextDecoder().decode(response.Body),
);
// If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body
if (responseBody.embedding) {
return responseBody.embedding;
} else if (responseBody.embeddings) {
return responseBody.embeddings;
} else {
return responseBody;
}
}
}),
)
).flat();
}
private _generateInvokeModelCommandInput(
prompts: string | string[],
options: EmbedOptions,
): any {
const payload = {
inputs: prompts,
normalize: true,
// ...(options.requestOptions?.extraBodyProperties || {}),
};
if (options.requestOptions?.extraBodyProperties) {
Object.assign(payload, options.requestOptions.extraBodyProperties);
}
return {
EndpointName: this.options.model,
Body: JSON.stringify(payload),
ContentType: "application/json",
CustomAttributes: "accept_eula=false",
};
}
private async _getCredentials() {
try {
return await fromIni({
profile: this.profile,
ignoreCache: true,
})();
} catch (e) {
console.warn(
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "sagemaker";
}
}
export default SageMakerEmbeddingsProvider;
async embed(chunks: string[]) {
const credentials = await this._getCredentials();
const client = new SageMakerRuntimeClient({
region: this.options.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const batchedChunks = this.getBatchedChunks(chunks);
return (
await Promise.all(
batchedChunks.map(async (batch) => {
const input = this._generateInvokeModelCommandInput(
batch,
this.options,
);
const command = new InvokeEndpointCommand(input);
const response = await client.send(command);
if (response.Body) {
const responseBody = JSON.parse(
new TextDecoder().decode(response.Body),
);
// If the body contains a key called "embedding" or "embeddings", return the value, otherwise return the whole body
if (responseBody.embedding) {
return responseBody.embedding;
} else if (responseBody.embeddings) {
return responseBody.embeddings;
} else {
return responseBody;
}
}
}),
)
).flat();
}
private _generateInvokeModelCommandInput(
prompts: string | string[],
options: EmbedOptions,
): any {
const payload = {
inputs: prompts,
normalize: true,
// ...(options.requestOptions?.extraBodyProperties || {}),
};
if (options.requestOptions?.extraBodyProperties) {
Object.assign(payload, options.requestOptions.extraBodyProperties);
}
return {
EndpointName: this.options.model,
Body: JSON.stringify(payload),
ContentType: "application/json",
CustomAttributes: "accept_eula=false",
};
}
private async _getCredentials() {
try {
return await fromIni({
profile: this.profile,
ignoreCache: true,
})();
} catch (e) {
console.warn(
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
}
export default SageMakerEmbeddingsProvider;

View file

@ -8,7 +8,7 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
* [View the Vertex Text Embedding docs.](https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings)
*/
class VertexEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "vertex";
static providerName: EmbeddingsProviderName = "vertexai";
declare apiBase: string;

View file

@ -0,0 +1,150 @@
import {
EmbeddingsProviderName,
EmbedOptions,
FetchFunction,
} from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider, {
IBaseEmbeddingsProvider,
} from "./BaseEmbeddingsProvider.js";
let accessToken = {
expiration: 0,
token: "",
};
class WatsonxEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "watsonx";
static maxBatchSize = 1000;
static defaultOptions: Partial<EmbedOptions> | undefined = {
model: "ibm/slate-125m-english-rtrvr-v2",
};
async getBearerToken(): Promise<{ token: string; expiration: number }> {
if (
this.options.apiBase?.includes("cloud.ibm.com")
) {
// watsonx SaaS
const wxToken = await (
await fetch(
`https://iam.cloud.ibm.com/identity/token?apikey=${this.options.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
},
)
).json();
return {
token: wxToken["access_token"],
expiration: wxToken["expiration"],
};
} else {
// watsonx Software
if (!this.options.apiKey?.includes(":")) {
// Using ZenApiKey auth
return {
token: this.options.apiKey ?? "",
expiration: -1,
};
} else {
// Using username/password auth
const userPass = this.options.apiKey?.split(":");
const wxToken = await (
await fetch(`${this.options.apiBase}/icp4d-api/v1/authorize`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
username: userPass[0],
password: userPass[1],
}),
})
).json();
const wxTokenExpiry = await (
await fetch(
`${this.options.apiBase}/usermgmt/v1/user/tokenExpiry`,
{
method: "GET",
headers: {
Accept: "application/json",
Authorization: `Bearer ${wxToken["token"]}`,
},
},
)
).json();
return {
token: wxToken["token"],
expiration: wxTokenExpiry["exp"],
};
}
}
}
async getSingleBatchEmbedding(batch: string[]) {
var now = new Date().getTime() / 1000;
if (
accessToken === undefined ||
now > accessToken.expiration ||
accessToken.token === undefined
) {
accessToken = await this.getBearerToken();
} else {
console.log(
`Reusing token (expires in ${(accessToken.expiration - now) / 60
} mins)`,
);
}
return await withExponentialBackoff<number[][]>(async () => {
const payload: any = {
inputs: batch,
parameters: {
truncate_input_tokens: 500,
return_options: { input_text: false },
},
model_id: this.options.model,
project_id: this.options.projectId,
};
const headers = {
"Content-Type": "application/json",
Authorization: `${accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"
} ${accessToken.token}`,
};
const resp = await this.fetch(
new URL(
`${this.options.apiBase}/ml/v1/text/embeddings?version=${this.options.apiVersion}`,
),
{
method: "POST",
body: JSON.stringify(payload),
headers: headers,
},
);
if (!resp.ok) {
throw new Error(`Failed to embed chunk: ${await resp.text()}`);
}
const data = await resp.json();
const embeddings = data.results;
if (!embeddings || embeddings.length === 0) {
throw new Error("Watsonx generated empty embedding");
}
return embeddings.map((e: any) => e.embedding);
});
}
async embed(chunks: string[]) {
const batchedChunks = this.getBatchedChunks(chunks);
const results = await Promise.all(
batchedChunks.map((batch) => this.getSingleBatchEmbedding(batch)),
);
return results.flat();
}
}
export default WatsonxEmbeddingsProvider;

View file

@ -15,6 +15,8 @@ import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider
import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js";
import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js";
import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js";
import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js";
import NebiusEmbeddingsProvider from "./NebiusEmbeddingsProvider.js";
type EmbeddingsProviderConstructor = new (
...args: any[]
@ -38,5 +40,7 @@ export const allEmbeddingsProviders: Record<
nvidia: NvidiaEmbeddingsProvider,
voyage: VoyageEmbeddingsProvider,
mistral: MistralEmbeddingsProvider,
vertex: VertexEmbeddingsProvider
nebius: NebiusEmbeddingsProvider,
vertexai: VertexEmbeddingsProvider,
watsonx: WatsonxEmbeddingsProvider
};

View file

@ -1,4 +1,7 @@
import ignore from "ignore";
import path from "path";
import os from "os";
import fs from "fs";
export const DEFAULT_IGNORE_FILETYPES = [
"*.DS_Store",
@ -114,3 +117,18 @@ export function gitIgArrayFromFile(file: string) {
.map((l) => l.trim()) // Remove whitespace
.filter((l) => !/^#|^$/.test(l)); // Remove empty lines
}
export const GLOBAL_CONTINUEIGNORE_PATH = path.join(os.homedir(), ".continue", ".continueignore");
export const getGlobalContinueIgArray = () => {
try {
const contents = fs.readFileSync(GLOBAL_CONTINUEIGNORE_PATH, "utf8");
return gitIgArrayFromFile(contents);
} catch (error) {
// If the file doesn't exist, that's okay
if (error instanceof Error && ("code" in error) && error.code === "ENOENT") {
return [];
}
throw error;
}
};

View file

@ -0,0 +1,34 @@
import { truncateToLastNBytes } from "./refreshIndex";
describe("truncateToLastNBytes", () => {
it("should return full string if maxBytes greater than string byte length", () => {
const input = "Hello World";
const result = truncateToLastNBytes(input, 100);
expect(result).toBe("Hello World");
});
it("should truncate ASCII string correctly", () => {
const input = "Hello World";
const result = truncateToLastNBytes(input, 5);
expect(result).toBe("World");
});
it("should handle empty string", () => {
const input = "";
const result = truncateToLastNBytes(input, 5);
expect(result).toBe("");
});
it("should handle UTF-8 characters correctly", () => {
const input = "👋 Hello";
// 👋 is 4 bytes, space is 1 byte
const result = truncateToLastNBytes(input, 5);
expect(result).toBe("Hello");
});
it("should handle maxBytes of 0", () => {
const input = "Hello World";
const result = truncateToLastNBytes(input, 0);
expect(result).toBe("");
});
});

View file

@ -416,11 +416,9 @@ export async function getComputeDeleteAddRemove(
export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 1;
private db: DatabaseConnection;
constructor(db: DatabaseConnection) {
this.db = db;
}
constructor(private db: DatabaseConnection) {}
artifactId = "globalCache";
static async create(): Promise<GlobalCacheCodeBaseIndex> {
@ -471,3 +469,24 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
);
}
}
const SQLITE_MAX_LIKE_PATTERN_LENGTH = 50000;
export function truncateToLastNBytes(input: string, maxBytes: number): string {
let bytes = 0;
let startIndex = 0;
for (let i = input.length - 1; i >= 0; i--) {
bytes += new TextEncoder().encode(input[i]).length;
if (bytes > maxBytes) {
startIndex = i + 1;
break;
}
}
return input.substring(startIndex, input.length);
}
export function truncateSqliteLikePattern(input: string) {
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH);
}

View file

@ -6,6 +6,7 @@ import {
DEFAULT_IGNORE_FILETYPES,
defaultIgnoreDir,
defaultIgnoreFile,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "./ignore.js";
@ -38,15 +39,13 @@ type IgnoreContext = {
};
class DFSWalker {
private readonly path: string;
private readonly ide: IDE;
private readonly options: WalkerOptions;
private readonly ignoreFileNames: Set<string>;
constructor(path: string, ide: IDE, options: WalkerOptions) {
this.path = path;
this.ide = ide;
this.options = options;
constructor(
private readonly path: string,
private readonly ide: IDE,
private readonly options: WalkerOptions,
) {
this.ignoreFileNames = new Set<string>(options.ignoreFiles);
}
@ -85,6 +84,7 @@ class DFSWalker {
}
private newRootWalkContext(): WalkContext {
const globalIgnoreFile = getGlobalContinueIgArray();
return {
walkableEntry: {
relPath: "",
@ -94,7 +94,7 @@ class DFSWalker {
},
ignoreContexts: [
{
ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile),
ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile).add(globalIgnoreFile),
dirname: "",
},
],
@ -128,10 +128,7 @@ class DFSWalker {
ignore: ignore().add(patterns),
dirname: curDir.walkableEntry.relPath,
};
return [
...curDir.ignoreContexts,
newIgnoreContext
];
return [...curDir.ignoreContexts, newIgnoreContext];
}
private async loadIgnoreFiles(entries: WalkableEntry[]): Promise<string[]> {
@ -147,7 +144,10 @@ class DFSWalker {
return this.ignoreFileNames.has(p);
}
private shouldInclude(walkableEntry: WalkableEntry, ignoreContexts: IgnoreContext[]) {
private shouldInclude(
walkableEntry: WalkableEntry,
ignoreContexts: IgnoreContext[],
) {
if (this.entryIsSymlink(walkableEntry.entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it linksto something outside of the repository and

View file

@ -5,6 +5,7 @@ import {
codeLlama70bTemplateMessages,
deepseekTemplateMessages,
gemmaTemplateMessage,
graniteTemplateMessages,
llama2TemplateMessages,
llama3TemplateMessages,
llavaTemplateMessages,
@ -41,28 +42,27 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"together",
"msty",
"anthropic",
"anthropic-vertexai",
"bedrock",
"sagemaker",
"continue-proxy",
"mistral",
"mistral-vertexai",
"sambanova",
"vertexai",
"watsonx"
];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
"openai",
"ollama",
"gemini",
"gemini-vertexai",
"free-trial",
"msty",
"anthropic",
"anthropic-vertexai",
"bedrock",
"sagemaker",
"continue-proxy",
"openrouter",
"vertexai"
];
const MODEL_SUPPORTS_IMAGES: string[] = [
@ -79,6 +79,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"opus",
"haiku",
"pixtral",
"llama3.2",
];
function modelSupportsImages(
@ -107,20 +108,19 @@ function modelSupportsImages(
}
const PARALLEL_PROVIDERS: ModelProvider[] = [
"anthropic",
"anthropic-vertexai",
"bedrock",
"sagemaker",
"deepinfra",
"gemini",
"gemini-vertexai",
"huggingface-inference-api",
"huggingface-tgi",
"mistral",
"mistral-vertexai",
"free-trial",
"replicate",
"together",
"sambanova",
"nebius",
"vertexai"
];
function llmCanGenerateInParallel(
@ -220,6 +220,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
return "neural-chat";
}
if (lower.includes("granite")) {
return "granite";
}
return "chatml";
}
@ -253,6 +257,7 @@ function autodetectTemplateFunction(
llava: llavaTemplateMessages,
"codellama-70b": codeLlama70bTemplateMessages,
gemma: gemmaTemplateMessage,
granite: graniteTemplateMessages,
llama3: llama3TemplateMessages,
none: null,
};

View file

@ -114,13 +114,8 @@ export abstract class BaseLLM implements ILLM {
accountId?: string;
aiGatewaySlug?: string;
// For IBM watsonx only.
watsonxUrl?: string;
watsonxCreds?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
watsonxFullUrl?: string;
// For IBM watsonx
deploymentId?: string;
private _llmOptions: LLMOptions;
@ -186,13 +181,8 @@ export abstract class BaseLLM implements ILLM {
this.apiBase = options.apiBase;
this.cacheBehavior = options.cacheBehavior;
// for watsonx only
this.watsonxUrl = options.watsonxUrl;
this.watsonxCreds = options.watsonxCreds;
this.watsonxProjectId = options.watsonxProjectId;
this.watsonxStopToken = options.watsonxStopToken;
this.watsonxApiVersion = options.watsonxApiVersion;
this.watsonxFullUrl = options.watsonxFullUrl;
// watsonx deploymentId
this.deploymentId = options.deploymentId;
if (this.apiBase && !this.apiBase.endsWith("/")) {
this.apiBase = `${this.apiBase}/`;

View file

@ -20,7 +20,7 @@ class Anthropic extends BaseLLM {
apiBase: "https://api.anthropic.com/v1/",
};
private _convertArgs(options: CompletionOptions) {
public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI
const finalOptions = {
top_k: options.topK,
top_p: options.topP,
@ -34,7 +34,7 @@ class Anthropic extends BaseLLM {
return finalOptions;
}
private _convertMessages(msgs: ChatMessage[]): any[] {
public convertMessages(msgs: ChatMessage[]): any[] { // should be public for use within VertexAI
const filteredmessages = msgs.filter((m) => m.role !== "system")
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
@ -115,8 +115,8 @@ class Anthropic extends BaseLLM {
: {}),
},
body: JSON.stringify({
...this._convertArgs(options),
messages: this._convertMessages(messages),
...this.convertArgs(options),
messages: this.convertMessages(messages),
system: shouldCacheSystemMessage
? [
{

View file

@ -1,142 +0,0 @@
import {
ChatMessage,
CompletionOptions,
LLMOptions,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { streamSse } from "../stream.js";
import VertexAI from "./VertexAI.js";
class AnthropicVertexAI extends VertexAI {
static providerName: ModelProvider = "anthropic-vertexai";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east5",
model: "claude-3-5-sonnet",
};
private _convertArgs(options: CompletionOptions) {
const finalOptions = {
anthropic_version: "vertex-2023-10-16",
top_k: options.topK,
top_p: options.topP,
temperature: options.temperature,
max_tokens: options.maxTokens ?? 2048,
stop_sequences: options.stop?.filter((x) => x.trim() !== ""),
stream: options.stream ?? true,
};
return finalOptions;
}
private _convertMessages(msgs: ChatMessage[]): any[] {
const filteredmessages = msgs.filter((m) => m.role !== "system")
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1).slice(-2);
const messages = filteredmessages.map((message, filteredMsgIdx) => {
// Add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx);
if (typeof message.content === "string") {
var chatMessage = {
...message,
content: [{
type: "text",
text: message.content,
...(addCaching? { cache_control: { type: "ephemeral" } } : {})
}]
};
return chatMessage;
}
return {
...message,
content: message.content.map((part, contentIdx) => {
if (part.type === "text") {
const newpart = {
...part,
// If multiple text parts, only add cache_control to the last one
...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {})
};
return newpart;
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}),
};
});
return messages;
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
yield stripImages(update.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const systemMessage: string = stripImages(
messages.filter((m) => m.role === "system")[0]?.content,
);
const apiURL = new URL(
`publishers/anthropic/models/${options.model}:streamRawPredict`,
this.apiBase
);
const response = await this.fetch(apiURL, {
method: "POST",
headers: {
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
? { "anthropic-beta": "prompt-caching-2024-07-31" }
: {}),
},
body: JSON.stringify({
...this._convertArgs(options),
messages: this._convertMessages(messages),
system: shouldCacheSystemMessage
? [
{
type: "text",
text: this.systemMessage,
cache_control: { type: "ephemeral" },
},
]
: systemMessage,
}),
});
if (options.stream === false) {
const data = await response.json();
yield { role: "assistant", content: data.content[0].text };
return;
}
for await (const value of streamSse(response)) {
if (value.type == "message_start") console.log(value);
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}
}
}
}
export default AnthropicVertexAI;

168
core/llm/llms/Asksage.ts Normal file
View file

@ -0,0 +1,168 @@
import {
ChatMessage,
CompletionOptions,
LLMOptions,
ModelProvider,
} from "../../index.js";
import { BaseLLM } from "../index.js";
class Asksage extends BaseLLM {
static providerName: ModelProvider = "askSage";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.asksage.ai/server/",
model: "gpt-4o",
};
private static modelConversion: { [key: string]: string } = {
"gpt-4o": "gpt-4o",
"gpt-4o-mini": "gpt-4o-mini",
"gpt4-gov": "gpt4-gov",
"gpt-4o-gov": "gpt-4o-gov",
"gpt-3.5-turbo": "gpt35-16k",
"mistral-large-latest": "mistral-large",
"llama3-70b": "llma3",
"gemini-1.5-pro-latest": "google-gemini-pro",
"claude-3-5-sonnet-20240620": "claude-35-sonnet",
"claude-3-opus-20240229": "claude-3-opus",
"claude-3-sonnet-20240229": "claude-3-sonnet",
};
constructor(options: LLMOptions) {
super(options);
this.apiVersion = options.apiVersion ?? "v1.2.4";
}
protected _convertModelName(model: string): string {
return Asksage.modelConversion[model] ?? model;
}
protected _convertMessage(message: ChatMessage) {
return {
user: message.role === "assistant" ? "gpt" : "me",
message:
typeof message.content === "string"
? message.content
: message.content.map((part) => part.text).join(""),
};
}
protected _convertArgs(options: any, messages: ChatMessage[]) {
let formattedMessage: any;
if (messages.length === 1) {
formattedMessage = messages[0].content;
} else {
formattedMessage = messages.map(this._convertMessage);
}
const args: any = {
message: formattedMessage,
persona: options.persona ?? "default",
dataset: options.dataset ?? "none",
limit_references: options.limitReferences ?? 0,
temperature: options.temperature ?? 0.0,
live: options.live ?? 0,
model: this._convertModelName(options.model),
system_prompt: options.systemPrompt ?? "You are an expert software developer. You give helpful and concise responses.",
tools: options.tools,
tool_choice: options.toolChoice,
};
Object.keys(args).forEach(
(key) => args[key] === undefined && delete args[key]
);
return args;
}
protected _getHeaders() {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers["x-access-tokens"] = this.apiKey;
}
return headers;
}
protected _getEndpoint(endpoint: string) {
if (!this.apiBase) {
throw new Error(
"No API base URL provided. Please set the 'apiBase' option."
);
}
return new URL(endpoint, this.apiBase);
}
protected async _complete(
prompt: string,
options: CompletionOptions
): Promise<string> {
if (typeof prompt !== "string" || prompt.trim() === "") {
throw new Error("Prompt must be a non-empty string.");
}
const messages: ChatMessage[] = [{ role: "user", content: prompt }];
const args = this._convertArgs(options, messages);
const response = await this.fetch(this._getEndpoint("query"), {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify(args),
});
if (!response.ok) {
throw new Error(
`API request failed with status ${response.status}: ${response.statusText}`
);
}
const data = await response.json();
return data.message;
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions
): AsyncGenerator<string> {
const completion = await this._complete(prompt, options);
yield completion;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
const args = this._convertArgs(options, messages);
const response = await this.fetch(this._getEndpoint("query"), {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify(args),
});
if (!response.ok) {
throw new Error(
`API request failed with status ${response.status}: ${response.statusText}`
);
}
const data = await response.json();
const assistantMessage: ChatMessage = {
role: "assistant",
content: data.message,
};
yield assistantMessage;
}
async listModels(): Promise<string[]> {
return Object.keys(Asksage.modelConversion);
}
}
export default Asksage;

View file

@ -111,7 +111,15 @@ class Bedrock extends BaseLLM {
maxTokens: options.maxTokens,
temperature: options.temperature,
topP: options.topP,
stopSequences: options.stop?.filter((stop) => stop.trim() !== ""),
// TODO: The current approach selects the first 4 items from the list to comply with Bedrock's requirement
// of having at most 4 stop sequences, as per the AWS documentation:
// https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_InferenceConfiguration.html
// However, it might be better to implement a strategy that dynamically selects the most appropriate stop sequences
// based on the context.
// TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback.
// For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes),
// providing meaningful error messages to improve the user experience.
stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4),
},
};
}

View file

@ -6,6 +6,7 @@ class DeepInfra extends OpenAI {
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.deepinfra.com/v1/openai/",
};
maxStopWords: number | undefined = 16;
}
export default DeepInfra;

View file

@ -15,10 +15,11 @@ class Gemini extends BaseLLM {
static defaultOptions: Partial<LLMOptions> = {
model: "gemini-pro",
apiBase: "https://generativelanguage.googleapis.com/v1beta/",
maxStopWords: 5,
};
// Function to convert completion options to Gemini format
private _convertArgs(options: CompletionOptions) {
public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI
const finalOptions: any = {}; // Initialize an empty object
// Map known options
@ -35,7 +36,9 @@ class Gemini extends BaseLLM {
finalOptions.maxOutputTokens = options.maxTokens;
}
if (options.stop) {
finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== "");
finalOptions.stopSequences = options.stop
.filter((x) => x.trim() !== "")
.slice(0, this.maxStopWords ?? Gemini.defaultOptions.maxStopWords);
}
return { generationConfig: finalOptions }; // Wrap options under 'generationConfig'
@ -53,7 +56,7 @@ class Gemini extends BaseLLM {
}
}
private removeSystemMessage(messages: ChatMessage[]) {
public removeSystemMessage(messages: ChatMessage[]) { // should be public for use within VertexAI
const msgs = [...messages];
if (msgs[0]?.role === "system") {
@ -100,7 +103,7 @@ class Gemini extends BaseLLM {
}
}
private _continuePartToGeminiPart(part: MessagePart) {
continuePartToGeminiPart(part: MessagePart) {
return part.type === "text"
? {
text: part.text,
@ -139,13 +142,13 @@ class Gemini extends BaseLLM {
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this._continuePartToGeminiPart),
: msg.content.map(this.continuePartToGeminiPart),
};
})
.filter((c) => c !== null);
const body = {
...this._convertArgs(options),
...this.convertArgs(options),
contents,
// if this.systemMessage is defined, reformat it for Gemini API
...(this.systemMessage &&

View file

@ -1,232 +0,0 @@
import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessagePart,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { streamResponse } from "../stream.js";
import VertexAI from "./VertexAI.js";
class GeminiVertexAI extends VertexAI {
static providerName: ModelProvider = "gemini-vertexai";
static defaultOptions: Partial<LLMOptions> = {
model: "gemini-pro",
region: "us-central1",
};
// Function to convert completion options to Gemini format
private _convertArgs(options: CompletionOptions) {
const finalOptions: any = {}; // Initialize an empty object
// Map known options
if (options.topK) {
finalOptions.topK = options.topK;
}
if (options.topP) {
finalOptions.topP = options.topP;
}
if (options.temperature !== undefined && options.temperature !== null) {
finalOptions.temperature = options.temperature;
}
if (options.maxTokens) {
finalOptions.maxOutputTokens = options.maxTokens;
}
if (options.stop) {
finalOptions.stopSequences = options.stop.filter((x) => x.trim() !== "");
}
return { generationConfig: finalOptions }; // Wrap options under 'generationConfig'
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const message of this._streamChat(
[{ content: prompt, role: "user" }],
options,
)) {
yield stripImages(message.content);
}
}
private removeSystemMessage(messages: ChatMessage[]) {
const msgs = [...messages];
if (msgs[0]?.role === "system") {
const sysMsg = msgs.shift()?.content;
// @ts-ignore
if (msgs[0]?.role === "user") {
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
}
}
return msgs;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const isV1API = this.apiBase.includes("/v1/");
// Conditionally apply removeSystemMessage
const convertedMsgs = isV1API
? this.removeSystemMessage(messages)
: messages;
if (options.model.includes("gemini")) {
yield* this.streamChatGemini(convertedMsgs, options);
} else {
yield* this.streamChatBison(convertedMsgs, options);
}
}
private _continuePartToGeminiPart(part: MessagePart) {
return part.type === "text"
? {
text: part.text,
}
: {
inlineData: {
mimeType: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}
private async *streamChatGemini(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const apiURL = new URL(
`publishers/google/models/${options.model}:streamGenerateContent`,
this.apiBase,
);
// 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 isV1API = this.apiBase.includes("/v1/");
const contents = messages
.map((msg) => {
if (msg.role === "system" && !isV1API) {
return null; // Don't include system message in contents
}
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 }] },
}),
};
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
});
let buffer = "";
for await (const chunk of streamResponse(response)) {
buffer += chunk;
if (buffer.startsWith("[")) {
buffer = buffer.slice(1);
}
if (buffer.endsWith("]")) {
buffer = buffer.slice(0, -1);
}
if (buffer.startsWith(",")) {
buffer = buffer.slice(1);
}
const parts = buffer.split("\n,");
let foundIncomplete = false;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
let data;
try {
data = JSON.parse(part);
} catch (e) {
foundIncomplete = true;
continue; // yo!
}
if (data.error) {
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;
const words = content.split(/(\s+)/);
const delaySeconds = Math.min(4.0 / (words.length + 1), 0.1);
while (words.length > 0) {
const wordsToYield = Math.min(3, words.length);
yield {
role: "assistant",
content: words.splice(0, wordsToYield).join(""),
};
await delay(delaySeconds);
}
} else {
// Handle the case where the expected data structure is not found
console.warn("Unexpected response format:", data);
}
}
if (foundIncomplete) {
buffer = parts[parts.length - 1];
} else {
buffer = "";
}
}
}
private async *streamChatBison(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const instances = messages.map((message) => ({ prompt: message.content }));
const apiURL = new URL(
`publishers/google/models/${options.model}:predict`,
this.apiBase,
);
const body = {
instances,
parameters: {
temperature: options.temperature,
maxOutputTokens: options.maxTokens,
topP: options.topP,
topK: options.topK,
stopSequences: options.stop,
presencePenalty: options.presencePenalty,
frequencyPenalty: options.frequencyPenalty,
},
};
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
});
const data = await response.json();
yield { role: "assistant", content: data.predictions[0].content };
}
}
async function delay(seconds: number) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
export default GeminiVertexAI;

View file

@ -18,6 +18,10 @@ class Groq extends OpenAI {
"llama3.1-8b": "llama-3.1-8b-instant",
"llama3.1-70b": "llama-3.1-70b-versatile",
"llama3.1-405b": "llama-3.1-405b-reasoning",
"llama3.2-1b": "llama-3.2-1b-preview",
"llama3.2-3b": "llama-3.2-3b-preview",
"llama3.2-11b": "llama-3.2-11b-vision-preview",
"llama3.2-90b": "llama-3.2-90b-vision-preview",
};
protected _convertModelName(model: string): string {
return Groq.modelConversion[model] ?? model;

View file

@ -1,106 +0,0 @@
import {
ChatMessage,
CompletionOptions,
LLMOptions,
ModelProvider
} from "../../index.js";
import { stripImages } from "../images.js";
import { streamSse } from "../stream.js";
import { gptEditPrompt } from "../templates/edit.js";
import VertexAI from "./VertexAI.js";
class MistralVertexAI extends VertexAI {
static providerName: ModelProvider = "mistral-vertexai";
static defaultOptions: Partial<LLMOptions> = {
region: "us-central1",
model: "codestral-latest",
promptTemplates: {
edit: gptEditPrompt,
},
};
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
options,
)) {
yield stripImages(chunk.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const apiBase = this.apiBase!;
const apiURL = new URL(
`publishers/mistralai/models/${options.model}:streamRawPredict`,
apiBase,
);
const lastMessage = messages[messages.length - 1];
if (lastMessage?.role === "assistant") {
(lastMessage as any).prefix = true;
}
const body = {
model: options.model,
temperature: options.temperature,
top_p: options.topP,
max_tokens: options.maxTokens,
stream: options.stream ?? true,
stop: options.stop,
messages,
};
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
});
for await (const chunk of streamSse(response)) {
yield chunk.choices[0].delta;
}
}
protected async *_streamFim(
prefix: string,
suffix: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const apiBase = this.apiBase!;
const apiURL = new URL(
`publishers/mistralai/models/${options.model}:streamRawPredict`,
apiBase,
);
const body = {
model: options.model,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
stream: options.stream ?? true,
stop: options.stop,
prompt: prefix,
suffix,
};
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
});
for await (const chunk of streamSse(response)) {
yield chunk.choices[0].delta.content;
}
}
supportsFim(): boolean {
return true;
}
}
export default MistralVertexAI;

View file

@ -2,24 +2,26 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { BaseLLM } from "../index.js";
class Mock extends BaseLLM {
static Completion = "Test Completion";
public completion: string = "Test Completion";
static providerName: ModelProvider = "mock";
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
yield Mock.Completion;
yield this.completion;
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
yield {
role: "assistant",
content: Mock.Completion,
};
for (const char of this.completion) {
yield {
role: "assistant",
content: char,
};
}
}
}

12
core/llm/llms/Nebius.ts Normal file
View file

@ -0,0 +1,12 @@
import { LLMOptions, ModelProvider } from "../..";
import OpenAI from "./OpenAI";
class Nebius extends OpenAI {
static providerName: ModelProvider = "nvidia";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.studio.nebius.ai/v1/",
useLegacyCompletionsEndpoint: false,
};
}
export default Nebius;

View file

@ -8,6 +8,59 @@ import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
interface OllamaChatMessage extends ChatMessage {
images?: string[];
}
// See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter
interface ModelFileParams {
mirostat?: number;
mirostat_eta?: number;
mirostat_tau?: number;
num_ctx?: number;
repeat_last_n?: number;
repeat_penalty?: number;
temperature?: number;
seed?: number;
stop?: string | string[];
tfs_z?: number;
num_predict?: number;
top_k?: number;
top_p?: number;
min_p?: number;
// deprecated?
num_thread?: number;
num_gqa?: number;
num_gpu?: number;
}
// See https://github.com/ollama/ollama/blob/main/docs/api.md
interface BaseOptions {
model: string; // the model name
options?: ModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature
format?: "json"; // the format to return a response in. Currently, the only accepted value is json
stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects
keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m)
}
interface GenerateOptions extends BaseOptions {
prompt: string; // the prompt to generate a response for
suffix?: string; // the text after the model response
images?: string[]; // a list of base64-encoded images (for multimodal models such as llava)
system?: string; // system message to (overrides what is defined in the Modelfile)
template?: string; // the prompt template to use (overrides what is defined in the Modelfile)
context?: string; // the context parameter returned from a previous request to /generate, this can be used to keep a short conversational memory
raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API
}
interface ChatOptions extends BaseOptions {
messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory
// Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false
// And correspondingly, tool calls in OllamaChatMessage
}
class Ollama extends BaseLLM {
static providerName: ModelProvider = "ollama";
static defaultOptions: Partial<LLMOptions> = {
@ -63,7 +116,7 @@ class Ollama extends BaseLLM {
this.completionOptions.stop.push(JSON.parse(value));
} catch (e) {
console.warn(
'Error parsing stop parameter value "{value}: ${e}',
`Error parsing stop parameter value "{value}: ${e}`,
);
}
break;
@ -101,6 +154,10 @@ class Ollama extends BaseLLM {
"llama3.1-8b": "llama3.1:8b",
"llama3.1-70b": "llama3.1:70b",
"llama3.1-405b": "llama3.1:405b",
"llama3.2-1b": "llama3.2:1b",
"llama3.2-3b": "llama3.2:3b",
"llama3.2-11b": "llama3.2:11b",
"llama3.2-90b": "llama3.2:90b",
"phi-2": "phi:2.7b",
"phind-codellama-34b": "phind-codellama:34b-v2",
"wizardcoder-7b": "wizardcoder:7b-python",
@ -124,49 +181,73 @@ class Ollama extends BaseLLM {
);
}
private _convertMessage(message: ChatMessage) {
private _getModelFileParams(options: CompletionOptions): ModelFileParams {
return {
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
num_predict: options.maxTokens,
stop: options.stop,
num_ctx: this.contextLength,
mirostat: options.mirostat,
num_thread: options.numThreads,
min_p: options.minP,
};
}
private _convertMessage(
message: ChatMessage
) {
if (typeof message.content === "string") {
return message;
}
const images: string[] = [];
message.content.forEach((part) => {
if (part.type === "imageUrl" && part.imageUrl) {
const image = part.imageUrl?.url.split(",").at(-1);
if (image) {
images.push(image);
}
}
});
return {
role: message.role,
content: stripImages(message.content),
images: message.content
.filter((part) => part.type === "imageUrl")
.map((part) => part.imageUrl?.url.split(",").at(-1)),
images
};
}
private _convertArgs(
private _getChatOptions(
options: CompletionOptions,
prompt: string | ChatMessage[],
suffix?: string,
) {
const finalOptions: any = {
messages: ChatMessage[]
): ChatOptions {
return {
model: this._getModel(),
raw: true,
messages: messages.map(this._convertMessage),
options: this._getModelFileParams(options),
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
suffix,
options: {
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
num_predict: options.maxTokens,
stop: options.stop,
num_ctx: this.contextLength,
mirostat: options.mirostat,
num_thread: options.numThreads,
},
stream: options.stream,
format: "json",
};
}
if (typeof prompt === "string") {
finalOptions.prompt = prompt;
} else {
finalOptions.messages = prompt.map(this._convertMessage);
}
return finalOptions;
private _getGenerateOptions(
options: CompletionOptions,
prompt: string,
suffix?: string
): GenerateOptions {
return {
model: this._getModel(),
prompt,
suffix,
raw: options.raw,
options: this._getModelFileParams(options),
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
stream: options.stream,
format: "json"
// Not supported yet: context, images, system, template
};
}
private getEndpoint(endpoint: string): URL {
@ -188,7 +269,7 @@ class Ollama extends BaseLLM {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._convertArgs(options, prompt)),
body: JSON.stringify(this._getGenerateOptions(options, prompt)),
});
let buffer = "";
@ -227,7 +308,7 @@ class Ollama extends BaseLLM {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._convertArgs(options, messages)),
body: JSON.stringify(this._getChatOptions(options, messages)),
});
let buffer = "";
@ -274,7 +355,7 @@ class Ollama extends BaseLLM {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._convertArgs(options, prefix, suffix)),
body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)),
});
let buffer = "";

View file

@ -37,6 +37,8 @@ const CHAT_ONLY_MODELS = [
"gpt-4-0125-preview",
"gpt-4-1106-preview",
"gpt-4o-mini",
"o1-preview",
"o1-mini",
];
class OpenAI extends BaseLLM {
@ -111,9 +113,9 @@ class OpenAI extends BaseLLM {
: url.host === "api.deepseek.com"
? options.stop?.slice(0, 16)
: url.port === "1337" ||
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
};

View file

@ -59,10 +59,10 @@ class SageMaker extends BaseLLM {
const data = JSON.parse(line.replace(/^data:/, ''));
let text = undefined;
if ("choices" in data) {
if ("delta" in data.choices[0]){
if ("delta" in data.choices[0]) {
text = data.choices[0].delta.content;
}
else{
else {
text = data.choices[0].text;
}
}
@ -110,10 +110,10 @@ class SageMaker extends BaseLLM {
const data = JSON.parse(line.replace(/^data:/, ''));
let text = undefined;
if ("choices" in data) {
if ("delta" in data.choices[0]){
if ("delta" in data.choices[0]) {
text = data.choices[0].delta.content;
}
else{
else {
text = data.choices[0].text;
}
}

View file

@ -12,6 +12,8 @@ class SambaNova extends OpenAI {
"llama3.1-8b": "Meta-Llama-3.1-8B-Instruct",
"llama3.1-70b": "Meta-Llama-3.1-70B-Instruct",
"llama3.1-405b": "Meta-Llama-3.1-405B-Instruct",
"llama3.1-1b": "Meta-Llama-3.2-1B-Instruct",
"llama3.1-3b": "Meta-Llama-3.2-3B-Instruct",
};
protected _convertModelName(model: string) {

View file

@ -22,6 +22,9 @@ class Together extends OpenAI {
"llama3.1-8b": "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",
"llama3.1-70b": "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
"llama3.1-405b": "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo",
"llama3.2-3b": "meta-llama/Llama-3.2-3B-Instruct-Turbo",
"llama3.2-11b": "meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo",
"llama3.2-90b": "meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo",
"llama2-7b": "togethercomputer/llama-2-7b-chat",
"llama2-13b": "togethercomputer/llama-2-13b-chat",
"llama2-70b": "togethercomputer/llama-2-70b-chat",

View file

@ -1,9 +1,24 @@
import { GoogleAuth } from "google-auth-library";
import { LLMOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
import { stripImages } from "../images.js";
import { streamSse } from "../stream.js";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessagePart,
ModelProvider,
} from "../../index.js";
import { streamResponse } from "../stream.js";
import Anthropic from "./Anthropic.js";
import Gemini from "./Gemini.js";
abstract class VertexAI extends BaseLLM {
class VertexAI extends BaseLLM {
static providerName: ModelProvider = "vertexai";
declare apiBase: string;
declare vertexProvider: string;
declare anthropicInstance: Anthropic;
declare geminiInstance: Gemini;
private clientPromise = new GoogleAuth({
scopes: "https://www.googleapis.com/auth/cloud-platform",
@ -22,6 +37,17 @@ abstract class VertexAI extends BaseLLM {
constructor(_options: LLMOptions) {
super(_options);
this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options);
this.vertexProvider =
_options.model.includes("mistral") || _options.model.includes("codestral") || _options.model.includes("mixtral")
? "mistral"
: _options.model.includes("claude")
? "anthropic"
: _options.model.includes("gemini")
? "gemini" :
"unknown";
this.anthropicInstance = new Anthropic(_options);
this.geminiInstance = new Gemini(_options)
}
async fetch(url: RequestInfo | URL, init?: RequestInit) {
@ -41,6 +67,373 @@ abstract class VertexAI extends BaseLLM {
},
});
}
// Anthropic functions
private _anthropicConvertArgs(options: CompletionOptions) {
const convertedArgs = this.anthropicInstance.convertArgs(options);
// Remove the `model` property and add `anthropic_version`
const { model, ...finalOptions } = convertedArgs;
return {
...finalOptions,
anthropic_version: "vertex-2023-10-16",
};
}
protected async *StreamChatAnthropic(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const systemMessage: string = stripImages(
messages.filter((m) => m.role === "system")[0]?.content,
);
const apiURL = new URL(
`publishers/anthropic/models/${options.model}:streamRawPredict`,
this.apiBase
);
const response = await this.fetch(apiURL, {
method: "POST",
headers: {
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
? { "anthropic-beta": "prompt-caching-2024-07-31" }
: {}),
},
body: JSON.stringify({
...this._anthropicConvertArgs(options),
messages: this.anthropicInstance.convertMessages(messages),
system: shouldCacheSystemMessage
? [
{
type: "text",
text: this.systemMessage,
cache_control: { type: "ephemeral" },
},
]
: systemMessage,
}),
});
if (options.stream === false) {
const data = await response.json();
yield { role: "assistant", content: data.content[0].text };
return;
}
for await (const value of streamSse(response)) {
if (value.type == "message_start") console.log(value);
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}
}
}
//Gemini
private async *streamChatGemini(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const apiURL = new URL(
`publishers/google/models/${options.model}:streamGenerateContent`,
this.apiBase,
);
// 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 isV1API = this.apiBase.includes("/v1/");
const contents = messages
.map((msg) => {
if (msg.role === "system" && !isV1API) {
return null; // Don't include system message in contents
}
return {
role: msg.role === "assistant" ? "model" : "user",
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this.geminiInstance.continuePartToGeminiPart),
};
})
.filter((c) => c !== null);
const body = {
...this.geminiInstance.convertArgs(options),
contents,
// if this.systemMessage is defined, reformat it for Gemini API
...(this.systemMessage &&
!isV1API && {
systemInstruction: { parts: [{ text: this.systemMessage }] },
}),
};
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
});
let buffer = "";
for await (const chunk of streamResponse(response)) {
buffer += chunk;
if (buffer.startsWith("[")) {
buffer = buffer.slice(1);
}
if (buffer.endsWith("]")) {
buffer = buffer.slice(0, -1);
}
if (buffer.startsWith(",")) {
buffer = buffer.slice(1);
}
const parts = buffer.split("\n,");
let foundIncomplete = false;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
let data;
try {
data = JSON.parse(part);
} catch (e) {
foundIncomplete = true;
continue; // yo!
}
if (data.error) {
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;
const words = content.split(/(\s+)/);
const delaySeconds = Math.min(4.0 / (words.length + 1), 0.1);
while (words.length > 0) {
const wordsToYield = Math.min(3, words.length);
yield {
role: "assistant",
content: words.splice(0, wordsToYield).join(""),
};
await delay(delaySeconds);
}
} else {
// Handle the case where the expected data structure is not found
if (data?.candidates?.[0]?.finishReason !== "STOP") {
console.warn("Unexpected response format:", data);
}
}
}
if (foundIncomplete) {
buffer = parts[parts.length - 1];
} else {
buffer = "";
}
}
}
private async *streamChatBison(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const instances = messages.map((message) => ({ prompt: message.content }));
const apiURL = new URL(
`publishers/google/models/${options.model}:predict`,
this.apiBase,
);
const body = {
instances,
parameters: {
temperature: options.temperature,
maxOutputTokens: options.maxTokens,
topP: options.topP,
topK: options.topK,
stopSequences: options.stop,
presencePenalty: options.presencePenalty,
frequencyPenalty: options.frequencyPenalty,
},
};
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
});
const data = await response.json();
yield { role: "assistant", content: data.predictions[0].content };
}
//Mistral
protected async *StreamChatMistral(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const apiBase = this.apiBase!;
const apiURL = new URL(
`publishers/mistralai/models/${options.model}:streamRawPredict`,
apiBase,
);
const lastMessage = messages[messages.length - 1];
if (lastMessage?.role === "assistant") {
(lastMessage as any).prefix = true;
}
const body = {
model: options.model,
temperature: options.temperature,
top_p: options.topP,
max_tokens: options.maxTokens,
stream: options.stream ?? true,
stop: options.stop,
messages,
};
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
});
for await (const chunk of streamSse(response)) {
if (chunk.choices?.[0]) {
// At the end vertexai will return a empty chunk.
yield chunk.choices[0].delta;
}
}
}
protected async *StreamFimMistral(
prefix: string,
suffix: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const apiBase = this.apiBase!;
const apiURL = new URL(
`publishers/mistralai/models/${options.model}:streamRawPredict`,
apiBase,
);
const body = {
model: options.model,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
stream: options.stream ?? true,
stop: options.stop,
prompt: prefix,
suffix,
};
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
});
for await (const chunk of streamSse(response)) {
yield chunk.choices[0].delta.content;
}
}
//gecko
protected async *streamFimGecko(
prefix: string,
suffix: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
instances: [
{
prefix: prefix,
suffix: suffix
}
],
parameters: {
temperature: options.temperature,
maxOutputTokens: Math.min(options.maxTokens ?? 64, 64),
stopSequences: options.stop?.splice(0, 5),
frequencyPenalty: options.frequencyPenalty,
presencePenalty: options.frequencyPenalty,
}
}),
});
// Streaming is not supported by code-gecko
// TODO: convert to non-streaming fim method when one exist in continue.
yield (await resp.json()).predictions[0].content;
}
//Manager functions
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const isV1API = this.apiBase.includes("/v1/");
// Conditionally apply removeSystemMessage
const convertedMsgs = isV1API
? this.geminiInstance.removeSystemMessage(messages)
: messages;
if (this.vertexProvider == "gemini") {
yield* this.streamChatGemini(convertedMsgs, options);
} else if (this.vertexProvider == "mistral") {
yield* this.StreamChatMistral(messages, options);
} else if (this.vertexProvider == "anthropic") {
yield* this.StreamChatAnthropic(messages, options)
} else {
if (options.model.includes("bison")) {
yield* this.streamChatBison(convertedMsgs, options);
}
}
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const message of this._streamChat(
[{ content: prompt, role: "user" }],
options,
)) {
yield stripImages(message.content);
}
}
protected async *_streamFim(
prefix: string,
suffix: string,
options: CompletionOptions,
): AsyncGenerator<string> {
if (this.model === "code-gecko") {
yield* this.streamFimGecko(prefix, suffix, options);
} else if (this.model.includes("codestral")) {
yield* this.StreamFimMistral(prefix, suffix, options);
} else {
throw new Error(`Unsupported model: ${this.model}`);
}
}
supportsFim(): boolean {
return ["code-gecko", "codestral-latest"].includes(this.model);
}
}
async function delay(seconds: number) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
export default VertexAI;

View file

@ -7,26 +7,26 @@ import {
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
const watsonxConfig = {
accessToken: {
expiration: 0,
token: "",
},
};
let watsonxToken = {
expiration: 0,
token: ""
}
class WatsonX extends BaseLLM {
constructor(options: LLMOptions) {
super(options);
}
async getBearerToken(): Promise<{ token: string; expiration: number }> {
if (
this.watsonxFullUrl?.includes("cloud.ibm.com") ||
this.watsonxUrl?.includes("cloud.ibm.com")
this.apiBase?.includes("cloud.ibm.com")
) {
// watsonx SaaS
const wxToken = await (
await fetch(
`https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxCreds}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
`https://iam.cloud.ibm.com/identity/token?apikey=${this.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
{
method: "POST",
headers: {
@ -42,17 +42,17 @@ class WatsonX extends BaseLLM {
};
} else {
// watsonx Software
if (!this.watsonxCreds?.includes(":")) {
if (!this.apiKey?.includes(":")) {
// Using ZenApiKey auth
return {
token: this.watsonxCreds ?? "",
token: this.apiKey ?? "",
expiration: -1,
};
} else {
// Using username/password auth
const userPass = this.watsonxCreds?.split(":");
const userPass = this.apiKey?.split(":");
const wxToken = await (
await fetch(`${this.watsonxUrl}/icp4d-api/v1/authorize`, {
await fetch(`${this.apiBase}/icp4d-api/v1/authorize`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@ -65,7 +65,7 @@ class WatsonX extends BaseLLM {
})
).json();
const wxTokenExpiry = await (
await fetch(`${this.watsonxUrl}/usermgmt/v1/user/tokenExpiry`, {
await fetch(`${this.apiBase}/usermgmt/v1/user/tokenExpiry`, {
method: "GET",
headers: {
Accept: "application/json",
@ -83,8 +83,9 @@ class WatsonX extends BaseLLM {
getWatsonxEndpoint(): string {
return (
this.watsonxFullUrl ??
`${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`
this.deploymentId ?
`${this.apiBase}/ml/v1/deployments/${this.deploymentId}/text/generation_stream?version=${this.apiVersion}`:
`${this.apiBase}/ml/v1/text/generation_stream?version=${this.apiVersion}`
);
}
@ -132,8 +133,8 @@ class WatsonX extends BaseLLM {
protected _getHeaders() {
return {
"Content-Type": "application/json",
Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"
} ${watsonxConfig.accessToken.token}`,
Authorization: `${watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer"
} ${watsonxToken.token}`,
};
}
@ -170,24 +171,22 @@ class WatsonX extends BaseLLM {
): AsyncGenerator<ChatMessage> {
var now = new Date().getTime() / 1000;
if (
watsonxConfig.accessToken === undefined ||
now > watsonxConfig.accessToken.expiration ||
watsonxConfig.accessToken.token === undefined
watsonxToken === undefined ||
now > watsonxToken.expiration ||
watsonxToken.token === undefined
) {
watsonxConfig.accessToken = await this.getBearerToken();
watsonxToken = await this.getBearerToken();
} else {
console.log(
`Reusing token (expires in ${(watsonxConfig.accessToken.expiration - now) / 60
`Reusing token (expires in ${(watsonxToken.expiration - now) / 60
} mins)`,
);
}
if (watsonxConfig.accessToken.token === undefined) {
if (watsonxToken.token === undefined) {
throw new Error("Something went wrong. Check your credentials, please.");
}
const stopToken =
this.watsonxStopToken ??
(options.model?.includes("granite") ? "<|im_end|>" : undefined);
const stopSequences =
options.stop?.slice(0,6) ?? (options.model?.includes("granite") ? ["Question:"] : []);
const url = this.getWatsonxEndpoint();
const headers = this._getHeaders();
@ -195,24 +194,25 @@ class WatsonX extends BaseLLM {
decoding_method: "greedy",
max_new_tokens: options.maxTokens ?? 1024,
min_new_tokens: 1,
stop_sequences: stopToken ? [stopToken] : [],
stop_sequences: stopSequences,
include_stop_sequence: false,
repetition_penalty: 1,
truncate_input_tokens: this.contextLength - (options.maxTokens ?? 1024),
repetition_penalty: options.frequencyPenalty || 1,
};
if (!!options.temperature) {
parameters.decoding_method = "sample";
parameters.temperature = options.temperature;
parameters.top_p = options.topP || 1.0;
parameters.top_k = options.topK;
parameters.top_k = options.topK || 100;
}
const payload: any = {
input: messages[messages.length - 1].content,
parameters: parameters,
};
if (!this.watsonxFullUrl) {
if (!this.deploymentId) {
payload.model_id = options.model;
payload.project_id = this.watsonxProjectId;
payload.project_id = this.projectId;
}
var response = await this.fetch(url, {
@ -245,7 +245,8 @@ class WatsonX extends BaseLLM {
generatedChunk += result.generated_text || "";
});
} catch (e) {
console.error(`Error parsing JSON string: ${dataStr}`, e);
// parsing error is expected with streaming response
// console.error(`Error parsing JSON string: ${dataStr}`, e);
}
}
});

View file

@ -8,7 +8,6 @@ import {
import { renderTemplatedString } from "../../promptFiles/renderTemplatedString";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import AnthropicVertexAI from "./AnthropicVertexAI";
import Azure from "./Azure";
import Bedrock from "./Bedrock";
import BedrockImport from "./BedrockImport";
@ -21,7 +20,6 @@ import Fireworks from "./Fireworks";
import Flowise from "./Flowise";
import FreeTrial from "./FreeTrial";
import Gemini from "./Gemini";
import GeminiVertexAI from "./GeminiVertexAI";
import Groq from "./Groq";
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
import HuggingFaceTGI from "./HuggingFaceTGI";
@ -30,9 +28,9 @@ import LMStudio from "./LMStudio";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import Mistral from "./Mistral";
import MistralVertexAI from "./MistralVertexAI";
import Mock from "./Mock";
import Msty from "./Msty";
import Nebius from "./Nebius";
import Nvidia from "./Nvidia";
import Ollama from "./Ollama";
import OpenAI from "./OpenAI";
@ -45,14 +43,14 @@ import Together from "./Together";
import Vllm from "./Vllm";
import WatsonX from "./WatsonX";
import ContinueProxy from "./stubs/ContinueProxy";
import VertexAI from "./VertexAI";
import Asksage from "./Asksage";
const LLMs = [
Anthropic,
AnthropicVertexAI,
Cohere,
FreeTrial,
Gemini,
GeminiVertexAI,
Llamafile,
Ollama,
Replicate,
@ -65,7 +63,6 @@ const LLMs = [
OpenAI,
LMStudio,
Mistral,
MistralVertexAI,
Bedrock,
BedrockImport,
SageMaker,
@ -85,6 +82,9 @@ const LLMs = [
SambaNova,
Mock,
Cerebras,
Asksage,
Nebius,
VertexAI
];
export async function llmFromDescription(

View file

@ -274,12 +274,22 @@ const gemmaTemplateMessage = templateFactory(
"<end_of_turn>\n",
);
const graniteTemplateMessages = templateFactory(
(msg) => (!!msg ? `\n\nSystem:\n ${msg.content}\n\n` : ""),
"Question:\n",
"Answer:\n",
"\n\n",
"",
"",
);
export {
anthropicTemplateMessages,
chatmlTemplateMessages,
codeLlama70bTemplateMessages,
deepseekTemplateMessages,
gemmaTemplateMessage,
graniteTemplateMessages,
llama2TemplateMessages,
llama3TemplateMessages,
llavaTemplateMessages,

78
core/package-lock.json generated
View file

@ -17,7 +17,6 @@
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
@ -89,7 +88,6 @@
"cross-env": "^7.0.3",
"esbuild": "0.17.19",
"eslint": "^8",
"eslint-plugin-import": "^2.29.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"myers-diff": "^2.1.0",
@ -4969,7 +4967,8 @@
"node_modules/@types/json5": {
"version": "0.0.29",
"resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz",
"integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ=="
"integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==",
"peer": true
},
"node_modules/@types/long": {
"version": "4.0.2",
@ -5224,6 +5223,7 @@
"version": "7.10.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.10.0.tgz",
"integrity": "sha512-2EjZMA0LUW5V5tGQiaa2Gys+nKdfrn2xiTIBLR4fxmPmVSvgPcKNW+AE/ln9k0A4zDUti0J/GZXMDupQoI+e1w==",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "7.10.0",
"@typescript-eslint/types": "7.10.0",
@ -5645,6 +5645,7 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.1.tgz",
"integrity": "sha512-ahC5W1xgou+KTXix4sAO8Ki12Q+jf4i0+tmk3sC+zgcynshkHxzpXdImBehiUYKKKDwvfFiJl1tZt6ewscS1Mg==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.5",
"is-array-buffer": "^3.0.4"
@ -5660,6 +5661,7 @@
"version": "3.1.8",
"resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.8.tgz",
"integrity": "sha512-itaWrbYbqpGXkGhZPGUulwnhVf5Hpy1xiCFsGqyIGglbBxmG5vSjxQen3/WGOjPpNEv1RtBLKxbmVXm8HpJStQ==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1",
@ -5692,6 +5694,7 @@
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.5.tgz",
"integrity": "sha512-zfETvRFA8o7EiNn++N5f/kaCw221hrpGsDmcpndVupkPzEc1Wuf3VgC0qby1BbHs7f5DVYjgtEU2LLh5bqeGfQ==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1",
@ -5711,6 +5714,7 @@
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.2.tgz",
"integrity": "sha512-djYB+Zx2vLewY8RWlNCUdHjDXs2XOgm602S9E7P/UpHgfeHL00cRiIF+IN/G/aUJ7kGPb6yO/ErDI5V2s8iycA==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.2",
"define-properties": "^1.2.0",
@ -5728,6 +5732,7 @@
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.2.tgz",
"integrity": "sha512-Ewyx0c9PmpcsByhSW4r+9zDU7sGjFc86qf/kKtuSCRdhfbk0SNLLkaT5qvcHnRGgc5NP/ly/y+qkXkqONX54CQ==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.2",
"define-properties": "^1.2.0",
@ -5745,6 +5750,7 @@
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.3.tgz",
"integrity": "sha512-bMxMKAjg13EBSVscxTaYA4mRc5t1UAXa2kXiGTNfZ079HIWXEkKmkgFrh/nJqamaLSrXO5H4WFFkPEaLJWbs3A==",
"peer": true,
"dependencies": {
"array-buffer-byte-length": "^1.0.1",
"call-bind": "^1.0.5",
@ -5806,6 +5812,7 @@
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",
"integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==",
"peer": true,
"dependencies": {
"possible-typed-array-names": "^1.0.0"
},
@ -6901,6 +6908,7 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.1.tgz",
"integrity": "sha512-0lht7OugA5x3iJLOWFhWK/5ehONdprk0ISXqVFn/NFrDu+cuc8iADFrGQz5BnRK7LLU3JmkbXSxaqX+/mXYtUA==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.6",
"es-errors": "^1.3.0",
@ -6917,6 +6925,7 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.1.tgz",
"integrity": "sha512-4J7wRJD3ABAzr8wP+OcIcqq2dlUKp4DVflx++hs5h5ZKydWMI6/D/fAot+yh6g2tHh8fLFTvNOaVN357NvSrOQ==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"es-errors": "^1.3.0",
@ -6933,6 +6942,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.0.tgz",
"integrity": "sha512-t/Ygsytq+R995EJ5PZlD4Cu56sWa8InXySaViRzw9apusqsOO2bQP+SbYzAhR0pFKoB+43lYy8rWban9JSuXnA==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.6",
"es-errors": "^1.3.0",
@ -7396,6 +7406,7 @@
"version": "1.23.3",
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.3.tgz",
"integrity": "sha512-e+HfNH61Bj1X9/jLc5v1owaLYuHdeHHSQlkhCBiTK8rBvKaULl/beGMxwrMXjpYrv4pz22BlY570vVePA2ho4A==",
"peer": true,
"dependencies": {
"array-buffer-byte-length": "^1.0.1",
"arraybuffer.prototype.slice": "^1.0.3",
@ -7485,6 +7496,7 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.0.3.tgz",
"integrity": "sha512-3T8uNMC3OQTHkFUsFq8r/BwAXLHvU/9O9mE0fBc/MY5iq/8H7ncvO947LmYA6ldWw9Uh8Yhf25zu6n7nML5QWQ==",
"peer": true,
"dependencies": {
"get-intrinsic": "^1.2.4",
"has-tostringtag": "^1.0.2",
@ -7498,6 +7510,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.0.2.tgz",
"integrity": "sha512-J3yBRXCzDu4ULnQwxyToo/OjdMx6akgVC7K6few0a7F/0wLtmKKN7I73AH5T2836UuXRqN7Qg+IIUw/+YJksRw==",
"peer": true,
"dependencies": {
"hasown": "^2.0.0"
}
@ -7506,6 +7519,7 @@
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.1.tgz",
"integrity": "sha512-QCOllgZJtaUo9miYBcLChTUaHNjJF3PYs1VidD7AwiEj1kYxKeQTctLAezAOH5ZKRH0g2IgPn6KwB4IT8iRpvA==",
"peer": true,
"dependencies": {
"is-callable": "^1.1.4",
"is-date-object": "^1.0.1",
@ -7690,6 +7704,7 @@
"version": "0.3.9",
"resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz",
"integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==",
"peer": true,
"dependencies": {
"debug": "^3.2.7",
"is-core-module": "^2.13.0",
@ -7700,6 +7715,7 @@
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",
"integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
"peer": true,
"dependencies": {
"ms": "^2.1.1"
}
@ -7708,6 +7724,7 @@
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.8.1.tgz",
"integrity": "sha512-rXDXR3h7cs7dy9RNpUlQf80nX31XWJEyGq1tRMo+6GsO5VmTe4UTwtmonAD4ZkAsrfMVDA2wlGJ3790Ys+D49Q==",
"peer": true,
"dependencies": {
"debug": "^3.2.7"
},
@ -7724,6 +7741,7 @@
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",
"integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
"peer": true,
"dependencies": {
"ms": "^2.1.1"
}
@ -7732,6 +7750,7 @@
"version": "2.29.1",
"resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.29.1.tgz",
"integrity": "sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==",
"peer": true,
"dependencies": {
"array-includes": "^3.1.7",
"array.prototype.findlastindex": "^1.2.3",
@ -7762,6 +7781,7 @@
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"peer": true,
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
@ -7771,6 +7791,7 @@
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",
"integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
"peer": true,
"dependencies": {
"ms": "^2.1.1"
}
@ -7779,6 +7800,7 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz",
"integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==",
"peer": true,
"dependencies": {
"esutils": "^2.0.2"
},
@ -7790,6 +7812,7 @@
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"peer": true,
"dependencies": {
"brace-expansion": "^1.1.7"
},
@ -7801,6 +7824,7 @@
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"peer": true,
"bin": {
"semver": "bin/semver.js"
}
@ -8258,6 +8282,7 @@
"version": "0.3.3",
"resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz",
"integrity": "sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==",
"peer": true,
"dependencies": {
"is-callable": "^1.1.3"
}
@ -8413,6 +8438,7 @@
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.6.tgz",
"integrity": "sha512-Z5kx79swU5P27WEayXM1tBi5Ze/lbIyiNgU3qyXUOf9b2rgXYyF9Dy9Cx+IQv/Lc8WCG6L82zwUPpSS9hGehIg==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.2",
"define-properties": "^1.2.0",
@ -8430,6 +8456,7 @@
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz",
"integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
@ -8593,6 +8620,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.0.2.tgz",
"integrity": "sha512-g0QYk1dZBxGwk+Ngc+ltRH2IBp2f7zBkBMBJZCDerh6EhlhSR6+9irMCuT/09zD6qkarHUSn529sK/yL4S27mg==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.5",
"es-errors": "^1.3.0",
@ -8708,6 +8736,7 @@
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz",
"integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",
"peer": true,
"dependencies": {
"define-properties": "^1.2.1",
"gopd": "^1.0.1"
@ -8904,6 +8933,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz",
"integrity": "sha512-tSvCKtBr9lkF0Ex0aQiP9N+OpV4zi2r/Nee5VkRDbaqv35RLYMzbwQfFSZZH0kR+Rd6302UJZ2p/bJCEoR3VoQ==",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
@ -8961,6 +8991,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"peer": true,
"dependencies": {
"has-symbols": "^1.0.3"
},
@ -9209,6 +9240,7 @@
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.7.tgz",
"integrity": "sha512-NGnrKwXzSms2qUUih/ILZ5JBqNTSa1+ZmP6flaIp6KmSElgE9qdndzS3cqjrDovwFdmwsGsLdeFgB6suw+1e9g==",
"peer": true,
"dependencies": {
"es-errors": "^1.3.0",
"hasown": "^2.0.0",
@ -9234,6 +9266,7 @@
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.4.tgz",
"integrity": "sha512-wcjaerHw0ydZwfhiKbXJWLDY8A7yV7KhjQOpb83hGgGfId/aQa4TOvwyzn2PuswW2gPCYEL/nEAiSVpdOj1lXw==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.2",
"get-intrinsic": "^1.2.1"
@ -9254,6 +9287,7 @@
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.0.4.tgz",
"integrity": "sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==",
"peer": true,
"dependencies": {
"has-bigints": "^1.0.1"
},
@ -9265,6 +9299,7 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.1.2.tgz",
"integrity": "sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.2",
"has-tostringtag": "^1.0.0"
@ -9280,6 +9315,7 @@
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz",
"integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==",
"peer": true,
"engines": {
"node": ">= 0.4"
},
@ -9302,6 +9338,7 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.1.tgz",
"integrity": "sha512-AHkaJrsUVW6wq6JS8y3JnM/GJF/9cf+k20+iDzlSaJrinEo5+7vRiteOSwBhHRiAyQATN1AmY4hwzxJKPmYf+w==",
"peer": true,
"dependencies": {
"is-typed-array": "^1.1.13"
},
@ -9316,6 +9353,7 @@
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.5.tgz",
"integrity": "sha512-9YQaSxsAiSwcvS33MBk3wTCVnWK+HhF8VZR2jRxehM16QcVOdHqPn4VPHmRK4lSr38n9JriurInLcP90xsYNfQ==",
"peer": true,
"dependencies": {
"has-tostringtag": "^1.0.0"
},
@ -9377,6 +9415,7 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz",
"integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==",
"peer": true,
"engines": {
"node": ">= 0.4"
},
@ -9396,6 +9435,7 @@
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.0.7.tgz",
"integrity": "sha512-k1U0IRzLMo7ZlYIfzRu23Oh6MiIFasgpb9X76eqfFZAqwH44UI4KTBvBYIZ1dSL9ZzChTB9ShHfLkR4pdW5krQ==",
"peer": true,
"dependencies": {
"has-tostringtag": "^1.0.0"
},
@ -9428,6 +9468,7 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.4.tgz",
"integrity": "sha512-kvRdxDsxZjhzUX07ZnLydzS1TU/TJlTUHHY4YLL87e37oUA49DfkLqgy+VjFocowy29cKvcSiu+kIv728jTTVg==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.2",
"has-tostringtag": "^1.0.0"
@ -9443,6 +9484,7 @@
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.3.tgz",
"integrity": "sha512-nA2hv5XIhLR3uVzDDfCIknerhx8XUKnstuOERPNNIinXG7v9u+ohXF67vxm4TPTEPU6lm61ZkwP3c9PCB97rhg==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7"
},
@ -9468,6 +9510,7 @@
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.7.tgz",
"integrity": "sha512-tE2UXzivje6ofPW7l23cjDOMa09gb7xlAqG6jG5ej6uPV32TlWP3NKPigtaGeHNu9fohccRYvIiZMfOOnOYUtg==",
"peer": true,
"dependencies": {
"has-tostringtag": "^1.0.0"
},
@ -9482,6 +9525,7 @@
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.4.tgz",
"integrity": "sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==",
"peer": true,
"dependencies": {
"has-symbols": "^1.0.2"
},
@ -9496,6 +9540,7 @@
"version": "1.1.13",
"resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.13.tgz",
"integrity": "sha512-uZ25/bUAlUY5fR4OKT4rZQEBrzQWYV9ZJYGGsUmEJ6thodVJ1HX64ePQ6Z0qPWP+m+Uq6e9UugrE38jeYsDSMw==",
"peer": true,
"dependencies": {
"which-typed-array": "^1.1.14"
},
@ -9515,6 +9560,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz",
"integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.2"
},
@ -9525,7 +9571,8 @@
"node_modules/isarray": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",
"integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw=="
"integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",
"peer": true
},
"node_modules/isexe": {
"version": "2.0.0",
@ -11569,6 +11616,7 @@
"version": "1.13.1",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz",
"integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
@ -11615,6 +11663,7 @@
"version": "2.0.8",
"resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz",
"integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1",
@ -11632,6 +11681,7 @@
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz",
"integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1",
@ -11645,6 +11695,7 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.0.tgz",
"integrity": "sha512-yBYjY9QX2hnRmZHAjG/f13MzmBzxzYgQhFrke06TTyKY5zSTEqkOeukBzIdVA3j3ulu8Qa3MbVFShV7T2RmGtQ==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1",
@ -12294,6 +12345,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.0.0.tgz",
"integrity": "sha512-d7Uw+eZoloe0EHDIYoe+bQ5WXnGMOpmiZFTuMWCwpjzzkL2nTjcKiAk4hh8TjnGye2TwWOk3UXucZ+3rbmBa8Q==",
"peer": true,
"engines": {
"node": ">= 0.4"
}
@ -12869,6 +12921,7 @@
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.2.tgz",
"integrity": "sha512-NcDiDkTLuPR+++OCKB0nWafEmhg/Da8aUPLPMQbK+bxKKCm1/S5he+AqYa4PlMCVBalb4/yxIRub6qkEx5yJbw==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.6",
"define-properties": "^1.2.1",
@ -13142,6 +13195,7 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.2.tgz",
"integrity": "sha512-vj6RsCsWBCf19jIeHEfkRMw8DPiBb+DMXklQ/1SGDHOMlHdPUkZXFQ2YdplS23zESTijAcurb1aSgJA3AgMu1Q==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"get-intrinsic": "^1.2.4",
@ -13178,6 +13232,7 @@
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.0.3.tgz",
"integrity": "sha512-CdASjNJPvRa7roO6Ra/gLYBTzYzzPyyBXxIMdGW3USQLyjWEls2RgW5UBTXaQVp+OrpeCK3bLem8smtmheoRuw==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.6",
"es-errors": "^1.3.0",
@ -13248,6 +13303,7 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz",
"integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==",
"peer": true,
"dependencies": {
"define-data-property": "^1.1.4",
"es-errors": "^1.3.0",
@ -13303,6 +13359,7 @@
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz",
"integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"es-errors": "^1.3.0",
@ -13724,6 +13781,7 @@
"version": "1.2.9",
"resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.9.tgz",
"integrity": "sha512-klHuCNxiMZ8MlsOihJhJEBJAiMVqU3Z2nEXWfWnIqjN0gEFS9J9+IxKozWWtQGcgoa1WUZzLjKPTr4ZHNFTFxw==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1",
@ -13741,6 +13799,7 @@
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.8.tgz",
"integrity": "sha512-p73uL5VCHCO2BZZ6krwwQE3kCzM7NKmis8S//xEC6fQonchbum4eP6kR4DLEjQFO3Wnj3Fuo8NM0kOSjVdHjZQ==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1",
@ -13754,6 +13813,7 @@
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz",
"integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1",
@ -14184,6 +14244,7 @@
"version": "3.15.0",
"resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz",
"integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==",
"peer": true,
"dependencies": {
"@types/json5": "^0.0.29",
"json5": "^1.0.2",
@ -14195,6 +14256,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz",
"integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==",
"peer": true,
"dependencies": {
"minimist": "^1.2.0"
},
@ -14206,6 +14268,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz",
"integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==",
"peer": true,
"engines": {
"node": ">=4"
}
@ -14266,6 +14329,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.2.tgz",
"integrity": "sha512-gEymJYKZtKXzzBzM4jqa9w6Q1Jjm7x2d+sh19AdsD4wqnMPDYyvwpsIc2Q/835kHuo3BEQ7CjelGhfTsoBb2MQ==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"es-errors": "^1.3.0",
@ -14279,6 +14343,7 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.1.tgz",
"integrity": "sha512-3iMJ9q0ao7WE9tWcaYKIptkNBuOIcZCCT0d4MRvuuH88fEoEH62IuQe0OtraD3ebQEoTRk8XCBoknUNc1Y67pw==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"for-each": "^0.3.3",
@ -14297,6 +14362,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.2.tgz",
"integrity": "sha512-Ous0vodHa56FviZucS2E63zkgtgrACj7omjwd/8lTEMEPFFyjfixMZ1ZXenpgCFBBt4EC1J2XsyVS2gkG0eTFA==",
"peer": true,
"dependencies": {
"available-typed-arrays": "^1.0.7",
"call-bind": "^1.0.7",
@ -14316,6 +14382,7 @@
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.6.tgz",
"integrity": "sha512-/OxDN6OtAk5KBpGb28T+HZc2M+ADtvRxXrKKbUwtsLgdoxgX13hyy7ek6bFRl5+aBs2yZzB0c4CnQfAtVypW/g==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.7",
"for-each": "^0.3.3",
@ -14374,6 +14441,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz",
"integrity": "sha512-61pPlCD9h51VoreyJ0BReideM3MDKMKnh6+V9L08331ipq6Q8OFXZYiqP6n/tbHx4s5I9uRhcye6BrbkizkBDw==",
"peer": true,
"dependencies": {
"call-bind": "^1.0.2",
"has-bigints": "^1.0.2",
@ -14720,6 +14788,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.0.2.tgz",
"integrity": "sha512-bwZdv0AKLpplFY2KZRX6TvyuN7ojjr7lwkg6ml0roIy9YeuSr7JS372qlNW18UQYzgYK9ziGcerWqZOmEn9VNg==",
"peer": true,
"dependencies": {
"is-bigint": "^1.0.1",
"is-boolean-object": "^1.1.0",
@ -14735,6 +14804,7 @@
"version": "1.1.15",
"resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.15.tgz",
"integrity": "sha512-oV0jmFtUky6CXfkqehVvBP/LSWJ2sy4vWMioiENyJLePrBO/yKyV9OyJySfAKosh+RYkIl5zJCNZ8/4JncrpdA==",
"peer": true,
"dependencies": {
"available-typed-arrays": "^1.0.7",
"call-bind": "^1.0.7",

View file

@ -32,7 +32,6 @@
"cross-env": "^7.0.3",
"esbuild": "0.17.19",
"eslint": "^8",
"eslint-plugin-import": "^2.29.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"myers-diff": "^2.1.0",
@ -49,7 +48,6 @@
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@typescript-eslint/parser": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",

View file

@ -15,7 +15,12 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
},
];
openUrl: [string, void];
applyToCurrentFile: [{ text: string; streamId: string }, void];
// We pass the `curSelectedModel` because we currently cannot access the
// default model title in the GUI from JB
applyToCurrentFile: [
{ text: string; streamId: string; curSelectedModelTitle: string },
void,
];
showTutorial: [undefined, void];
showFile: [{ filepath: string }, void];
openConfigJson: [undefined, void];
@ -66,6 +71,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
* @deprecated Use navigateTo with a path instead.
*/
viewHistory: [undefined, void];
focusContinueSessionId: [{ sessionId: string | undefined }, void];
newSession: [undefined, void];
setTheme: [{ theme: any }, void];
setColors: [{ [key: string]: string }, void];

View file

@ -1,6 +1,6 @@
import fs from "node:fs";
import { getGlobalContextFilePath } from "./paths";
import { EmbeddingsProvider } from "../";
import { getGlobalContextFilePath } from "./paths";
export type GlobalContextType = {
indexingPaused: boolean;
@ -37,7 +37,15 @@ export class GlobalContext {
);
} else {
const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8");
const parsed = JSON.parse(data);
let parsed;
try {
parsed = JSON.parse(data);
} catch (e: any) {
console.warn(`Error updating global context: ${e}`);
return;
}
parsed[key] = value;
fs.writeFileSync(
getGlobalContextFilePath(),
@ -54,7 +62,12 @@ export class GlobalContext {
}
const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8");
const parsed = JSON.parse(data);
return parsed[key];
try {
const parsed = JSON.parse(data);
return parsed[key];
} catch (e: any) {
console.warn(`Error parsing global context: ${e}`);
return undefined;
}
}
}

View file

@ -38,7 +38,7 @@ class FileSystemIde implements IDE {
throw new Error("Method not implemented.");
}
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void {
throw new Error("Method not implemented.");
return;
}
async getIdeSettings(): Promise<IdeSettings> {

View file

@ -12,9 +12,6 @@ export interface RepoMapOptions {
}
class RepoMapGenerator {
private llm: ILLM;
private ide: IDE;
private options: RepoMapOptions;
private maxRepoMapTokens: number;
private repoMapPath: string = getRepoMapFilePath();
@ -32,10 +29,11 @@ class RepoMapGenerator {
"this map contains the name of the file, and the signature for any " +
"classes, methods, or functions in the file.\n\n";
constructor(llm: ILLM, ide: IDE, options: RepoMapOptions) {
this.llm = llm;
this.ide = ide;
this.options = options;
constructor(
private llm: ILLM,
private ide: IDE,
private options: RepoMapOptions,
) {
this.maxRepoMapTokens =
llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO;
}

View file

@ -3,6 +3,18 @@ import { PersistedSessionInfo, SessionInfo } from "../index.js";
import { ListHistoryOptions } from "../protocol/core.js";
import { getSessionFilePath, getSessionsListPath } from "./paths.js";
function safeParseArray<T>(
value: string,
errorMessage: string = "Error parsing array",
): T[] | undefined {
try {
return JSON.parse(value) as T[];
} catch (e: any) {
console.warn(`${errorMessage}: ${e}`);
return undefined;
}
}
class HistoryManager {
list(options: ListHistoryOptions): SessionInfo[] {
const filepath = getSessionsListPath();
@ -10,7 +22,9 @@ class HistoryManager {
return [];
}
const content = fs.readFileSync(filepath, "utf8");
let sessions = JSON.parse(content).filter((session: any) => {
let sessions = safeParseArray<SessionInfo>(content) ?? [];
sessions = sessions.filter((session: any) => {
// Filter out old format
return typeof session.session_id !== "string";
});
@ -35,14 +49,11 @@ class HistoryManager {
// Read and update the sessions list
const sessionsListFile = getSessionsListPath();
const sessionsListRaw = fs.readFileSync(sessionsListFile, "utf-8");
let sessionsList: SessionInfo[];
try {
sessionsList = JSON.parse(sessionsListRaw);
} catch (error) {
throw new Error(
`It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFile}). Please fix this before creating a new session.`,
);
}
let sessionsList =
safeParseArray<SessionInfo>(
sessionsListRaw,
"Error parsing sessions.json",
) ?? [];
sessionsList = sessionsList.filter(
(session) => session.sessionId !== sessionId,

View file

@ -21,6 +21,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
disableInFiles: undefined,
useImports: true,
useRootPathContext: true,
transform: true,
};
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;

View file

@ -3,9 +3,9 @@ import dotenv from "dotenv";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { IdeType, SerializedContinueConfig } from "../";
import { defaultConfig, defaultConfigJetBrains } from "../config/default";
import Types from "../config/types";
import { IdeType, SerializedContinueConfig } from "../";
dotenv.config();
@ -348,3 +348,18 @@ export function getRepoMapFilePath(): string {
export function getEsbuildBinaryPath(): string {
return path.join(getContinueUtilsPath(), "esbuild");
}
export function setupInitialDotContinueDirectory() {
const devDataTypes = [
"chat",
"autocomplete",
"quickEdit",
"tokens_generated",
];
devDataTypes.forEach((p) => {
const devDataPath = getDevDataFilePath(p);
if (!fs.existsSync(devDataPath)) {
fs.writeFileSync(devDataPath, "");
}
});
}

View file

@ -13,22 +13,34 @@ export class Telemetry {
event: string,
properties: { [key: string]: any },
sendToTeam: boolean = false,
isExtensionActivationError: boolean = false,
) {
if (process.env.NODE_ENV === "test") {
return;
}
try {
Telemetry.client?.capture({
const augmentedProperties = {
...properties,
os: Telemetry.os,
extensionVersion: Telemetry.ideInfo?.extensionVersion,
ideName: Telemetry.ideInfo?.name,
ideType: Telemetry.ideInfo?.ideType,
};
const payload = {
distinctId: Telemetry.uniqueId,
event,
properties: {
...properties,
os: Telemetry.os,
extensionVersion: Telemetry.ideInfo?.extensionVersion,
ideName: Telemetry.ideInfo?.name,
ideType: Telemetry.ideInfo?.ideType,
},
});
properties: augmentedProperties,
};
// In cases where an extremely early fatal error occurs, we may not have initialized yet
if (isExtensionActivationError && !Telemetry.client) {
const client = await Telemetry.getTelemetryClient();
client?.capture(payload);
return;
}
if (process.env.NODE_ENV === "test") {
return;
}
Telemetry.client?.capture(payload);
if (sendToTeam) {
void TeamAnalytics.capture(event, properties);
@ -42,6 +54,17 @@ export class Telemetry {
Telemetry.client?.shutdown();
}
static async getTelemetryClient() {
try {
const { PostHog } = await import("posthog-node");
return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", {
host: "https://app.posthog.com",
});
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
}
static async setup(allow: boolean, uniqueId: string, ideInfo: IdeInfo) {
Telemetry.uniqueId = uniqueId;
Telemetry.os = os.platform();
@ -49,20 +72,8 @@ export class Telemetry {
if (!allow || process.env.NODE_ENV === "test") {
Telemetry.client = undefined;
} else {
try {
if (!Telemetry.client) {
const { PostHog } = await import("posthog-node");
Telemetry.client = new PostHog(
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
{
host: "https://app.posthog.com",
},
);
}
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
} else if (!Telemetry.client) {
Telemetry.client = await Telemetry.getTelemetryClient();
}
}
}

View file

@ -7,7 +7,7 @@ sidebar_position: 5
## Built-in slash commands
Continue has a large library of built-in slash commands, but when you first install we only display the most commonly used ones, like “/edit”, “/comment”, and “/share”. To add more actions, you can open [config.json](../customize/config.mdx) and add them to the `slashCommands` array.
Continue has a large library of built-in slash commands, but when you first install we only display the most commonly used ones, like “/edit”, “/comment”, and “/share”. To add more actions, you can open [config.json](../reference.md) and add them to the `slashCommands` array.
## Custom slash commands
@ -20,7 +20,7 @@ There are two ways to add custom slash commands:
<!-- TODO: We need a config.ts reference -->
<!-- :::tip[config.ts]
Before adding a custom slash command, we recommend reading the [introduction to `config.ts`](../customize/config.mdx).
Before adding a custom slash command, we recommend reading the [introduction to `config.ts`](../customize/deep-dives/ways-to-configure.md).
::: -->
If you want to go a step further than writing custom commands with natural language, you can write a custom function that returns the response. This requires using `config.ts` instead of `config.json`.

View file

@ -14,7 +14,7 @@ Actions are shortcuts for common use cases. For example, you might want to revie
### Slash commands
The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor.
The most common way to invoke an action is with a slash command. These are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. For example, the built-in '/edit' slash command lets you stream edits directly into your editor.
![slash-commands](/img/slash-commands.png)

View file

@ -5,7 +5,7 @@ keywords: [customize]
sidebar_position: 5
---
Continue offers a handful of parameters in [`config.json`](../customize/config.mdx) that can be tuned to find the perfect balance between suggestion quality and system performance for your specific needs and hardware capabilities:
Continue offers a handful of parameters in [`config.json`](../reference.md) that can be tuned to find the perfect balance between suggestion quality and system performance for your specific needs and hardware capabilities:
```json title="config.json"
"tabAutocompleteOptions": {

View file

@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
:::info
This page recommends models and providers for Chat. Read more about how to set up your `config.json` [here](../customize/config.mdx).
This page recommends models and providers for Chat. Read more about how to set up your `config.json` [here](../reference.md).
:::
## Best overall experience

View file

@ -1,22 +0,0 @@
---
title: config.json Reference
keywords: [config.json, configuration, options]
---
import Schema from "@site/static/schemas/config.json";
import JSONSchemaViewer from "@theme/JSONSchemaViewer";
# Configuration options
The following shows the JSON Schema definition for `config.json`.
You can also define a partial `config.json` object in a file called `.continuerc.json` at the root of your workspace. This will be applied on top of any configuration from `config.json`.
<JSONSchemaViewer
schema={Schema}
resolverOptions={{
jsonPointer: "#/definitions/SerializedContinueConfig",
}}
/>
[View the source](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json)

View file

@ -44,7 +44,7 @@ All of the configuration options available for chat models are available to use
}
```
If you aren't yet familiar with the available options, you can find the full reference [here](../config.mdx).
If you aren't yet familiar with the available options, you can find the full reference [here](./ways-to-configure.md).
## Configuration Options

View file

@ -5,7 +5,11 @@ keywords: [talk, embeddings, reranker, codebase, experimental]
# @Codebase
Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally with `all-MiniLM-L6-v2` and stored locally in `~/.continue/index`.
Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally using `transformers.js` and stored locally in `~/.continue/index`.
:::info[`transformers.js cannot be used in JetBrains`]
Currently, `transformers.js` cannot be used in JetBrains IDEs. However, you can select a differet embeddings model from [the list here](../model-types/embeddings.md).
:::
Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@Codebase` or `@Folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files.
@ -34,7 +38,7 @@ Here are use cases where it is not useful:
## Configuration
There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`, and are the same for the codebase and folder context providers:
There are a few options that let you configure the behavior of the codebase context provider. These can be set in `config.json`, and are the same for the codebase, docs, and folder context providers:
```json title="config.json"
{
@ -67,10 +71,12 @@ Whether to use re-ranking, which will allow initial selection of `nRetrieve` res
Continue respects `.gitignore` files in order to determine which files should not be indexed. If you'd like to exclude additional files, you can add them to a `.continueignore` file, which follows the exact same rules as `.gitignore`.
Continue also supports a **global** `.continueignore` file that will be respected for all workspaces, which can be created at `~/.continue/.continueignore`.
If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file.
If you need to force a refresh of the index, reload the VS Code window with `cmd/ctrl + shift + p` + "Reload Window".
## Repository map
Models in the Claude 3, Llama 3.1, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.
Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.

View file

@ -69,6 +69,25 @@ The [configuration schema for docs](https://github.com/continuedev/continue/blob
- `rootUrl`: The base URL of the documentation site, used to determine which pages to index.
- `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI.
## Configuration
As with [@Codebase context provider configuration](https://docs.continue.dev/customize/deep-dives/codebase#configuration), you can adjust the behavior of the docs context provider with the `nRetrieve`, `nFinal`, and `useReranking`
```json title="config.json"
{
"contextProviders": [
{
"name": "docs",
"params": {
"nRetrieve": 25,
"nFinal": 5,
"useReranking": true
}
}
]
}
```
## Crawling dynamically generated sites with `useChromiumForDocsCrawling`
By default, we use a lighter weight tool to crawl documentation sites that cannot render sites that are dynamically generated using JavaScript.

View file

@ -0,0 +1,68 @@
---
description: Ways to configure
keywords: [config, settings, customize]
---
# Ways to configure
Continue can be deeply customized. User-level configuration is stored and can be edited in your home directory in [`config.json`](#configjson):
- `~/.continue/config.json` (MacOS / Linux)
- `%USERPROFILE%\.continue\config.json` (Windows)
To open `config.json`, you can click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can see the available options suggested as you type, or check the reference below.
When you save `config.json`, Continue will automatically refresh to take into account your changes. `config.json` is automatically created the first time you use Continue. `config.json` is automatically generated if it doesn't exist.
In the vast majority of cases, you will only need to edit `config.json`. However, Continue offers two additional ways to customize configuration:
- [`.continuerc.json`](#continuercjson) - Workspace-level configuration. If you'd like to scope certain settings to a particular workspace, you can add a `.continuerc.json` to the root of your project. This can be set to merge with _or_ override the user-level `config.json`
- [`config.ts`](#configts) - Advanced configuration (probably unnecessary) - a TypeScript file in your home directory that can be used to programmatically modify (_merged_) the `config.json` schema:
- `~/.continue/config.ts` (MacOS / Linux)
- `%USERPROFILE%\.continue\config.ts` (Windows)
## `config.json`
See the full reference for `config.json` [here](../../reference.md).
## `.continuerc.json`
The format of `.continuerc.json` is the same as `config.json`, plus one _additional_ property `mergeBehavior`, which can be set to either "merge" or "overwrite". If set to "merge" (the default), `.continuerc.json` will be applied on top of `config.json` (arrays and objects are merged). If set to "overwrite", then every top-level property of `.continuerc.json` will overwrite that property from `config.json`.
Example
```json title="config.json"
{
"tabAutocompleteOptions": {
"disable": true
},
"mergeBehavior": "overwrite"
}
```
## `config.ts`
To programatically extend `config.json`, you can place a `config.ts` script in same directory as `config.json` and export a `modifyConfig` function, like:
```ts title="config.ts"
export function modifyConfig(config: Config): Config {
config.slashCommands?.push({
name: "commit",
description: "Write a commit message",
run: async function* (sdk) {
const diff = await sdk.ide.getDiff();
for await (const message of sdk.llm.streamComplete(
`${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`,
{
maxTokens: 20,
},
)) {
yield message;
}
},
});
return config;
}
```
This can be used for slash commands and custom context providers.

View file

@ -1,79 +0,0 @@
---
title: Anthropic Vertex AI
slug: ../anthropic-vertexai
---
:::info
You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).
:::
## Chat model
We recommend configuring **Claude 3.5 Sonnet** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "Claude 3.5 Sonnet",
"provider": "anthropic-vertexai",
"model": "claude-3-5-sonnet-20240620",
"projectId": "[PROJECT_ID]",
"region": "us-east5"
}
]
}
```
## Autocomplete model
Anthropic Vertex AI currently does not offer any autocomplete models.
[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers.
## Embeddings model
We recommend configuring **text-embedding-004** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": {
"provider": "vertex",
"model": "text-embedding-004",
"projectId": "[PROJECT_ID]",
"region": "us-central1"
}
}
```
## Reranking model
Anthropic Vertex AI currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
## Prompt caching
Anthropic Vertex AI supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching).
To enable caching of the system message and the turn-by-turn conversation, update your your model configuration as following:
```jsonc
{
"models": [
{
// Enable prompt caching
"cacheBehavior": {
"cacheSystemMessage": true,
"cacheConversation": true
},
"title": "Anthropic",
"provider": "anthropic",
"model": "claude-3-5-sonnet-20240620",
"apiKey": "[API_KEY]"
}
]
}
```

View file

@ -0,0 +1,61 @@
# Ask Sage
:::info
To get an Ask Sage API key login to the Ask Sage platform (If you don't have an account, you can create one [here](https://chat.asksage.ai/)) and follow the instructions in the Ask Sage Docs:[Ask Sage API Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html)
:::
## Configuration
To use the Ask Sage models, the following configuration is required to the `config.json` file:
```json
{
"models": [
{
"apiKey": "YOUR_API_KEY",
"apiBase": "https://api.asksage.ai/server/", // apiBase will be the same for all models, but will vary based on tenant.
"model": "gpt4-gov",
"title": "GPT-4 gov",
"provider": "askSage"
}
]
}
```
The `apiBase` will be listed on the Ask Sage platform when you generate an `API key`. You will see context as shown below:
> Server API for query/training etc.:
> - Documentation: https://app.swaggerhub.com/apis-docs/NICOLASCHAILLAN_1/server_ask-sage_api/1.0
> - URL for this API is: https://api.asksage.ai/server/
## Usage
Currently, the setup for the models provided by Ask Sage is to support the following two functionalities provided by Continue.Dev:
- `Chat` to understand and iterate on code in the sidebar
- `Edit` to modify code without leaving your current file
More models, functionalities and documentation will be added in the future for Ask Sage Integration.
> We recommend to utilize the`OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities.
## Current Models From Ask Sage Supported
The current Models available provided by Ask Sage are:
| Model | Added |
|--------------------|-------|
| Gov GPT-4.0 | Yes |
| Gov GPT-4o | Yes |
| GPT-4o | Yes |
| GPT-4o-mini | Yes |
| GPT-3.5-16K | Yes |
| Calude 3 Opus | Yes |
| Calude 3 Sonet | Yes |
| Calude 3.5 Sonnet | Yes |
| Gemini Pro | Yes |
| llama 3 | Yes |
| Mistral Large | Yes |

View file

@ -1,6 +1,6 @@
# Cerebras Inference
Cerebras Inference uses specialized silicon to provides fast inference for the Llama3.1 8B and Llama3.1 70B models.
Cerebras Inference uses specialized silicon to provides fast inference.
1. Create an account in the portal [here](https://cloud.cerebras.ai/).
2. Create and copy the API key for use in Continue.

Some files were not shown because too many files have changed in this diff Show more