Merge branch 'main' into test-file-codeblock
This commit is contained in:
commit
190feed9dc
184 changed files with 15987 additions and 1078 deletions
6
.continue/rules/typescript-enum-usage.md
Normal file
6
.continue/rules/typescript-enum-usage.md
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
---
|
||||
globs: "**/*.{ts,tsx}"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
Use enums instead of simple string unions when possible in TypeScript code
|
||||
4
.github/pull_request_template.md
vendored
4
.github/pull_request_template.md
vendored
|
|
@ -8,9 +8,9 @@
|
|||
- [] The relevant docs, if any, have been updated or created
|
||||
- [] The relevant tests, if any, have been updated or created
|
||||
|
||||
## Screenshots
|
||||
## Screen recording or screenshot
|
||||
|
||||
[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ]
|
||||
[ When applicable, please include a short screen recording or screenshot - this makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example. ]
|
||||
|
||||
## Tests
|
||||
|
||||
|
|
|
|||
41
.github/workflows/pr_checks.yaml
vendored
41
.github/workflows/pr_checks.yaml
vendored
|
|
@ -572,6 +572,43 @@ jobs:
|
|||
cd packages/config-yaml
|
||||
npm test
|
||||
|
||||
openai-adapters-tests:
|
||||
needs: install-openai-adapters
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules
|
||||
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Run openai-adapters tests
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm test
|
||||
env:
|
||||
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
|
||||
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
|
||||
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
|
||||
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
|
||||
|
||||
vscode-get-test-file-matrix:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [install-root, install-vscode, install-config-yaml]
|
||||
|
|
@ -613,6 +650,9 @@ jobs:
|
|||
echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$FILES" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
|
||||
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
|
||||
|
||||
- name: Debug Outputs
|
||||
run: |
|
||||
|
|
@ -1068,6 +1108,7 @@ jobs:
|
|||
- config-yaml-checks
|
||||
- install-config-yaml
|
||||
- install-openai-adapters
|
||||
- openai-adapters-tests
|
||||
|
||||
steps:
|
||||
- name: Decide whether the needed jobs succeeded or failed
|
||||
|
|
|
|||
16
.github/workflows/release-config-yaml.yml
vendored
16
.github/workflows/release-config-yaml.yml
vendored
|
|
@ -6,6 +6,13 @@ on:
|
|||
- main
|
||||
paths:
|
||||
- "packages/config-yaml/**"
|
||||
- ".github/workflows/release-config-yaml.yml"
|
||||
- ".github/workflows/reusable-release.yml"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
|
|
@ -16,3 +23,12 @@ jobs:
|
|||
secrets:
|
||||
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
|
||||
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
|
||||
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
|
||||
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
|
||||
|
|
|
|||
16
.github/workflows/release-fetch.yml
vendored
16
.github/workflows/release-fetch.yml
vendored
|
|
@ -6,6 +6,13 @@ on:
|
|||
- main
|
||||
paths:
|
||||
- "packages/fetch/**"
|
||||
- ".github/workflows/release-fetch.yml"
|
||||
- ".github/workflows/reusable-release.yml"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
|
|
@ -16,3 +23,12 @@ jobs:
|
|||
secrets:
|
||||
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
|
||||
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
|
||||
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
|
||||
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
|
||||
|
|
|
|||
8
.github/workflows/release-llm-info.yml
vendored
8
.github/workflows/release-llm-info.yml
vendored
|
|
@ -16,3 +16,11 @@ jobs:
|
|||
secrets:
|
||||
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
|
||||
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
|
||||
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
|
||||
16
.github/workflows/release-openai-adapters.yml
vendored
16
.github/workflows/release-openai-adapters.yml
vendored
|
|
@ -6,6 +6,13 @@ on:
|
|||
- main
|
||||
paths:
|
||||
- "packages/openai-adapters/**"
|
||||
- ".github/workflows/release-openai-adapters.yml"
|
||||
- ".github/workflows/reusable-release.yml"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
|
|
@ -16,3 +23,12 @@ jobs:
|
|||
secrets:
|
||||
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
|
||||
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
|
||||
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
|
||||
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
|
||||
|
|
|
|||
30
.github/workflows/reusable-release.yml
vendored
30
.github/workflows/reusable-release.yml
vendored
|
|
@ -14,6 +14,24 @@ on:
|
|||
required: true
|
||||
SEMANTIC_RELEASE_NPM_TOKEN:
|
||||
required: true
|
||||
OPENAI_API_KEY:
|
||||
required: false
|
||||
ANTHROPIC_API_KEY:
|
||||
required: false
|
||||
GEMINI_API_KEY:
|
||||
required: false
|
||||
MISTRAL_API_KEY:
|
||||
required: false
|
||||
AZURE_OPENAI_API_KEY:
|
||||
required: false
|
||||
AZURE_FOUNDRY_CODESTRAL_API_KEY:
|
||||
required: false
|
||||
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY:
|
||||
required: false
|
||||
AZURE_OPENAI_GPT41_API_KEY:
|
||||
required: false
|
||||
VOYAGE_API_KEY:
|
||||
required: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
|
@ -46,10 +64,20 @@ jobs:
|
|||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
env:
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
|
||||
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
|
||||
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
|
||||
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
|
||||
|
||||
- name: Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
run: npx semantic-release
|
||||
run: npx semantic-release
|
||||
|
|
|
|||
|
|
@ -192,6 +192,7 @@ To keep the Continue codebase clean and maintainable, we expect the following fr
|
|||
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
|
||||
- Write or update tests for new functionality
|
||||
- Update relevant documentation in the `docs` folder
|
||||
- **For new features**: Include a short screen recording or screenshot demonstrating the new functionality. This makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example
|
||||
- Open a PR against the `main` branch. Make sure to fill in the PR template
|
||||
|
||||
### Formatting
|
||||
|
|
|
|||
|
|
@ -19,5 +19,13 @@
|
|||
"max-depth": ["error", { "max": 6 }],
|
||||
"max-nested-callbacks": ["error", { "max": 4 }],
|
||||
"max-params": ["error", { "max": 8 }]
|
||||
}
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["**/*.vitest.ts"],
|
||||
"rules": {
|
||||
"max-lines-per-function": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
|
|||
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
|
||||
import { postprocessCompletion } from "./postprocessing/index.js";
|
||||
import { shouldPrefilter } from "./prefiltering/index.js";
|
||||
import { getAllSnippets } from "./snippets/index.js";
|
||||
import { getAllSnippetsWithoutRace } from "./snippets/index.js";
|
||||
import { renderPrompt } from "./templating/index.js";
|
||||
import { GetLspDefinitionsFunction } from "./types.js";
|
||||
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
|
||||
|
|
@ -121,6 +121,12 @@ export class CompletionProvider {
|
|||
...config?.tabAutocompleteOptions,
|
||||
...llm.autocompleteOptions,
|
||||
};
|
||||
|
||||
// Enable static contextualization if defined.
|
||||
if (config?.experimental?.enableStaticContextualization) {
|
||||
options.experimental_enableStaticContextualization = true;
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
|
|
@ -171,7 +177,7 @@ export class CompletionProvider {
|
|||
}
|
||||
|
||||
const [snippetPayload, workspaceDirs] = await Promise.all([
|
||||
getAllSnippets({
|
||||
getAllSnippetsWithoutRace({
|
||||
helper,
|
||||
ide: this.ide,
|
||||
getDefinitionsFromLsp: this.getDefinitionsFromLsp,
|
||||
|
|
@ -258,6 +264,10 @@ export class CompletionProvider {
|
|||
...helper.options,
|
||||
};
|
||||
|
||||
if (options.experimental_enableStaticContextualization) {
|
||||
outcome.enabledStaticContextualization = true;
|
||||
}
|
||||
|
||||
//////////
|
||||
|
||||
// Save to cache
|
||||
|
|
|
|||
|
|
@ -2,16 +2,19 @@ import { IDE } from "../..";
|
|||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippetType,
|
||||
AutocompleteStaticSnippet,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
import { ImportDefinitionsService } from "./ImportDefinitionsService";
|
||||
import { getSymbolsForSnippet } from "./ranking";
|
||||
import { RootPathContextService } from "./root-path-context/RootPathContextService";
|
||||
import { StaticContextService } from "./static-context/StaticContextService";
|
||||
|
||||
export class ContextRetrievalService {
|
||||
private importDefinitionsService: ImportDefinitionsService;
|
||||
private rootPathContextService: RootPathContextService;
|
||||
private staticContextService: StaticContextService;
|
||||
|
||||
constructor(private readonly ide: IDE) {
|
||||
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
|
||||
|
|
@ -19,6 +22,7 @@ export class ContextRetrievalService {
|
|||
this.importDefinitionsService,
|
||||
this.ide,
|
||||
);
|
||||
this.staticContextService = new StaticContextService(this.ide);
|
||||
}
|
||||
|
||||
public async getSnippetsFromImportDefinitions(
|
||||
|
|
@ -71,6 +75,12 @@ export class ContextRetrievalService {
|
|||
);
|
||||
}
|
||||
|
||||
public async getStaticContextSnippets(
|
||||
helper: HelperVars,
|
||||
): Promise<AutocompleteStaticSnippet[]> {
|
||||
return this.staticContextService.getContext(helper);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the import definitions cache for a file.
|
||||
* This is normally done automatically when the active text editor changes,
|
||||
|
|
|
|||
888
core/autocomplete/context/static-context/StaticContextService.ts
Normal file
888
core/autocomplete/context/static-context/StaticContextService.ts
Normal file
|
|
@ -0,0 +1,888 @@
|
|||
import * as fs from "fs/promises";
|
||||
import path from "path";
|
||||
import { pathToFileURL } from "url";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { IDE, Position } from "../../..";
|
||||
import { localPathOrUriToPath } from "../../../util/pathToUri";
|
||||
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
|
||||
import {
|
||||
AutocompleteSnippetType,
|
||||
AutocompleteStaticSnippet,
|
||||
} from "../../snippets/types";
|
||||
import { getAst } from "../../util/ast";
|
||||
import { HelperVars } from "../../util/HelperVars";
|
||||
import {
|
||||
extractFunctionTypeFromDecl,
|
||||
extractTopLevelDecls,
|
||||
findEnclosingTypeDeclaration,
|
||||
unwrapToBaseType,
|
||||
} from "./tree-sitter-utils";
|
||||
import {
|
||||
HoleContext,
|
||||
RelevantHeaders,
|
||||
RelevantTypes,
|
||||
StaticContext,
|
||||
TypeSpanAndSourceFile,
|
||||
TypeSpanAndSourceFileAndAst,
|
||||
} from "./types";
|
||||
|
||||
export class StaticContextService {
|
||||
private readonly ide: IDE;
|
||||
|
||||
constructor(ide: IDE) {
|
||||
this.ide = ide;
|
||||
}
|
||||
|
||||
public logAutocompleteStaticSnippet(
|
||||
ctx: StaticContext,
|
||||
label = "Static Snippet",
|
||||
) {
|
||||
console.log(`=== ${label} ===`);
|
||||
console.log("Hole Type:", ctx.holeType);
|
||||
|
||||
console.log(`\nRelevant Types (${ctx.relevantTypes.size} files):`);
|
||||
ctx.relevantTypes.forEach((types, filepath) => {
|
||||
console.log(` 📁 ${filepath}`);
|
||||
types.forEach((type) => console.log(` • ${type}`));
|
||||
});
|
||||
|
||||
console.log(`\nRelevant Headers (${ctx.relevantHeaders.size} files):`);
|
||||
ctx.relevantHeaders.forEach((headers, filepath) => {
|
||||
console.log(` 📁 ${filepath}`);
|
||||
headers.forEach((header) => console.log(` • ${header}`));
|
||||
});
|
||||
}
|
||||
|
||||
public static formatAutocompleteStaticSnippet(ctx: StaticContext): string {
|
||||
let output = `AutocompleteStaticSnippet:\n`;
|
||||
output += ` holeType: ${ctx.holeType}\n`;
|
||||
|
||||
output += ` relevantTypes:\n`;
|
||||
if (ctx.relevantTypes.size === 0) {
|
||||
output += ` (none)\n`;
|
||||
} else {
|
||||
ctx.relevantTypes.forEach((types, filepath) => {
|
||||
output += ` ${filepath}: [${types.join(", ")}]\n`;
|
||||
});
|
||||
}
|
||||
|
||||
output += ` relevantHeaders:\n`;
|
||||
if (ctx.relevantHeaders.size === 0) {
|
||||
output += ` (none)\n`;
|
||||
} else {
|
||||
ctx.relevantHeaders.forEach((headers, filepath) => {
|
||||
output += ` ${filepath}: [${headers.join(", ")}]\n`;
|
||||
});
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
public async getContext(
|
||||
helper: HelperVars,
|
||||
): Promise<AutocompleteStaticSnippet[]> {
|
||||
const start = Date.now();
|
||||
const tsFiles = await this.getTypeScriptFilesFromWorkspaces(
|
||||
helper.workspaceUris,
|
||||
);
|
||||
// Get the three contexts holeContext, relevantTypes, relevantHeaders.
|
||||
const holeContext = await this.getHoleContext(
|
||||
helper.fileContents,
|
||||
helper.filepath,
|
||||
helper.pos,
|
||||
);
|
||||
|
||||
const relevantTypes = await this.extractRelevantTypes(
|
||||
holeContext.fullHoverResult,
|
||||
holeContext.functionName,
|
||||
holeContext.range.start.line,
|
||||
holeContext.source,
|
||||
new Map<string, string>(),
|
||||
);
|
||||
|
||||
// if (this.language === "typescript") {
|
||||
// repo = getAllTSFiles(this.repoPath);
|
||||
// } else if (this.language === "ocaml") {
|
||||
// repo = getAllOCamlFiles(this.repoPath);
|
||||
// }
|
||||
//
|
||||
|
||||
const relevantHeaders = await this.extractRelevantHeaders(
|
||||
tsFiles,
|
||||
relevantTypes,
|
||||
holeContext.functionTypeSpan,
|
||||
helper.pos,
|
||||
holeContext.returnTypeIsAny,
|
||||
);
|
||||
|
||||
const relevantTypesToReturn: Map<string, string[]> = new Map<
|
||||
string,
|
||||
string[]
|
||||
>();
|
||||
relevantTypes.forEach(({ typeSpan: v, sourceFile: src }, _) => {
|
||||
if (relevantTypesToReturn.has(src)) {
|
||||
const updated = relevantTypesToReturn.get(src)!;
|
||||
updated.push(v);
|
||||
relevantTypesToReturn.set(src, updated);
|
||||
} else {
|
||||
relevantTypesToReturn.set(src, [v]);
|
||||
}
|
||||
});
|
||||
|
||||
const relevantHeadersToReturn: Map<string, string[]> = new Map<
|
||||
string,
|
||||
string[]
|
||||
>();
|
||||
relevantHeaders.forEach(({ typeSpan: v, sourceFile: src }) => {
|
||||
if (relevantHeadersToReturn.has(src)) {
|
||||
const updated = relevantHeadersToReturn.get(src)!;
|
||||
if (!updated.includes(v)) {
|
||||
updated.push(v);
|
||||
}
|
||||
relevantHeadersToReturn.set(src, updated);
|
||||
} else {
|
||||
relevantHeadersToReturn.set(src, [v]);
|
||||
}
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
holeType: holeContext.functionTypeSpan,
|
||||
relevantTypes: relevantTypesToReturn,
|
||||
relevantHeaders: relevantHeadersToReturn,
|
||||
};
|
||||
const end = Date.now();
|
||||
|
||||
this.logAutocompleteStaticSnippet(ctx);
|
||||
|
||||
// console.log(end - start);
|
||||
|
||||
const snippets: AutocompleteStaticSnippet[] = [];
|
||||
|
||||
snippets.push({
|
||||
type: AutocompleteSnippetType.Static,
|
||||
filepath: pathToFileURL(path.resolve(holeContext.source)).toString(),
|
||||
content: holeContext.fullHoverResult,
|
||||
});
|
||||
|
||||
for (const [filepath, typs] of ctx.relevantTypes.entries()) {
|
||||
snippets.push({
|
||||
type: AutocompleteSnippetType.Static,
|
||||
filepath: pathToFileURL(path.resolve(filepath)).toString(),
|
||||
content: typs.join("\n"),
|
||||
});
|
||||
}
|
||||
|
||||
for (const [filepath, headers] of ctx.relevantHeaders.entries()) {
|
||||
snippets.push({
|
||||
type: AutocompleteSnippetType.Static,
|
||||
filepath: pathToFileURL(path.resolve(filepath)).toString(),
|
||||
content: headers.join("\n"),
|
||||
});
|
||||
}
|
||||
|
||||
return snippets;
|
||||
}
|
||||
|
||||
private async getHoleContext(
|
||||
sketchFileContent: string,
|
||||
sketchFilePath: string,
|
||||
cursorPosition: Position,
|
||||
): Promise<HoleContext> {
|
||||
// We need to inject the hole @ to trigger a treesitter error node.
|
||||
sketchFilePath = localPathOrUriToPath(sketchFilePath);
|
||||
// const sketchFileContent = await fs.readFile(sketchFilePath, "utf8");
|
||||
const injectedContent = this.insertAtPosition(
|
||||
sketchFileContent,
|
||||
cursorPosition,
|
||||
"@;",
|
||||
);
|
||||
|
||||
// The hole's position is cursorPosition.
|
||||
|
||||
// Use treesitter to parse.
|
||||
const ast = await getAst(sketchFilePath, injectedContent);
|
||||
if (!ast) {
|
||||
throw new Error("failed to get ast");
|
||||
}
|
||||
const language = getFullLanguageName(sketchFilePath);
|
||||
const query = await getQueryForFile(
|
||||
sketchFilePath,
|
||||
`static-context-queries/hole-queries/${language}.scm`,
|
||||
);
|
||||
if (!query) {
|
||||
throw new Error(
|
||||
`getHoleContext: failed to get query for file ${sketchFilePath} and language ${language}`,
|
||||
);
|
||||
}
|
||||
|
||||
const captures = query.captures(ast.rootNode);
|
||||
const res: HoleContext = {
|
||||
fullHoverResult: "",
|
||||
functionName: "",
|
||||
functionTypeSpan: "",
|
||||
returnTypeIsAny: false,
|
||||
range: {
|
||||
start: { line: 0, character: 0 },
|
||||
end: { line: 0, character: 0 },
|
||||
},
|
||||
source: `file://${sketchFilePath}`,
|
||||
};
|
||||
let paramsTypes = "";
|
||||
for (const c of captures) {
|
||||
const { name, node } = c;
|
||||
// console.log(`${name} →`, node.text, node.startPosition, node.endPosition);
|
||||
|
||||
switch (name) {
|
||||
case "function.decl": {
|
||||
res.fullHoverResult = node.text;
|
||||
break;
|
||||
}
|
||||
case "function.name": {
|
||||
res.functionName = node.text;
|
||||
break;
|
||||
}
|
||||
case "function.params": {
|
||||
paramsTypes = node.text;
|
||||
res.range = {
|
||||
start: {
|
||||
line: node.startPosition.row,
|
||||
character: node.startPosition.column,
|
||||
},
|
||||
end: {
|
||||
line: node.endPosition.row,
|
||||
character: node.endPosition.column,
|
||||
},
|
||||
};
|
||||
break;
|
||||
}
|
||||
case "function.type": {
|
||||
res.functionTypeSpan = node.text;
|
||||
res.range = {
|
||||
start: {
|
||||
line: node.startPosition.row,
|
||||
character: node.startPosition.column,
|
||||
},
|
||||
end: {
|
||||
line: node.endPosition.row,
|
||||
character: node.endPosition.column,
|
||||
},
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (res.functionTypeSpan === "") {
|
||||
res.functionTypeSpan = `${paramsTypes} => any`;
|
||||
res.returnTypeIsAny = true;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
private async extractRelevantTypes(
|
||||
declText: string,
|
||||
typeName: string,
|
||||
startLine: number,
|
||||
currentFile: string,
|
||||
foundContents: Map<string, string>, // uri -> contents
|
||||
): Promise<RelevantTypes> {
|
||||
const foundSoFar = new Map<string, TypeSpanAndSourceFileAndAst>(); // identifier -> [full hover result, source]
|
||||
|
||||
await this.extractRelevantTypesHelper(
|
||||
declText,
|
||||
typeName,
|
||||
startLine,
|
||||
foundSoFar,
|
||||
currentFile,
|
||||
foundContents,
|
||||
);
|
||||
|
||||
return foundSoFar;
|
||||
}
|
||||
|
||||
private async extractRelevantTypesHelper(
|
||||
declText: string,
|
||||
typeName: string,
|
||||
startLine: number,
|
||||
foundSoFar: Map<string, TypeSpanAndSourceFileAndAst>, // identifier -> [full hover result, source]
|
||||
currentFile: string,
|
||||
foundContents: Map<string, string>, // uri -> contents
|
||||
) {
|
||||
if (!foundSoFar.has(typeName)) {
|
||||
const ast = await getAst(currentFile, declText);
|
||||
if (!ast) {
|
||||
throw new Error(`failed to get ast for file ${currentFile}`);
|
||||
}
|
||||
foundSoFar.set(typeName, {
|
||||
typeSpan: declText,
|
||||
sourceFile: currentFile.slice(7),
|
||||
ast: ast,
|
||||
});
|
||||
|
||||
const language = getFullLanguageName(currentFile);
|
||||
const query = await getQueryForFile(
|
||||
currentFile,
|
||||
`static-context-queries/relevant-types-queries/${language}-extract-identifiers.scm`,
|
||||
);
|
||||
if (!query) {
|
||||
throw new Error(
|
||||
`failed to get query for file ${currentFile} and language ${language}`,
|
||||
);
|
||||
}
|
||||
|
||||
const identifiers = query.captures(ast.rootNode);
|
||||
|
||||
for (const { name, node } of identifiers) {
|
||||
if (foundSoFar.has(node.text)) continue;
|
||||
|
||||
try {
|
||||
const typeDefinitionResult = await this.ide.gotoTypeDefinition({
|
||||
filepath: currentFile,
|
||||
position: {
|
||||
character: node.startPosition.column,
|
||||
line: startLine + node.startPosition.row,
|
||||
},
|
||||
});
|
||||
|
||||
if (typeDefinitionResult.length > 0) {
|
||||
const tdLocation = typeDefinitionResult[0];
|
||||
|
||||
let content = "";
|
||||
|
||||
if (foundContents.has(tdLocation.filepath)) {
|
||||
content = foundContents.get(tdLocation.filepath)!;
|
||||
} else {
|
||||
content = await fs.readFile(
|
||||
localPathOrUriToPath(tdLocation.filepath),
|
||||
"utf8",
|
||||
);
|
||||
foundContents.set(tdLocation.filepath, content);
|
||||
}
|
||||
|
||||
const ast = await getAst(tdLocation.filepath, content);
|
||||
if (!ast) {
|
||||
throw new Error(
|
||||
`failed to get ast for file ${tdLocation.filepath}`,
|
||||
);
|
||||
}
|
||||
const decl = findEnclosingTypeDeclaration(
|
||||
content,
|
||||
tdLocation.range.start.line,
|
||||
tdLocation.range.start.character,
|
||||
ast,
|
||||
);
|
||||
if (!decl) {
|
||||
// throw new Error(`failed to get decl for file ${tdLocation.uri}`);
|
||||
console.error(
|
||||
`failed to get decl for file ${tdLocation.filepath}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (decl) {
|
||||
await this.extractRelevantTypesHelper(
|
||||
decl.fullText,
|
||||
node.text,
|
||||
tdLocation.range.start.line,
|
||||
foundSoFar,
|
||||
tdLocation.filepath,
|
||||
foundContents,
|
||||
);
|
||||
} else {
|
||||
// console.log("decl not found");
|
||||
}
|
||||
} else {
|
||||
// console.log("td not found");
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async extractRelevantHeaders(
|
||||
sources: string[],
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
holeType: string,
|
||||
cursorPosition: Position,
|
||||
returnTypeIsAny: boolean,
|
||||
): Promise<RelevantHeaders> {
|
||||
const relevantContext = new Set<TypeSpanAndSourceFile>();
|
||||
if (returnTypeIsAny) return relevantContext;
|
||||
// NOTE: This is necessary because TypeScript sucks.
|
||||
// There is no way to compare objects by value,
|
||||
// so sets of objects starts to accumulate tons of duplicates.
|
||||
const relevantContextMap = new Map<string, TypeSpanAndSourceFile>();
|
||||
const foundNormalForms = new Map<string, string>();
|
||||
|
||||
const targetTypes = await this.generateTargetTypes(relevantTypes, holeType);
|
||||
|
||||
for (const source of sources) {
|
||||
const topLevelDecls = await extractTopLevelDecls(source);
|
||||
for (const tld of topLevelDecls) {
|
||||
// pattern 0 is let/const, 1 is var, 2 is fun
|
||||
// if (!seenDecls.has(JSON.stringify()) {
|
||||
const originalDeclText =
|
||||
tld.pattern === 2
|
||||
? tld.captures.find((d) => d.name === "top.fn.decl")!.node.text
|
||||
: tld.captures.find((d) => d.name === "top.var.decl")!.node.text;
|
||||
|
||||
if (tld.pattern === 2) {
|
||||
// build a type span
|
||||
// TODO: this fails sometimes with Cannot read properties of undefined (reading 'text')
|
||||
// most likely due to my scm query and how I'm not attaching param name along with param type
|
||||
let funcType = "";
|
||||
try {
|
||||
funcType = extractFunctionTypeFromDecl(tld);
|
||||
} catch (err) {
|
||||
// Most likely is the case that there is no explicit return type annotation.
|
||||
const sigHelp = await this.ide.getSignatureHelp({
|
||||
filepath: source,
|
||||
position: cursorPosition,
|
||||
});
|
||||
if (!sigHelp) continue;
|
||||
funcType = sigHelp.signatures[0].label;
|
||||
|
||||
// TODO: This only works for TypeScript.
|
||||
function convertToArrowType(signature: string): string {
|
||||
// Handle various function declaration formats.
|
||||
const patterns = [
|
||||
// Standard: functionName(params): returnType.
|
||||
/^(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
|
||||
// With generics: functionName<T>(params): returnType.
|
||||
/^(\w+)\s*<[^>]*>\s*\((.*?)\)\s*:\s*(.+)$/,
|
||||
// With modifiers: export function functionName(params): returnType.
|
||||
/^(?:export\s+)?(?:function\s+)?(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const match = signature.match(pattern);
|
||||
if (match) {
|
||||
const [, , parameters, returnType] = match;
|
||||
return `(${parameters}) => ${returnType}`;
|
||||
}
|
||||
}
|
||||
|
||||
return signature;
|
||||
}
|
||||
|
||||
funcType = convertToArrowType(funcType);
|
||||
}
|
||||
const wrapped = `type __TMP = ${funcType};`;
|
||||
|
||||
const ast = await getAst("file.ts", wrapped);
|
||||
if (!ast) {
|
||||
throw new Error(`failed to generate ast for ${wrapped}`);
|
||||
}
|
||||
|
||||
// console.log(ast.rootNode);
|
||||
const alias = ast.rootNode.namedChild(0);
|
||||
// console.log(alias);
|
||||
if (!alias || alias.type !== "type_alias_declaration") {
|
||||
throw new Error(
|
||||
"extractRelevantHeaders: Failed to parse type alias",
|
||||
);
|
||||
}
|
||||
|
||||
const valueNode = alias.childForFieldName("value");
|
||||
if (!valueNode) throw new Error("No type value found");
|
||||
|
||||
const baseNode = unwrapToBaseType(valueNode);
|
||||
|
||||
await this.extractRelevantHeadersHelper(
|
||||
originalDeclText,
|
||||
baseNode,
|
||||
targetTypes,
|
||||
relevantTypes,
|
||||
relevantContext,
|
||||
relevantContextMap,
|
||||
foundNormalForms,
|
||||
source,
|
||||
);
|
||||
} else {
|
||||
const varTypNode = tld.captures.find(
|
||||
(d) => d.name === "top.var.type",
|
||||
)!.node;
|
||||
await this.extractRelevantHeadersHelper(
|
||||
originalDeclText,
|
||||
varTypNode,
|
||||
targetTypes,
|
||||
relevantTypes,
|
||||
relevantContext,
|
||||
relevantContextMap,
|
||||
foundNormalForms,
|
||||
source,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const v of relevantContextMap.values()) {
|
||||
relevantContext.add(v);
|
||||
}
|
||||
|
||||
return relevantContext;
|
||||
}
|
||||
|
||||
private async extractRelevantHeadersHelper(
|
||||
originalDeclText: string,
|
||||
node: Parser.SyntaxNode,
|
||||
targetTypes: Set<Parser.SyntaxNode>,
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
relevantContext: Set<TypeSpanAndSourceFile>,
|
||||
relevantContextMap: Map<string, TypeSpanAndSourceFile>,
|
||||
foundNormalForms: Map<string, string>,
|
||||
source: string,
|
||||
) {
|
||||
for (const typ of targetTypes) {
|
||||
if (
|
||||
await this.isTypeEquivalent(node, typ, relevantTypes, foundNormalForms)
|
||||
) {
|
||||
const ctx = { typeSpan: originalDeclText, sourceFile: source };
|
||||
relevantContextMap.set(JSON.stringify(ctx), ctx);
|
||||
}
|
||||
|
||||
if (node.type === "function_type") {
|
||||
const retTypeNode = node.namedChildren.find(
|
||||
(c) => c && c.type === "return_type",
|
||||
);
|
||||
if (retTypeNode) {
|
||||
await this.extractRelevantHeadersHelper(
|
||||
originalDeclText,
|
||||
retTypeNode,
|
||||
targetTypes,
|
||||
relevantTypes,
|
||||
relevantContext,
|
||||
relevantContextMap,
|
||||
foundNormalForms,
|
||||
source,
|
||||
);
|
||||
}
|
||||
} else if (node.type === "tuple_type") {
|
||||
for (const c of node.namedChildren) {
|
||||
await this.extractRelevantHeadersHelper(
|
||||
originalDeclText,
|
||||
c!,
|
||||
targetTypes,
|
||||
relevantTypes,
|
||||
relevantContext,
|
||||
relevantContextMap,
|
||||
foundNormalForms,
|
||||
source,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async generateTargetTypes(
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
holeType: string,
|
||||
) {
|
||||
const targetTypes = new Set<Parser.SyntaxNode>();
|
||||
// const ast = relevantTypes.get(holeIdentifier)!.ast;
|
||||
const ast = await getAst("file.ts", `type T = ${holeType};`);
|
||||
if (!ast) {
|
||||
throw new Error(`failed to generate ast for ${holeType}`);
|
||||
}
|
||||
|
||||
const alias = ast.rootNode.namedChild(0);
|
||||
if (!alias || alias.type !== "type_alias_declaration") {
|
||||
throw new Error("generateTargetTypes: Failed to parse type alias");
|
||||
}
|
||||
|
||||
const valueNode = alias.childForFieldName("value");
|
||||
if (!valueNode) throw new Error("No type value found");
|
||||
|
||||
const baseNode = unwrapToBaseType(valueNode);
|
||||
targetTypes.add(baseNode);
|
||||
await this.generateTargetTypesHelper(
|
||||
relevantTypes,
|
||||
holeType,
|
||||
targetTypes,
|
||||
baseNode,
|
||||
);
|
||||
|
||||
return targetTypes;
|
||||
}
|
||||
|
||||
private async generateTargetTypesHelper(
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
currType: string,
|
||||
targetTypes: Set<Parser.SyntaxNode>,
|
||||
node: Parser.SyntaxNode | null,
|
||||
): Promise<void> {
|
||||
if (!node) return;
|
||||
|
||||
if (node.type === "function_type") {
|
||||
const returnType = node.childForFieldName("return_type");
|
||||
if (returnType) {
|
||||
targetTypes.add(returnType);
|
||||
await this.generateTargetTypesHelper(
|
||||
relevantTypes,
|
||||
currType,
|
||||
targetTypes,
|
||||
returnType,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (node.type === "tuple_type") {
|
||||
for (const child of node.namedChildren) {
|
||||
if (child) {
|
||||
targetTypes.add(child);
|
||||
await this.generateTargetTypesHelper(
|
||||
relevantTypes,
|
||||
currType,
|
||||
targetTypes,
|
||||
child,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (relevantTypes.has(node.text)) {
|
||||
// const ast = relevantTypes.get(node.text)!.ast;
|
||||
const typeSpan = relevantTypes.get(node.text)?.typeSpan;
|
||||
|
||||
// const ast = await getAst("file.ts", `type T = ${typeSpan}`);
|
||||
const ast = await getAst("file.ts", typeSpan!);
|
||||
if (!ast) {
|
||||
throw new Error(`failed to generate ast for ${typeSpan}`);
|
||||
}
|
||||
|
||||
const alias = ast.rootNode.namedChild(0);
|
||||
if (!alias || alias.type !== "type_alias_declaration") {
|
||||
console.error("generateTargetTypesHelper: Failed to parse type alias");
|
||||
return;
|
||||
// throw new Error(
|
||||
// "generateTargetTypesHelper: Failed to parse type alias",
|
||||
// );
|
||||
}
|
||||
|
||||
const valueNode = alias.childForFieldName("value");
|
||||
if (!valueNode) throw new Error("No type value found");
|
||||
|
||||
const baseNode = unwrapToBaseType(valueNode);
|
||||
await this.generateTargetTypesHelper(
|
||||
relevantTypes,
|
||||
currType,
|
||||
targetTypes,
|
||||
baseNode,
|
||||
);
|
||||
}
|
||||
|
||||
// if (node.type === "type_identifier" || node.type === "predefined_type") {
|
||||
// return [node.text];
|
||||
// }
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
private async isTypeEquivalent(
|
||||
node: Parser.SyntaxNode,
|
||||
typ: Parser.SyntaxNode,
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
foundNormalForms: Map<string, string>,
|
||||
): Promise<boolean> {
|
||||
if (!node || !typ) {
|
||||
return false;
|
||||
}
|
||||
let normT1 = "";
|
||||
let normT2 = "";
|
||||
if (foundNormalForms.has(node.text)) {
|
||||
// console.log("found t1", true)
|
||||
normT1 = foundNormalForms.get(node.text)!;
|
||||
} else {
|
||||
// console.log("not found t1", false)
|
||||
normT1 = await this.normalize(node, relevantTypes);
|
||||
foundNormalForms.set(node.text, normT1);
|
||||
}
|
||||
if (foundNormalForms.has(typ.text)) {
|
||||
// console.log("found t2", true)
|
||||
normT2 = foundNormalForms.get(typ.text)!;
|
||||
} else {
|
||||
// console.log("not found t2", false)
|
||||
normT2 = await this.normalize(typ, relevantTypes);
|
||||
foundNormalForms.set(typ.text, normT2);
|
||||
}
|
||||
// const normT1 = foundNormalForms.has(t1) ? foundNormalForms.get(t1) : this.normalize2(t1, relevantTypes);
|
||||
// const normT2 = foundNormalForms.has(t2) ? foundNormalForms.get(t2) : this.normalize2(t2, relevantTypes);
|
||||
// console.log(`normal forms: ${normT1} {}{} ${normT2}`)
|
||||
return normT1 === normT2;
|
||||
}
|
||||
|
||||
private async normalize(
|
||||
node: Parser.SyntaxNode,
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
): Promise<string> {
|
||||
if (!node) return "";
|
||||
|
||||
switch (node.type) {
|
||||
case "function_type": {
|
||||
const params = node.child(0); // formal_parameters
|
||||
const returnType =
|
||||
node.childForFieldName("type") || node.namedChildren[1]; // function_type → parameters, =>, return
|
||||
|
||||
const paramTypes =
|
||||
params?.namedChildren
|
||||
.map((param) =>
|
||||
this.normalize(
|
||||
param!.childForFieldName("type")! ||
|
||||
param!.namedChildren.at(-1),
|
||||
relevantTypes,
|
||||
),
|
||||
)
|
||||
.join(", ") || "";
|
||||
|
||||
const ret = this.normalize(returnType!, relevantTypes);
|
||||
return `(${paramTypes}) => ${ret}`;
|
||||
}
|
||||
|
||||
case "tuple_type": {
|
||||
const elements = node.namedChildren.map((c) =>
|
||||
this.normalize(c!, relevantTypes),
|
||||
);
|
||||
return `[${elements.join(", ")}]`;
|
||||
}
|
||||
|
||||
case "union_type": {
|
||||
const parts = node.namedChildren.map((c) =>
|
||||
this.normalize(c!, relevantTypes),
|
||||
);
|
||||
return parts.join(" | ");
|
||||
}
|
||||
|
||||
case "type_identifier": {
|
||||
const alias = relevantTypes.get(node.text);
|
||||
if (!alias) return node.text;
|
||||
|
||||
// Parse the alias's type span
|
||||
const wrapped = `type __TMP = ${alias};`;
|
||||
const tree = await getAst("file.ts", wrapped);
|
||||
const valueNode = tree!.rootNode
|
||||
.descendantsOfType("type_alias_declaration")[0]
|
||||
?.childForFieldName("value");
|
||||
|
||||
return this.normalize(valueNode!, relevantTypes);
|
||||
}
|
||||
|
||||
case "predefined_type":
|
||||
case "number":
|
||||
case "string":
|
||||
return node.text;
|
||||
|
||||
default:
|
||||
// Fallback for types like array, etc.
|
||||
return node.text;
|
||||
}
|
||||
}
|
||||
|
||||
private insertAtPosition = (
|
||||
contents: string,
|
||||
cursorPosition: { line: number; character: number },
|
||||
insertText: string,
|
||||
): string => {
|
||||
const lines = contents.split(/\r?\n/); // Handle both LF and CRLF line endings
|
||||
const { line, character } = cursorPosition;
|
||||
|
||||
if (line < 0 || line >= lines.length) {
|
||||
throw new Error("Invalid line number");
|
||||
}
|
||||
|
||||
const targetLine = lines[line];
|
||||
if (character < 0 || character > targetLine.length) {
|
||||
throw new Error("Invalid character index");
|
||||
}
|
||||
|
||||
// Insert the text
|
||||
lines[line] =
|
||||
targetLine.slice(0, character) + insertText + targetLine.slice(character);
|
||||
|
||||
return lines.join("\n"); // Reconstruct the file
|
||||
};
|
||||
|
||||
private async getTypeScriptFilesFromWorkspaces(
|
||||
workspaceUris: string[],
|
||||
): Promise<string[]> {
|
||||
const tsExtensions = [".ts"];
|
||||
const allTsFiles: string[] = [];
|
||||
|
||||
for (const workspaceUri of workspaceUris) {
|
||||
try {
|
||||
// Convert URI to file path
|
||||
const folderPath = workspaceUri.startsWith("file://")
|
||||
? new URL(workspaceUri).pathname
|
||||
: workspaceUri;
|
||||
|
||||
const tsFiles = await this.scanDirectoryForTypeScriptFiles(
|
||||
folderPath,
|
||||
tsExtensions,
|
||||
);
|
||||
allTsFiles.push(...tsFiles);
|
||||
} catch (error) {
|
||||
console.error(`Error scanning workspace ${workspaceUri}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return allTsFiles;
|
||||
}
|
||||
|
||||
private async scanDirectoryForTypeScriptFiles(
|
||||
dirPath: string,
|
||||
tsExtensions: string[],
|
||||
): Promise<string[]> {
|
||||
const tsFiles: string[] = [];
|
||||
|
||||
const shouldSkipDirectory = (dirName: string): boolean => {
|
||||
const skipDirs = [
|
||||
"node_modules",
|
||||
".git",
|
||||
".vscode",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".next",
|
||||
"coverage",
|
||||
".nyc_output",
|
||||
"tmp",
|
||||
"temp",
|
||||
".cache",
|
||||
];
|
||||
|
||||
return skipDirs.includes(dirName) || dirName.startsWith(".");
|
||||
};
|
||||
|
||||
async function scanRecursively(currentPath: string): Promise<void> {
|
||||
try {
|
||||
const entries = await fs.readdir(currentPath, {
|
||||
withFileTypes: true,
|
||||
});
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = localPathOrUriToPath(
|
||||
path.join(currentPath, entry.name),
|
||||
);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// Skip common directories that typically don't contain source files
|
||||
if (!shouldSkipDirectory(entry.name)) {
|
||||
await scanRecursively(fullPath);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
const extension = path.extname(entry.name).toLowerCase();
|
||||
if (tsExtensions.includes(extension)) {
|
||||
tsFiles.push(fullPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error reading directory ${currentPath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
await scanRecursively(dirPath);
|
||||
return tsFiles;
|
||||
}
|
||||
}
|
||||
222
core/autocomplete/context/static-context/tree-sitter-utils.ts
Normal file
222
core/autocomplete/context/static-context/tree-sitter-utils.ts
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
import * as fs from "fs/promises";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
|
||||
import { getAst } from "../../util/ast";
|
||||
|
||||
export interface TypeDeclarationResult {
|
||||
name: string;
|
||||
fullText: string;
|
||||
startLine: number;
|
||||
startColumn: number;
|
||||
endLine: number;
|
||||
endColumn: number;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
export function findEnclosingTypeDeclaration(
|
||||
sourceCode: string,
|
||||
cursorLine: number,
|
||||
cursorColumn: number,
|
||||
ast: Parser.Tree,
|
||||
): TypeDeclarationResult | null {
|
||||
const point = { row: cursorLine, column: cursorColumn };
|
||||
let node = ast.rootNode.descendantForPosition(point);
|
||||
|
||||
while (
|
||||
node &&
|
||||
![
|
||||
"type_alias_declaration",
|
||||
"interface_declaration",
|
||||
"enum_declaration",
|
||||
].includes(node.type)
|
||||
) {
|
||||
if (!node.parent) return null;
|
||||
node = node.parent;
|
||||
}
|
||||
|
||||
if (!node) return null;
|
||||
|
||||
const nameNode = node.childForFieldName("name");
|
||||
const name = nameNode?.text ?? "<anonymous>";
|
||||
const fullText = sourceCode.slice(node.startIndex, node.endIndex);
|
||||
|
||||
return {
|
||||
name,
|
||||
fullText,
|
||||
startLine: node.startPosition.row,
|
||||
startColumn: node.startPosition.column,
|
||||
endLine: node.endPosition.row,
|
||||
endColumn: node.endPosition.column,
|
||||
kind: node.type,
|
||||
};
|
||||
}
|
||||
|
||||
export async function extractTopLevelDecls(
|
||||
currentFile: string,
|
||||
givenParser?: Parser,
|
||||
) {
|
||||
const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
|
||||
if (!ast) {
|
||||
throw new Error(`failed to get ast for file ${currentFile}`);
|
||||
}
|
||||
let language;
|
||||
if (givenParser) {
|
||||
language = givenParser.getLanguage();
|
||||
} else {
|
||||
language = getFullLanguageName(currentFile);
|
||||
}
|
||||
|
||||
const query = await getQueryForFile(
|
||||
currentFile,
|
||||
`static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
|
||||
);
|
||||
if (!query) {
|
||||
throw new Error(
|
||||
`failed to get query for file ${currentFile} and language ${language}`,
|
||||
);
|
||||
}
|
||||
return query.matches(ast.rootNode);
|
||||
}
|
||||
|
||||
export async function extractTopLevelDeclsWithFormatting(
|
||||
currentFile: string,
|
||||
givenParser?: Parser,
|
||||
) {
|
||||
const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
|
||||
if (!ast) {
|
||||
throw new Error(`failed to get ast for file ${currentFile}`);
|
||||
}
|
||||
let language;
|
||||
if (givenParser) {
|
||||
language = givenParser.getLanguage();
|
||||
} else {
|
||||
language = getFullLanguageName(currentFile);
|
||||
}
|
||||
|
||||
const query = await getQueryForFile(
|
||||
currentFile,
|
||||
`static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
|
||||
);
|
||||
if (!query) {
|
||||
throw new Error(
|
||||
`failed to get query for file ${currentFile} and language ${language}`,
|
||||
);
|
||||
}
|
||||
const matches = query.matches(ast.rootNode);
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const match of matches) {
|
||||
const item: {
|
||||
declaration: string;
|
||||
nodeType: string;
|
||||
name: string;
|
||||
declaredType: string;
|
||||
returnType?: string;
|
||||
} = {
|
||||
declaration: "",
|
||||
nodeType: "",
|
||||
name: "",
|
||||
declaredType: "",
|
||||
};
|
||||
|
||||
for (const { name, node } of match.captures) {
|
||||
if (name === "top.var.decl") {
|
||||
item.nodeType = "variable";
|
||||
item.declaration = node.text;
|
||||
|
||||
// Attempt to get the declared type (e.g., const x: string = ...)
|
||||
const typeNode = node.descendantsOfType("type_annotation")[0];
|
||||
if (typeNode) {
|
||||
item.declaredType = typeNode.text.replace(/^:\s*/, "");
|
||||
}
|
||||
} else if (name === "top.var.name" || name === "top.fn.name") {
|
||||
item.name = node.text;
|
||||
} else if (name === "top.fn.decl") {
|
||||
item.nodeType = "function";
|
||||
item.declaration = node.text;
|
||||
|
||||
// Get the return type (e.g., function foo(): string)
|
||||
const returnTypeNode = node.childForFieldName("return_type");
|
||||
if (returnTypeNode) {
|
||||
item.returnType = returnTypeNode.text.replace(/^:\s*/, "");
|
||||
}
|
||||
|
||||
// Get declaredType if needed (TypeScript style)
|
||||
const nameNode = node.childForFieldName("name");
|
||||
if (nameNode && nameNode.nextSibling?.type === "type_annotation") {
|
||||
item.declaredType = nameNode.nextSibling.text.replace(/^:\s*/, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (item.name && item.declaration) {
|
||||
results.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
export function extractFunctionTypeFromDecl(match: Parser.QueryMatch): string {
|
||||
let paramsNode: Parser.SyntaxNode | undefined = undefined;
|
||||
let returnNode: Parser.SyntaxNode | undefined = undefined;
|
||||
|
||||
for (const capture of match.captures) {
|
||||
if (capture.name === "top.fn.param.type") {
|
||||
paramsNode = capture.node;
|
||||
} else if (capture.name === "top.fn.type") {
|
||||
returnNode = capture.node;
|
||||
}
|
||||
}
|
||||
|
||||
if (!paramsNode) {
|
||||
console.error(
|
||||
`extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
|
||||
);
|
||||
throw new Error(
|
||||
`extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!returnNode) {
|
||||
console.error(
|
||||
`extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
|
||||
);
|
||||
throw new Error(
|
||||
`extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
|
||||
);
|
||||
}
|
||||
|
||||
return `(${paramsNode!.text}) => ${returnNode!.text}`;
|
||||
}
|
||||
|
||||
export function unwrapToBaseType(node: Parser.SyntaxNode): Parser.SyntaxNode {
|
||||
if (
|
||||
[
|
||||
"function_type",
|
||||
"tuple_type",
|
||||
"type_identifier",
|
||||
"predefined_type",
|
||||
].includes(node.type)
|
||||
) {
|
||||
return node;
|
||||
}
|
||||
|
||||
for (const child of node.namedChildren) {
|
||||
const unwrapped = unwrapToBaseType(child!);
|
||||
if (
|
||||
unwrapped !== child ||
|
||||
[
|
||||
"function_type",
|
||||
"tuple_type",
|
||||
"type_identifier",
|
||||
"predefined_type",
|
||||
].includes(unwrapped.type)
|
||||
) {
|
||||
return unwrapped;
|
||||
}
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
33
core/autocomplete/context/static-context/types.ts
Normal file
33
core/autocomplete/context/static-context/types.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { Tree } from "web-tree-sitter";
|
||||
import { Range } from "../../..";
|
||||
|
||||
export interface TypeSpanAndSourceFile {
|
||||
typeSpan: string;
|
||||
sourceFile: string;
|
||||
}
|
||||
|
||||
export interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile {
|
||||
ast: Tree;
|
||||
}
|
||||
|
||||
export interface HoleContext {
|
||||
fullHoverResult: string;
|
||||
functionName: string;
|
||||
functionTypeSpan: string;
|
||||
returnTypeIsAny: boolean;
|
||||
range: Range;
|
||||
source: string;
|
||||
}
|
||||
|
||||
export type RelevantTypes = Map<string, TypeSpanAndSourceFileAndAst>;
|
||||
export type RelevantHeaders = Set<TypeSpanAndSourceFile>;
|
||||
|
||||
export type Filepath = string;
|
||||
export type RelevantType = string;
|
||||
export type RelevantHeader = string;
|
||||
|
||||
export interface StaticContext {
|
||||
holeType: string;
|
||||
relevantTypes: Map<Filepath, RelevantType[]>;
|
||||
relevantHeaders: Map<Filepath, RelevantHeader[]>;
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@ import {
|
|||
AutocompleteCodeSnippet,
|
||||
AutocompleteDiffSnippet,
|
||||
AutocompleteSnippetType,
|
||||
AutocompleteStaticSnippet,
|
||||
} from "./types";
|
||||
|
||||
const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled
|
||||
|
|
@ -24,6 +25,7 @@ export interface SnippetPayload {
|
|||
diffSnippets: AutocompleteDiffSnippet[];
|
||||
clipboardSnippets: AutocompleteClipboardSnippet[];
|
||||
recentlyOpenedFileSnippets: AutocompleteCodeSnippet[];
|
||||
staticSnippet: AutocompleteStaticSnippet[];
|
||||
}
|
||||
|
||||
function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
|
||||
|
|
@ -185,6 +187,7 @@ export const getAllSnippets = async ({
|
|||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyOpenedFileSnippets,
|
||||
staticSnippet,
|
||||
] = await Promise.all([
|
||||
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
|
||||
racePromise(
|
||||
|
|
@ -196,6 +199,9 @@ export const getAllSnippets = async ({
|
|||
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
|
||||
racePromise(getClipboardSnippets(ide)),
|
||||
racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete
|
||||
helper.options.experimental_enableStaticContextualization
|
||||
? racePromise(contextRetrievalService.getStaticContextSnippets(helper))
|
||||
: [],
|
||||
]);
|
||||
|
||||
return {
|
||||
|
|
@ -207,6 +213,7 @@ export const getAllSnippets = async ({
|
|||
clipboardSnippets,
|
||||
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
|
||||
recentlyOpenedFileSnippets,
|
||||
staticSnippet,
|
||||
};
|
||||
};
|
||||
|
||||
|
|
@ -231,6 +238,7 @@ export const getAllSnippetsWithoutRace = async ({
|
|||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyOpenedFileSnippets,
|
||||
staticSnippet,
|
||||
] = await Promise.all([
|
||||
contextRetrievalService.getRootPathSnippets(helper),
|
||||
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
|
||||
|
|
@ -240,6 +248,9 @@ export const getAllSnippetsWithoutRace = async ({
|
|||
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
|
||||
getClipboardSnippets(ide),
|
||||
getSnippetsFromRecentlyOpenedFiles(helper, ide),
|
||||
helper.options.experimental_enableStaticContextualization
|
||||
? contextRetrievalService.getStaticContextSnippets(helper)
|
||||
: [],
|
||||
]);
|
||||
|
||||
return {
|
||||
|
|
@ -251,5 +262,6 @@ export const getAllSnippetsWithoutRace = async ({
|
|||
clipboardSnippets,
|
||||
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
|
||||
recentlyOpenedFileSnippets,
|
||||
staticSnippet,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ export enum AutocompleteSnippetType {
|
|||
Code = "code",
|
||||
Diff = "diff",
|
||||
Clipboard = "clipboard",
|
||||
Static = "static",
|
||||
}
|
||||
|
||||
interface BaseAutocompleteSnippet {
|
||||
|
|
@ -23,7 +24,13 @@ export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet {
|
|||
copiedAt: string;
|
||||
}
|
||||
|
||||
export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet {
|
||||
type: AutocompleteSnippetType.Static;
|
||||
filepath: string;
|
||||
}
|
||||
|
||||
export type AutocompleteSnippet =
|
||||
| AutocompleteCodeSnippet
|
||||
| AutocompleteDiffSnippet
|
||||
| AutocompleteClipboardSnippet;
|
||||
| AutocompleteClipboardSnippet
|
||||
| AutocompleteStaticSnippet;
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {
|
|||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippet,
|
||||
AutocompleteSnippetType,
|
||||
AutocompleteStaticSnippet,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { formatOpenedFilesContext } from "./formatOpenedFilesContext";
|
||||
|
|
@ -32,9 +33,9 @@ const shuffleArray = <T>(array: T[]): T[] => {
|
|||
};
|
||||
|
||||
function filterSnippetsAlreadyInCaretWindow(
|
||||
snippets: AutocompleteCodeSnippet[],
|
||||
snippets: (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[],
|
||||
caretWindow: string,
|
||||
): AutocompleteCodeSnippet[] {
|
||||
): (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[] {
|
||||
return snippets.filter(
|
||||
(s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()),
|
||||
);
|
||||
|
|
@ -52,7 +53,11 @@ export const getSnippets = (
|
|||
recentlyOpenedFiles: payload.recentlyOpenedFileSnippets,
|
||||
base: shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
[
|
||||
...payload.rootPathSnippets,
|
||||
...payload.importDefinitionSnippets,
|
||||
...payload.staticSnippet,
|
||||
],
|
||||
helper.prunedCaretWindow,
|
||||
),
|
||||
),
|
||||
|
|
@ -107,7 +112,11 @@ export const getSnippets = (
|
|||
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
|
||||
snippets: shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
[
|
||||
...payload.rootPathSnippets,
|
||||
...payload.importDefinitionSnippets,
|
||||
...payload.staticSnippet,
|
||||
],
|
||||
helper.prunedCaretWindow,
|
||||
),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
AutocompleteDiffSnippet,
|
||||
AutocompleteSnippet,
|
||||
AutocompleteSnippetType,
|
||||
AutocompleteStaticSnippet,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
|
|
@ -51,6 +52,12 @@ const formatDiffSnippet = (
|
|||
return snippet;
|
||||
};
|
||||
|
||||
const formatStaticSnippet = (
|
||||
snippet: AutocompleteStaticSnippet,
|
||||
): AutocompleteStaticSnippet => {
|
||||
return snippet;
|
||||
};
|
||||
|
||||
const commentifySnippet = (
|
||||
helper: HelperVars,
|
||||
snippet: AutocompleteSnippet,
|
||||
|
|
@ -81,6 +88,8 @@ export const formatSnippets = (
|
|||
return formatDiffSnippet(snippet);
|
||||
case AutocompleteSnippetType.Clipboard:
|
||||
return formatClipboardSnippet(snippet, workspaceDirs);
|
||||
case AutocompleteSnippetType.Static:
|
||||
return formatStaticSnippet(snippet);
|
||||
}
|
||||
})
|
||||
.map((item) => {
|
||||
|
|
|
|||
|
|
@ -105,24 +105,27 @@ export class AutocompleteLoggingService {
|
|||
});
|
||||
|
||||
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
|
||||
void Telemetry.capture(
|
||||
"autocomplete",
|
||||
{
|
||||
accepted: restOfOutcome.accepted,
|
||||
cacheHit: restOfOutcome.cacheHit,
|
||||
completionId: restOfOutcome.completionId,
|
||||
completionOptions: restOfOutcome.completionOptions,
|
||||
debounceDelay: restOfOutcome.debounceDelay,
|
||||
fileExtension: getUriFileExtension(restOfOutcome.filepath),
|
||||
maxPromptTokens: restOfOutcome.maxPromptTokens,
|
||||
modelName: restOfOutcome.modelName,
|
||||
modelProvider: restOfOutcome.modelProvider,
|
||||
multilineCompletions: restOfOutcome.multilineCompletions,
|
||||
time: restOfOutcome.time,
|
||||
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
|
||||
numLines: restOfOutcome.numLines,
|
||||
},
|
||||
true,
|
||||
);
|
||||
const toLog = {
|
||||
accepted: restOfOutcome.accepted,
|
||||
cacheHit: restOfOutcome.cacheHit,
|
||||
completionId: restOfOutcome.completionId,
|
||||
completionOptions: restOfOutcome.completionOptions,
|
||||
debounceDelay: restOfOutcome.debounceDelay,
|
||||
fileExtension: getUriFileExtension(restOfOutcome.filepath),
|
||||
maxPromptTokens: restOfOutcome.maxPromptTokens,
|
||||
modelName: restOfOutcome.modelName,
|
||||
modelProvider: restOfOutcome.modelProvider,
|
||||
multilineCompletions: restOfOutcome.multilineCompletions,
|
||||
time: restOfOutcome.time,
|
||||
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
|
||||
numLines: restOfOutcome.numLines,
|
||||
};
|
||||
|
||||
outcome.enabledStaticContextualization
|
||||
? void Telemetry.capture("autocomplete", {
|
||||
...toLog,
|
||||
enabledStaticContextualization: true,
|
||||
})
|
||||
: void Telemetry.capture("autocomplete", toLog);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,4 +42,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
|
|||
completionId: string;
|
||||
uniqueId: string;
|
||||
timestamp: string;
|
||||
enabledStaticContextualization?: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,5 +11,6 @@ export function convertCustomCommandToSlashCommand(
|
|||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
source: "json-custom-command",
|
||||
promptFile: customCommand.sourceFile, // TODO refactor promptFile to align with sourceFile
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,5 +9,6 @@ export function convertPromptBlockToSlashCommand(
|
|||
description: prompt.description ?? "",
|
||||
prompt: prompt.prompt,
|
||||
source: "yaml-prompt-block",
|
||||
promptFile: prompt.sourceFile, // Align with the sourceFile property
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -522,7 +522,10 @@ export class ConfigHandler {
|
|||
return config;
|
||||
}
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
async openConfigProfile(
|
||||
profileId?: string,
|
||||
element?: { sourceFile?: string },
|
||||
) {
|
||||
let openProfileId = profileId || this.currentProfile?.profileDescription.id;
|
||||
if (!openProfileId) {
|
||||
return;
|
||||
|
|
@ -530,8 +533,10 @@ export class ConfigHandler {
|
|||
const profile = this.currentOrg.profiles.find(
|
||||
(p) => p.profileDescription.id === openProfileId,
|
||||
);
|
||||
|
||||
if (profile?.profileDescription.profileType === "local") {
|
||||
await this.ide.openFile(profile.profileDescription.uri);
|
||||
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
|
||||
await this.ide.openFile(configFile);
|
||||
} else {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
|
||||
|
|
|
|||
|
|
@ -652,6 +652,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
|
|||
configurationStatus: llm.getConfigurationStatus(),
|
||||
apiKeyLocation: llm.apiKeyLocation,
|
||||
envSecretLocations: llm.envSecretLocations,
|
||||
sourceFile: llm.sourceFile,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export const sharedConfigSchema = z
|
|||
optInNextEditFeature: z.boolean(),
|
||||
enableExperimentalTools: z.boolean(),
|
||||
codebaseToolCallingOnly: z.boolean(),
|
||||
enableStaticContextualization: z.boolean(),
|
||||
|
||||
// `ui` in `ContinueConfig`
|
||||
showSessionTabs: z.boolean(),
|
||||
|
|
@ -188,6 +189,10 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
configCopy.experimental.codebaseToolCallingOnly =
|
||||
sharedConfig.codebaseToolCallingOnly;
|
||||
}
|
||||
if (sharedConfig.enableStaticContextualization !== undefined) {
|
||||
configCopy.experimental.enableStaticContextualization =
|
||||
sharedConfig.enableStaticContextualization;
|
||||
}
|
||||
|
||||
return configCopy;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,6 +56,7 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
|||
rule: rule.rule,
|
||||
globs: rule.globs,
|
||||
name: rule.name,
|
||||
ruleFile: rule.sourceFile,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -235,8 +236,8 @@ async function configYamlToContinueConfig(options: {
|
|||
startUrl: doc.startUrl,
|
||||
rootUrl: doc.rootUrl,
|
||||
faviconUrl: doc.faviconUrl,
|
||||
maxDepth: doc.maxDepth,
|
||||
useLocalCrawling: doc.useLocalCrawling,
|
||||
sourceFile: doc.sourceFile,
|
||||
}));
|
||||
|
||||
config.mcpServers?.forEach((mcpServer) => {
|
||||
|
|
@ -429,6 +430,7 @@ async function configYamlToContinueConfig(options: {
|
|||
(config.mcpServers ?? []).map((server) => ({
|
||||
id: server.name,
|
||||
name: server.name,
|
||||
sourceFile: server.sourceFile,
|
||||
transport: {
|
||||
type: "stdio",
|
||||
args: [],
|
||||
|
|
|
|||
|
|
@ -349,7 +349,10 @@ export class Core {
|
|||
});
|
||||
|
||||
on("config/openProfile", async (msg) => {
|
||||
await this.configHandler.openConfigProfile(msg.data.profileId);
|
||||
await this.configHandler.openConfigProfile(
|
||||
msg.data.profileId,
|
||||
msg.data?.element,
|
||||
);
|
||||
});
|
||||
|
||||
on("config/reload", async (msg) => {
|
||||
|
|
|
|||
119
core/index.d.ts
vendored
119
core/index.d.ts
vendored
|
|
@ -237,6 +237,7 @@ export interface SiteIndexingConfig {
|
|||
maxDepth?: number;
|
||||
faviconUrl?: string;
|
||||
useLocalCrawling?: boolean;
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
export interface DocsIndexingDetails {
|
||||
|
|
@ -369,10 +370,32 @@ export interface ThinkingChatMessage {
|
|||
toolCalls?: ToolCallDelta[];
|
||||
}
|
||||
|
||||
/**
|
||||
* This is meant to be equivalent to the OpenAI [usage object](https://platform.openai.com/docs/api-reference/chat/object#chat/object-usage)
|
||||
* but potentially with additional information that is needed for other providers.
|
||||
*/
|
||||
export interface Usage {
|
||||
completionTokens: number;
|
||||
promptTokens: number;
|
||||
promptTokensDetails?: {
|
||||
cachedTokens?: number;
|
||||
/** This an Anthropic-specific property */
|
||||
cacheWriteTokens?: number;
|
||||
audioTokens?: number;
|
||||
};
|
||||
completionTokensDetails?: {
|
||||
acceptedPredictionTokens?: number;
|
||||
reasoningTokens?: number;
|
||||
rejectedPredictionTokens?: number;
|
||||
audioTokens?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AssistantChatMessage {
|
||||
role: "assistant";
|
||||
content: MessageContent;
|
||||
toolCalls?: ToolCallDelta[];
|
||||
usage?: Usage;
|
||||
}
|
||||
|
||||
export interface SystemChatMessage {
|
||||
|
|
@ -491,12 +514,14 @@ export interface LLMInteractionStartChat extends LLMInteractionBase {
|
|||
kind: "startChat";
|
||||
messages: ChatMessage[];
|
||||
options: CompletionOptions;
|
||||
provider: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartComplete extends LLMInteractionBase {
|
||||
kind: "startComplete";
|
||||
prompt: string;
|
||||
options: CompletionOptions;
|
||||
provider: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionStartFim extends LLMInteractionBase {
|
||||
|
|
@ -504,6 +529,7 @@ export interface LLMInteractionStartFim extends LLMInteractionBase {
|
|||
prefix: string;
|
||||
suffix: string;
|
||||
options: CompletionOptions;
|
||||
provider: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionChunk extends LLMInteractionBase {
|
||||
|
|
@ -520,6 +546,7 @@ export interface LLMInteractionEnd extends LLMInteractionBase {
|
|||
promptTokens: number;
|
||||
generatedTokens: number;
|
||||
thinkingTokens: number;
|
||||
usage: Usage | undefined;
|
||||
}
|
||||
|
||||
export interface LLMInteractionSuccess extends LLMInteractionEnd {
|
||||
|
|
@ -634,6 +661,8 @@ export interface LLMOptions {
|
|||
deploymentId?: string;
|
||||
|
||||
env?: Record<string, string | number | boolean>;
|
||||
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
|
||||
|
|
@ -845,6 +874,8 @@ export interface IDE {
|
|||
|
||||
// LSP
|
||||
gotoDefinition(location: Location): Promise<RangeInFile[]>;
|
||||
gotoTypeDefinition(location: Location): Promise<RangeInFile[]>; // TODO: add to jetbrains
|
||||
getSignatureHelp(location: Location): Promise<SignatureHelp | null>; // TODO: add to jetbrains
|
||||
|
||||
// Callbacks
|
||||
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void;
|
||||
|
|
@ -1009,6 +1040,7 @@ export interface CustomCommand {
|
|||
name: string;
|
||||
prompt: string;
|
||||
description?: string;
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
export interface Prediction {
|
||||
|
|
@ -1126,6 +1158,8 @@ export interface ModelDescription {
|
|||
capabilities?: ModelCapability;
|
||||
roles?: ModelRole[];
|
||||
configurationStatus?: LLMConfigurationStatuses;
|
||||
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
export interface JSONEmbedOptions {
|
||||
|
|
@ -1183,6 +1217,7 @@ export interface TabAutocompleteOptions {
|
|||
experimental_includeRecentlyVisitedRanges: boolean | number;
|
||||
experimental_includeRecentlyEditedRanges: boolean | number;
|
||||
experimental_includeDiff: boolean | number;
|
||||
experimental_enableStaticContextualization: boolean;
|
||||
}
|
||||
|
||||
export interface StdioOptions {
|
||||
|
|
@ -1280,6 +1315,7 @@ export interface MCPServerStatus extends MCPOptions {
|
|||
tools: MCPTool[];
|
||||
resources: MCPResource[];
|
||||
resourceTemplates: MCPResourceTemplate[];
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
export interface ContinueUIConfig {
|
||||
|
|
@ -1382,6 +1418,68 @@ export interface RangeInFileWithNextEditInfo {
|
|||
|
||||
export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
|
||||
|
||||
/**
|
||||
* Signature help represents the signature of something
|
||||
* callable. There can be multiple signatures but only one
|
||||
* active and only one active parameter.
|
||||
*/
|
||||
export class SignatureHelp {
|
||||
/**
|
||||
* One or more signatures.
|
||||
*/
|
||||
signatures: SignatureInformation[];
|
||||
|
||||
/**
|
||||
* The active signature.
|
||||
*/
|
||||
activeSignature: number;
|
||||
|
||||
/**
|
||||
* The active parameter of the active signature.
|
||||
*/
|
||||
activeParameter: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the signature of something callable. A signature
|
||||
* can have a label, like a function-name, a doc-comment, and
|
||||
* a set of parameters.
|
||||
*/
|
||||
export class SignatureInformation {
|
||||
/**
|
||||
* The label of this signature. Will be shown in
|
||||
* the UI.
|
||||
*/
|
||||
label: string;
|
||||
|
||||
/**
|
||||
* The parameters of this signature.
|
||||
*/
|
||||
parameters: ParameterInformation[];
|
||||
|
||||
/**
|
||||
* The index of the active parameter.
|
||||
*
|
||||
* If provided, this is used in place of {@linkcode SignatureHelp.activeParameter}.
|
||||
*/
|
||||
activeParameter?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a parameter of a callable-signature. A parameter can
|
||||
* have a label and a doc-comment.
|
||||
*/
|
||||
export class ParameterInformation {
|
||||
/**
|
||||
* The label of this signature.
|
||||
*
|
||||
* Either a string or inclusive start and exclusive end offsets within its containing
|
||||
* {@link SignatureInformation.label signature label}. *Note*: A label of type string must be
|
||||
* a substring of its containing signature information's {@link SignatureInformation.label label}.
|
||||
*/
|
||||
label: string | [number, number];
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the configuration for a quick action in the Code Lens.
|
||||
* Quick actions are custom commands that can be added to function and class declarations.
|
||||
|
|
@ -1452,6 +1550,12 @@ export interface ExperimentalConfig {
|
|||
* instead of embeddings, FTS, recently edited files, etc.
|
||||
*/
|
||||
codebaseToolCallingOnly?: boolean;
|
||||
|
||||
/**
|
||||
* If enabled, static contextualization will be used to
|
||||
* gather context for the model where necessary.
|
||||
*/
|
||||
enableStaticContextualization?: boolean;
|
||||
}
|
||||
|
||||
export interface AnalyticsConfig {
|
||||
|
|
@ -1686,23 +1790,12 @@ export interface CompleteOnboardingPayload {
|
|||
apiKey?: string;
|
||||
}
|
||||
|
||||
export type PruningStatus = "deleted-last-input" | "pruned" | "not-pruned";
|
||||
|
||||
export interface CompiledMessagesResult {
|
||||
compiledChatMessages: ChatMessage[];
|
||||
pruningStatus: PruningStatus;
|
||||
didPrune: boolean;
|
||||
contextPercentage: number;
|
||||
}
|
||||
|
||||
export interface MessageOption {
|
||||
precompiled: boolean;
|
||||
}
|
||||
|
||||
export type WarningMessageLevel = "warning" | "fatal";
|
||||
|
||||
export type WarningCategory = "exceeded-context-length" | "deleted-last-input";
|
||||
|
||||
export interface WarningMessage {
|
||||
message: string;
|
||||
level: WarningMessageLevel;
|
||||
category: WarningCategory;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,7 +53,7 @@ describe("DocsCrawler", () => {
|
|||
};
|
||||
}
|
||||
|
||||
describe("GitHub Crawler", () => {
|
||||
describe.skip("GitHub Crawler", () => {
|
||||
const repoUrl =
|
||||
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import {
|
|||
CompiledMessagesResult,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
PruningStatus,
|
||||
Tool,
|
||||
} from "../index.js";
|
||||
import { autodetectTemplateType } from "./autodetect.js";
|
||||
|
|
@ -363,9 +362,6 @@ function getTokenCountingBufferSafety(contextLength: number) {
|
|||
}
|
||||
|
||||
const MIN_RESPONSE_TOKENS = 1000;
|
||||
function getMinResponseTokens(maxTokens: number) {
|
||||
return Math.min(MIN_RESPONSE_TOKENS, maxTokens);
|
||||
}
|
||||
|
||||
function pruneRawPromptFromTop(
|
||||
modelName: string,
|
||||
|
|
@ -425,6 +421,8 @@ function compileChatMessages({
|
|||
supportsImages: boolean;
|
||||
tools?: Tool[];
|
||||
}): CompiledMessagesResult {
|
||||
let didPrune = false;
|
||||
|
||||
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
|
||||
|
||||
// If images not supported, convert MessagePart[] to string
|
||||
|
|
@ -446,22 +444,15 @@ function compileChatMessages({
|
|||
|
||||
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
|
||||
|
||||
while (msgsCopy.length > 1) {
|
||||
if (isUserOrToolMsg(msgsCopy.at(-1))) {
|
||||
break;
|
||||
}
|
||||
msgsCopy.pop();
|
||||
// Extract the tool sequence from the end of the message array
|
||||
const toolSequence = extractToolSequence(msgsCopy);
|
||||
|
||||
// Count tokens for all messages in the tool sequence
|
||||
let lastMessagesTokens = 0;
|
||||
for (const msg of toolSequence) {
|
||||
lastMessagesTokens += countChatMessageTokens(modelName, msg);
|
||||
}
|
||||
|
||||
// // Extract the tool sequence from the end of the message array
|
||||
// const toolSequence = extractToolSequence(msgsCopy);
|
||||
|
||||
// // Count tokens for all messages in the tool sequence
|
||||
// let lastMessagesTokens = 0;
|
||||
// for (const msg of toolSequence) {
|
||||
// lastMessagesTokens += countChatMessageTokens(modelName, msg);
|
||||
// }
|
||||
|
||||
// System message
|
||||
let systemMsgTokens = 0;
|
||||
if (systemMsg) {
|
||||
|
|
@ -475,7 +466,7 @@ function compileChatMessages({
|
|||
}
|
||||
|
||||
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
|
||||
const minOutputTokens = getMinResponseTokens(maxTokens);
|
||||
const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens);
|
||||
|
||||
let inputTokensAvailable = contextLength;
|
||||
|
||||
|
|
@ -486,19 +477,19 @@ function compileChatMessages({
|
|||
// Non-negotiable messages
|
||||
inputTokensAvailable -= toolTokens;
|
||||
inputTokensAvailable -= systemMsgTokens;
|
||||
// inputTokensAvailable -= lastMessagesTokens;
|
||||
inputTokensAvailable -= lastMessagesTokens;
|
||||
|
||||
// Make sure there's enough context for the non-excludable items
|
||||
if (inputTokensAvailable < 0) {
|
||||
throw new Error(
|
||||
`Not enough context available to include the system message, last user message, and tools.
|
||||
There must be at least ${minOutputTokens} tokens remaining for output.
|
||||
Request had the following token counts:
|
||||
- contextLength: ${contextLength}
|
||||
- counting safety buffer: ${countingSafetyBuffer}
|
||||
- tools: ~${toolTokens}
|
||||
- system message: ~${systemMsgTokens}
|
||||
- max output tokens: ${maxTokens}`,
|
||||
There must be at least ${minOutputTokens} tokens remaining for output.
|
||||
Request had the following token counts:
|
||||
- contextLength: ${contextLength}
|
||||
- counting safety buffer: ${countingSafetyBuffer}
|
||||
- tools: ~${toolTokens}
|
||||
- system message: ~${systemMsgTokens}
|
||||
- max output tokens: ${maxTokens}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -513,12 +504,10 @@ function compileChatMessages({
|
|||
};
|
||||
});
|
||||
|
||||
let pruningStatus: PruningStatus = "not-pruned";
|
||||
|
||||
while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
|
||||
const message = historyWithTokens.shift()!;
|
||||
currentTotal -= message.tokens;
|
||||
pruningStatus = "pruned";
|
||||
didPrune = true;
|
||||
|
||||
// At this point make sure no latent tool response without corresponding call
|
||||
while (historyWithTokens[0]?.role === "tool") {
|
||||
|
|
@ -527,18 +516,24 @@ function compileChatMessages({
|
|||
}
|
||||
}
|
||||
|
||||
if (historyWithTokens.length === 0) {
|
||||
pruningStatus = "deleted-last-input";
|
||||
}
|
||||
|
||||
// Now reassemble
|
||||
const reassembled: ChatMessage[] = [];
|
||||
if (systemMsg) {
|
||||
reassembled.push(systemMsg);
|
||||
}
|
||||
reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
|
||||
reassembled.push(...toolSequence);
|
||||
|
||||
return { compiledChatMessages: reassembled, pruningStatus };
|
||||
const inputTokens =
|
||||
currentTotal + systemMsgTokens + toolTokens + lastMessagesTokens;
|
||||
const availableTokens =
|
||||
contextLength - countingSafetyBuffer - minOutputTokens;
|
||||
const contextPercentage = inputTokens / availableTokens;
|
||||
return {
|
||||
compiledChatMessages: reassembled,
|
||||
didPrune,
|
||||
contextPercentage,
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import {
|
|||
RequestOptions,
|
||||
TabAutocompleteOptions,
|
||||
TemplateType,
|
||||
Usage,
|
||||
} from "../index.js";
|
||||
import mergeJson from "../util/merge.js";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
|
|
@ -186,6 +187,9 @@ export abstract class BaseLLM implements ILLM {
|
|||
maxEmbeddingChunkSize: number;
|
||||
maxEmbeddingBatchSize: number;
|
||||
|
||||
//URI to local block defining this LLM
|
||||
sourceFile?: string;
|
||||
|
||||
private _llmOptions: LLMOptions;
|
||||
|
||||
protected openaiAdapter?: BaseLlmApi;
|
||||
|
|
@ -289,6 +293,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`;
|
||||
|
||||
this.autocompleteOptions = options.autocompleteOptions;
|
||||
this.sourceFile = options.sourceFile;
|
||||
}
|
||||
|
||||
getConfigurationStatus() {
|
||||
|
|
@ -327,6 +332,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion: string,
|
||||
thinking: string | undefined,
|
||||
interaction: ILLMInteractionLog | undefined,
|
||||
usage: Usage | undefined,
|
||||
error?: any,
|
||||
): InteractionStatus {
|
||||
let promptTokens = this.countTokens(prompt);
|
||||
|
|
@ -368,6 +374,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "cancelled";
|
||||
} else {
|
||||
|
|
@ -379,6 +386,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "error";
|
||||
}
|
||||
|
|
@ -388,6 +396,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "success";
|
||||
}
|
||||
|
|
@ -574,6 +583,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
prefix,
|
||||
suffix,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, fimLog);
|
||||
|
|
@ -622,6 +632,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -630,6 +641,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -641,6 +653,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -681,6 +694,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "startComplete",
|
||||
prompt,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
|
|
@ -736,6 +750,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -744,6 +759,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -755,6 +771,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -796,6 +813,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "startComplete",
|
||||
prompt: prompt,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
|
|
@ -829,6 +847,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -837,6 +856,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -848,6 +868,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -923,7 +944,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
let messages = _messages;
|
||||
|
||||
// If not precompiled, compile the chat messages
|
||||
if (!messageOptions || messageOptions.precompiled === false) {
|
||||
if (!messageOptions?.precompiled) {
|
||||
const { compiledChatMessages } = compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: _messages,
|
||||
|
|
@ -944,6 +965,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "startChat",
|
||||
messages,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
|
|
@ -952,6 +974,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
let thinking = "";
|
||||
let completion = "";
|
||||
let usage: Usage | undefined = undefined;
|
||||
|
||||
try {
|
||||
if (this.templateMessages) {
|
||||
|
|
@ -1018,6 +1041,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "message",
|
||||
message: chunk,
|
||||
});
|
||||
|
||||
if (chunk.role === "assistant" && chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
|
|
@ -1028,6 +1056,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
usage,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -1036,6 +1065,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
usage,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -1047,6 +1077,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
usage,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,10 @@
|
|||
import { streamSse } from "@continuedev/fetch";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
Usage,
|
||||
} from "../../index.js";
|
||||
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
|
@ -234,15 +239,49 @@ class Anthropic extends BaseLLM {
|
|||
|
||||
if (options.stream === false) {
|
||||
const data = await response.json();
|
||||
yield { role: "assistant", content: data.content[0].text };
|
||||
const cost = data.usage
|
||||
? {
|
||||
inputTokens: data.usage.input_tokens,
|
||||
outputTokens: data.usage.output_tokens,
|
||||
totalTokens: data.usage.input_tokens + data.usage.output_tokens,
|
||||
}
|
||||
: {};
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: data.content[0].text,
|
||||
...(Object.keys(cost).length > 0 ? { cost } : {}),
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
let lastToolUseId: string | undefined;
|
||||
let lastToolUseName: string | undefined;
|
||||
let usage: Usage = {
|
||||
promptTokens: 0,
|
||||
completionTokens: 0,
|
||||
promptTokensDetails: {
|
||||
cachedTokens: 0,
|
||||
cacheWriteTokens: 0,
|
||||
},
|
||||
};
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
// https://docs.anthropic.com/en/api/messages-streaming#event-types
|
||||
switch (value.type) {
|
||||
case "message_start":
|
||||
// Capture initial usage information
|
||||
usage.promptTokens = value.message.usage.input_tokens;
|
||||
usage.promptTokensDetails!.cachedTokens =
|
||||
value.message.usage.cache_read_input_tokens;
|
||||
usage.promptTokensDetails!.cacheWriteTokens =
|
||||
value.message.usage.cache_creation_input_tokens;
|
||||
break;
|
||||
case "message_delta":
|
||||
// Update usage information during streaming
|
||||
if (value.usage) {
|
||||
usage.completionTokens = value.usage.output_tokens;
|
||||
}
|
||||
break;
|
||||
case "content_block_start":
|
||||
if (value.content_block.type === "tool_use") {
|
||||
lastToolUseId = value.content_block.id;
|
||||
|
|
@ -250,7 +289,6 @@ class Anthropic extends BaseLLM {
|
|||
}
|
||||
// handle redacted thinking
|
||||
if (value.content_block.type === "redacted_thinking") {
|
||||
console.log("redacted thinking", value.content_block.data);
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
|
|
@ -303,6 +341,12 @@ class Anthropic extends BaseLLM {
|
|||
break;
|
||||
}
|
||||
}
|
||||
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
usage,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
495
core/llm/llms/Anthropic.vitest.ts
Normal file
495
core/llm/llms/Anthropic.vitest.ts
Normal file
|
|
@ -0,0 +1,495 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../index.js";
|
||||
import Anthropic from "./Anthropic.js";
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("Anthropic", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "hello" }],
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chat should send a valid request", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "hello" }],
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamComplete should send a valid request", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Complete this: Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "Complete this: Hello" }],
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("complete should send a valid request", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "complete",
|
||||
params: ["Complete this: Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "Complete this: Hello" }],
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
describe("Different configurations", () => {
|
||||
test("should handle system message", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{ role: "user", content: "Hello!" },
|
||||
],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "Hello!" }],
|
||||
},
|
||||
],
|
||||
system: "You are a helpful assistant.",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle tool calls", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
const tools = [
|
||||
{
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "get_weather",
|
||||
description: "Get the current weather",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "What's the weather in New York?" }],
|
||||
new AbortController().signal,
|
||||
{ tools },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 8192,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "What's the weather in New York?" },
|
||||
],
|
||||
},
|
||||
],
|
||||
tools: [
|
||||
{
|
||||
name: "get_weather",
|
||||
description: "Get the current weather",
|
||||
input_schema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_start", "content_block": {"type": "tool_use", "id": "toolu_123", "name": "get_weather"}}',
|
||||
'{"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": "{\\"location\\": \\"New York\\""}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle custom max tokens", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "test-api-key",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
{ maxTokens: 1000 },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
max_tokens: 1000,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "text", text: "hello" }],
|
||||
},
|
||||
],
|
||||
system: "",
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello!"}}',
|
||||
'{"type": "content_block_stop"}',
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Error handling", () => {
|
||||
test("should throw error when API key is missing", async () => {
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: "",
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
apiBase: "https://api.anthropic.com/v1/",
|
||||
});
|
||||
|
||||
await expect(
|
||||
runLlmTest({
|
||||
llm: anthropic,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.anthropic.com/v1/messages",
|
||||
method: "POST",
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -17,7 +17,7 @@ import OpenAI from "./OpenAI.js";
|
|||
class Docker extends OpenAI implements ModelInstaller {
|
||||
static providerName = "docker";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:12434/engines/v1",
|
||||
apiBase: "http://localhost:12434/engines/v1/",
|
||||
model: "gemma3-4B-F4", // Default model
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import OpenAI from "./OpenAI.js";
|
|||
class Fireworks extends OpenAI {
|
||||
static providerName = "fireworks";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.fireworks.ai/inference/v1",
|
||||
apiBase: "https://api.fireworks.ai/inference/v1/",
|
||||
};
|
||||
|
||||
private static modelConversion: { [key: string]: string } = {
|
||||
|
|
|
|||
12
core/llm/llms/Fireworks.vitest.ts
Normal file
12
core/llm/llms/Fireworks.vitest.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import Fireworks from "./Fireworks.js";
|
||||
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
|
||||
|
||||
createOpenAISubclassTests(Fireworks, {
|
||||
providerName: "fireworks",
|
||||
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
|
||||
modelConversions: {
|
||||
"starcoder-7b": "accounts/fireworks/models/starcoder-7b",
|
||||
},
|
||||
modelConversionContent:
|
||||
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
|
||||
});
|
||||
12
core/llm/llms/Groq.vitest.ts
Normal file
12
core/llm/llms/Groq.vitest.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
|
||||
import Groq from "./Groq.js";
|
||||
|
||||
createOpenAISubclassTests(Groq, {
|
||||
providerName: "groq",
|
||||
defaultApiBase: "https://api.groq.com/openai/v1/",
|
||||
modelConversions: {
|
||||
"mistral-8x7b": "mixtral-8x7b-32768",
|
||||
"llama3-8b": "llama3-8b-8192",
|
||||
"llama3-70b": "llama3-70b-8192",
|
||||
},
|
||||
});
|
||||
|
|
@ -5,7 +5,7 @@ import OpenAI from "./OpenAI";
|
|||
class Kindo extends OpenAI {
|
||||
static providerName = "kindo";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://llm.kindo.ai/v1",
|
||||
apiBase: "https://llm.kindo.ai/v1/",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
"kindo-token-transaction-type": "CONTINUE",
|
||||
|
|
|
|||
|
|
@ -6,9 +6,9 @@ import OpenAI from "./OpenAI.js";
|
|||
class NCompass extends OpenAI {
|
||||
static providerName = "ncompass";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.ncompass.tech/v1",
|
||||
apiBase: "https://api.ncompass.tech/v1/",
|
||||
};
|
||||
static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings";
|
||||
static embeddingsApiEndpoint = "https://api.gcp.ncompass.tech/v1/embeddings";
|
||||
|
||||
private static modelConversion: { [key: string]: string } = {
|
||||
"qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct",
|
||||
|
|
|
|||
294
core/llm/llms/OpenAI-compatible-core.vitest.ts
Normal file
294
core/llm/llms/OpenAI-compatible-core.vitest.ts
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
|
||||
|
||||
// Import core OpenAI-compatible providers
|
||||
import OpenAI from "./OpenAI.js";
|
||||
import Groq from "./Groq.js";
|
||||
import Fireworks from "./Fireworks.js";
|
||||
import Together from "./Together.js";
|
||||
import Deepseek from "./Deepseek.js";
|
||||
import OpenRouter from "./OpenRouter.js";
|
||||
import xAI from "./xAI.js";
|
||||
import Mistral from "./Mistral.js";
|
||||
import LMStudio from "./LMStudio.js";
|
||||
import Cerebras from "./Cerebras.js";
|
||||
import DeepInfra from "./DeepInfra.js";
|
||||
import Nvidia from "./Nvidia.js";
|
||||
|
||||
// Base OpenAI tests
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../index.js";
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
// Disable OpenAI adapter to use our custom fetch mock
|
||||
(llm as any).useOpenAIAdapterFor = [];
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("OpenAI", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Core OpenAI-compatible providers
|
||||
createOpenAISubclassTests(Groq, {
|
||||
providerName: "groq",
|
||||
defaultApiBase: "https://api.groq.com/openai/v1/",
|
||||
modelConversions: {
|
||||
"mistral-8x7b": "mistral-8x7b",
|
||||
"llama3-8b": "llama3-8b-8192",
|
||||
},
|
||||
modelConversionContent: "[INST] hello [/INST]",
|
||||
modelConversionMaxTokens: 4096,
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Fireworks, {
|
||||
providerName: "fireworks",
|
||||
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
|
||||
modelConversions: {
|
||||
"starcoder-7b": "starcoder-7b",
|
||||
},
|
||||
modelConversionContent:
|
||||
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Together, {
|
||||
providerName: "together",
|
||||
defaultApiBase: "https://api.together.xyz/v1/",
|
||||
modelConversions: {
|
||||
"codellama-7b": "codellama-7b",
|
||||
"llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
customStreamCompleteEndpoint: "completions",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Deepseek, {
|
||||
providerName: "deepseek",
|
||||
defaultApiBase: "https://api.deepseek.com/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(OpenRouter, {
|
||||
providerName: "openrouter",
|
||||
defaultApiBase: "https://openrouter.ai/api/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(xAI, {
|
||||
providerName: "xAI",
|
||||
defaultApiBase: "https://api.x.ai/v1/",
|
||||
modelConversions: {
|
||||
"grok-beta": "grok-beta",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Mistral, {
|
||||
providerName: "mistral",
|
||||
defaultApiBase: "https://api.mistral.ai/v1/",
|
||||
modelConversions: {
|
||||
"mistral-7b": "mistral-7b",
|
||||
"mistral-8x7b": "open-mixtral-8x7b",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(LMStudio, {
|
||||
providerName: "lmstudio",
|
||||
defaultApiBase: "http://localhost:1234/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Cerebras, {
|
||||
providerName: "cerebras",
|
||||
defaultApiBase: "https://api.cerebras.ai/v1/",
|
||||
modelConversions: {
|
||||
"llama3.1-8b": "llama3.1-8b",
|
||||
"llama3.1-70b": "llama3.1-70b",
|
||||
},
|
||||
modelConversionContent:
|
||||
"<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(DeepInfra, {
|
||||
providerName: "deepinfra",
|
||||
defaultApiBase: "https://api.deepinfra.com/v1/openai/",
|
||||
customEmbeddingsUrl:
|
||||
"https://api.deepinfra.com/v1/inference/text-embedding-ada-002",
|
||||
customEmbeddingsHeaders: {
|
||||
Authorization: "bearer test-api-key",
|
||||
},
|
||||
customEmbeddingsBody: {
|
||||
inputs: ["Hello", "World"],
|
||||
},
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Nvidia, {
|
||||
providerName: "nvidia",
|
||||
defaultApiBase: "https://integrate.api.nvidia.com/v1/",
|
||||
customEmbeddingsHeaders: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
customEmbeddingsBody: {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
input_type: "passage",
|
||||
truncate: "END",
|
||||
},
|
||||
});
|
||||
453
core/llm/llms/OpenAI-compatible.vitest.ts
Normal file
453
core/llm/llms/OpenAI-compatible.vitest.ts
Normal file
|
|
@ -0,0 +1,453 @@
|
|||
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
|
||||
|
||||
// Import all OpenAI-compatible providers
|
||||
import OpenAI from "./OpenAI.js";
|
||||
import Groq from "./Groq.js";
|
||||
import Fireworks from "./Fireworks.js";
|
||||
import Together from "./Together.js";
|
||||
import Deepseek from "./Deepseek.js";
|
||||
import OpenRouter from "./OpenRouter.js";
|
||||
import xAI from "./xAI.js";
|
||||
import Mistral from "./Mistral.js";
|
||||
import LMStudio from "./LMStudio.js";
|
||||
import Cerebras from "./Cerebras.js";
|
||||
import DeepInfra from "./DeepInfra.js";
|
||||
import Nvidia from "./Nvidia.js";
|
||||
import SambaNova from "./SambaNova.js";
|
||||
import Scaleway from "./Scaleway.js";
|
||||
import Venice from "./Venice.js";
|
||||
import Moonshot from "./Moonshot.js";
|
||||
import Novita from "./Novita.js";
|
||||
import SiliconFlow from "./SiliconFlow.js";
|
||||
import Kindo from "./Kindo.js";
|
||||
import Azure from "./Azure.js";
|
||||
import Inception from "./Inception.js";
|
||||
import Docker from "./Docker.js";
|
||||
import Voyage from "./Voyage.js";
|
||||
import Vllm from "./Vllm.js";
|
||||
import TextGenWebUI from "./TextGenWebUI.js";
|
||||
// import Relace from "./Relace.js"; // Skip - causing import issues
|
||||
import FunctionNetwork from "./FunctionNetwork.js";
|
||||
import NCompass from "./NCompass.js";
|
||||
import LlamaStack from "./LlamaStack.js";
|
||||
import Nebius from "./Nebius.js";
|
||||
import OVHcloud from "./OVHcloud.js";
|
||||
|
||||
// Base OpenAI tests
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../index.js";
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
// Disable OpenAI adapter to use our custom fetch mock
|
||||
(llm as any).useOpenAIAdapterFor = [];
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("OpenAI", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle embeddings", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "text-embedding-ada-002",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "embed",
|
||||
params: [["Hello", "World"]],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// OpenAI-compatible providers
|
||||
createOpenAISubclassTests(Groq, {
|
||||
providerName: "groq",
|
||||
defaultApiBase: "https://api.groq.com/openai/v1/",
|
||||
modelConversions: {
|
||||
"mistral-8x7b": "mixtral-8x7b-32768",
|
||||
"llama3-8b": "llama3-8b-8192",
|
||||
"llama3-70b": "llama3-70b-8192",
|
||||
},
|
||||
modelConversionContent: "[INST] hello [/INST]",
|
||||
modelConversionMaxTokens: 4096,
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Fireworks, {
|
||||
providerName: "fireworks",
|
||||
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
|
||||
modelConversions: {
|
||||
"starcoder-7b": "accounts/fireworks/models/starcoder-7b",
|
||||
},
|
||||
modelConversionContent:
|
||||
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Together, {
|
||||
providerName: "together",
|
||||
defaultApiBase: "https://api.together.xyz/v1/",
|
||||
modelConversions: {
|
||||
"codellama-7b": "codellama-7b",
|
||||
"llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
|
||||
"mistral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
customStreamCompleteEndpoint: "completions",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Deepseek, {
|
||||
providerName: "deepseek",
|
||||
defaultApiBase: "https://api.deepseek.com/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(OpenRouter, {
|
||||
providerName: "openrouter",
|
||||
defaultApiBase: "https://openrouter.ai/api/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(xAI, {
|
||||
providerName: "xAI",
|
||||
defaultApiBase: "https://api.x.ai/v1/",
|
||||
modelConversions: {
|
||||
"grok-beta": "grok-beta",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Mistral, {
|
||||
providerName: "mistral",
|
||||
defaultApiBase: "https://api.mistral.ai/v1/",
|
||||
modelConversions: {
|
||||
"mistral-7b": "mistral-7b",
|
||||
"mistral-8x7b": "open-mixtral-8x7b",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(LMStudio, {
|
||||
providerName: "lmstudio",
|
||||
defaultApiBase: "http://localhost:1234/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Cerebras, {
|
||||
providerName: "cerebras",
|
||||
defaultApiBase: "https://api.cerebras.ai/v1/",
|
||||
modelConversions: {
|
||||
"llama3.1-8b": "llama3.1-8b",
|
||||
"llama3.1-70b": "llama3.1-70b",
|
||||
},
|
||||
modelConversionContent:
|
||||
"<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(DeepInfra, {
|
||||
providerName: "deepinfra",
|
||||
defaultApiBase: "https://api.deepinfra.com/v1/openai/",
|
||||
customEmbeddingsUrl:
|
||||
"https://api.deepinfra.com/v1/inference/text-embedding-ada-002",
|
||||
customEmbeddingsHeaders: {
|
||||
Authorization: "bearer test-api-key",
|
||||
},
|
||||
customEmbeddingsBody: {
|
||||
inputs: ["Hello", "World"],
|
||||
},
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Nvidia, {
|
||||
providerName: "nvidia",
|
||||
defaultApiBase: "https://integrate.api.nvidia.com/v1/",
|
||||
customEmbeddingsHeaders: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
customEmbeddingsBody: {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
input_type: "passage",
|
||||
truncate: "END",
|
||||
},
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(SambaNova, {
|
||||
providerName: "sambanova",
|
||||
defaultApiBase: "https://api.sambanova.ai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Scaleway, {
|
||||
providerName: "scaleway",
|
||||
defaultApiBase: "https://api.scaleway.ai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Venice, {
|
||||
providerName: "venice",
|
||||
defaultApiBase: "https://api.venice.ai/api/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Moonshot, {
|
||||
providerName: "moonshot",
|
||||
defaultApiBase: "https://api.moonshot.cn/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Novita, {
|
||||
providerName: "novita",
|
||||
defaultApiBase: "https://api.novita.ai/v3/openai/",
|
||||
customStreamCompleteEndpoint: "completions",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(SiliconFlow, {
|
||||
providerName: "siliconflow",
|
||||
defaultApiBase: "https://api.siliconflow.cn/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Kindo, {
|
||||
providerName: "kindo",
|
||||
defaultApiBase: "https://llm.kindo.ai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Azure, {
|
||||
providerName: "azure",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Inception, {
|
||||
providerName: "inception",
|
||||
defaultApiBase: "https://api.inceptionlabs.ai/v1/",
|
||||
customBodyOptions: {
|
||||
temperature: 0.0,
|
||||
presence_penalty: 1.5,
|
||||
stop: ["<|endoftext|>"],
|
||||
},
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Docker, {
|
||||
providerName: "docker",
|
||||
defaultApiBase: "http://localhost:12434/engines/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Voyage, {
|
||||
providerName: "voyage",
|
||||
defaultApiBase: "https://api.voyageai.com/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Vllm, {
|
||||
providerName: "vllm",
|
||||
defaultApiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(TextGenWebUI, {
|
||||
providerName: "text-gen-webui",
|
||||
defaultApiBase: "http://localhost:5000/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(FunctionNetwork, {
|
||||
providerName: "function-network",
|
||||
defaultApiBase: "https://api.function.network/v1/",
|
||||
customEmbeddingsHeaders: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(NCompass, {
|
||||
providerName: "ncompass",
|
||||
defaultApiBase: "https://api.ncompass.tech/v1/",
|
||||
customEmbeddingsUrl: "https://api.gcp.ncompass.tech/v1/embeddings",
|
||||
customEmbeddingsHeaders: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
customEmbeddingsBody: {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
},
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(LlamaStack, {
|
||||
providerName: "llamastack",
|
||||
defaultApiBase: "http://localhost:8321/v1/openai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(Nebius, {
|
||||
providerName: "nebius",
|
||||
defaultApiBase: "https://api.studio.nebius.ai/v1/",
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(OVHcloud, {
|
||||
providerName: "ovhcloud",
|
||||
defaultApiBase: "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
|
||||
});
|
||||
427
core/llm/llms/OpenAI.vitest.ts
Normal file
427
core/llm/llms/OpenAI.vitest.ts
Normal file
|
|
@ -0,0 +1,427 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../index.js";
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
// Disable OpenAI adapter to use our custom fetch mock
|
||||
(llm as any).useOpenAIAdapterFor = [];
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("OpenAI", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chat should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamComplete should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "Hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("complete should send a valid request", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "complete",
|
||||
params: ["Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "Hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle O1 models correctly", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "o1-preview",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
{ maxTokens: 100 },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "o1-preview",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_completion_tokens: 100,
|
||||
},
|
||||
},
|
||||
mockStream: [{ choices: [{ delta: { content: "Hello world" } }] }],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle tools", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
const tools = [
|
||||
{
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "test_function",
|
||||
description: "Test function",
|
||||
parameters: { type: "object", properties: {} },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
{ tools },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_function",
|
||||
description: "Test function",
|
||||
parameters: { type: "object", properties: {} },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
mockStream: [{ choices: [{ delta: { content: "I'll help you" } }] }],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle custom max tokens", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
{ maxTokens: 500 },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 500,
|
||||
},
|
||||
},
|
||||
mockStream: [{ choices: [{ delta: { content: "Hello" } }] }],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle embeddings", async () => {
|
||||
const openai = new OpenAI({
|
||||
apiKey: "test-api-key",
|
||||
model: "text-embedding-ada-002",
|
||||
apiBase: "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: openai,
|
||||
methodToTest: "embed",
|
||||
params: [["Hello", "World"]],
|
||||
expectedRequest: {
|
||||
url: "https://api.openai.com/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -6,7 +6,7 @@ import OpenAI from "./OpenAI";
|
|||
class Venice extends OpenAI {
|
||||
static providerName = "venice";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.venice.ai/api/v1",
|
||||
apiBase: "https://api.venice.ai/api/v1/",
|
||||
};
|
||||
|
||||
protected _convertArgs(
|
||||
|
|
|
|||
93
core/llm/llms/llmTestHarness.ts
Normal file
93
core/llm/llms/llmTestHarness.ts
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import { expect, jest } from "@jest/globals";
|
||||
import { ILLM } from "../../index.js";
|
||||
|
||||
export interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: string[]; // array of string chunks for SSE
|
||||
}
|
||||
|
||||
export async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = jest.fn<any>();
|
||||
|
||||
if (mockStream) {
|
||||
const encoder = new TextEncoder();
|
||||
let streamIndex = 0;
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
mockStream.forEach((chunk) => {
|
||||
controller.enqueue(new TextEncoder().encode(chunk));
|
||||
});
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
llm.fetch = mockFetch;
|
||||
|
||||
// @ts-ignore
|
||||
if (typeof llm[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
const result = await llm[methodToTest](...params);
|
||||
|
||||
if (mockStream) {
|
||||
// Consume the stream to ensure it's processed correctly
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0] as [string, RequestInit];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(expectedRequest.headers);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
758
core/llm/llms/stubs/ContinueProxy.vitest.ts
Normal file
758
core/llm/llms/stubs/ContinueProxy.vitest.ts
Normal file
|
|
@ -0,0 +1,758 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../../index.js";
|
||||
import ContinueProxy from "./ContinueProxy.js";
|
||||
|
||||
vi.mock("@continuedev/config-yaml", async (importOriginal) => {
|
||||
const mod = (await importOriginal()) as any;
|
||||
return {
|
||||
...mod,
|
||||
parseProxyModelName: vi.fn(() => ({
|
||||
provider: "test-provider",
|
||||
model: "test-model",
|
||||
ownerSlug: "test-owner",
|
||||
packageSlug: "test-package",
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
describe("ContinueProxy", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("rerank should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "rerank",
|
||||
params: [
|
||||
"test query",
|
||||
[{ content: "document1" }, { content: "document2" }],
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
query: "test query",
|
||||
documents: ["document1", "document2"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [
|
||||
{ index: 0, relevance_score: 0.9 },
|
||||
{ index: 1, relevance_score: 0.1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamChat",
|
||||
params: [[{ role: "user", content: "hello" }]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "response"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chat should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "chat",
|
||||
params: [[{ role: "user", content: "hello" }]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "Hello! How can I help you today?"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamComplete should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Complete this: Hello"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "Complete this: Hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": " world!"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("complete should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "complete",
|
||||
params: ["Complete this: Hello"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "Complete this: Hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": " world!"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamFim should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamFim",
|
||||
params: ["function test() {\n ", "\n}"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"x-api-key": "test-api-key",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
prompt: "function test() {\n ",
|
||||
suffix: "\n}",
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "console.log("Hello");"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("embed should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "embed",
|
||||
params: [["text to embed", "another text"]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["text to embed", "another text"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("listModels should send a valid request", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "listModels",
|
||||
params: [],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/models",
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
describe("Different provider configurations", () => {
|
||||
test("should handle on-prem proxy URL", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
onPremProxyUrl: "https://my-proxy.company.com/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "rerank",
|
||||
params: [
|
||||
"test query",
|
||||
[{ content: "document1" }, { content: "document2" }],
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://my-proxy.company.com/model-proxy/v1/rerank",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
query: "test query",
|
||||
documents: ["document1", "document2"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: undefined,
|
||||
apiKeyLocation: undefined,
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [
|
||||
{ index: 0, relevance_score: 0.9 },
|
||||
{ index: 1, relevance_score: 0.1 },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle environment variables", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
env: {
|
||||
CUSTOM_VAR: "custom-value",
|
||||
ANOTHER_VAR: "another-value",
|
||||
},
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamChat",
|
||||
params: [[{ role: "user", content: "hello" }]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
env: {
|
||||
CUSTOM_VAR: "custom-value",
|
||||
ANOTHER_VAR: "another-value",
|
||||
},
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "response"}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle API key location", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: "env:OPENAI_API_KEY",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "embed",
|
||||
params: [["test text"]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["test text"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: "env:OPENAI_API_KEY",
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle env secret locations", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
envSecretLocations: {
|
||||
AZURE_API_KEY: "env:AZURE_API_KEY",
|
||||
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
|
||||
},
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamFim",
|
||||
params: ["const x = ", ";"],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"x-api-key": "test-api-key",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
prompt: "const x = ",
|
||||
suffix: ";",
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
envSecretLocations: {
|
||||
AZURE_API_KEY: "env:AZURE_API_KEY",
|
||||
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
|
||||
},
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: ['{"choices": [{"delta": {"content": "42"}}]}', "[DONE]"],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle organization scope ID", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: "org_12345",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "listModels",
|
||||
params: [],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/models",
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ id: "gpt-4" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Edge cases", () => {
|
||||
test("should handle empty chunks array for rerank", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "rerank",
|
||||
params: ["test query", []],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
},
|
||||
body: {
|
||||
query: "test query",
|
||||
documents: [],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: undefined,
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle complex chat messages", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
const complexMessages = [
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{ role: "user", content: "Hello!" },
|
||||
{ role: "assistant", content: "Hi there! How can I help you today?" },
|
||||
{ role: "user", content: "What's the weather like?" },
|
||||
];
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "streamChat",
|
||||
params: [complexMessages],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
"x-continue-unique-id": "NOT_UNIQUE",
|
||||
},
|
||||
body: {
|
||||
model: "test-model",
|
||||
messages: complexMessages,
|
||||
max_tokens: 4096,
|
||||
stream: true,
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"choices": [{"delta": {"content": "I don\'t have access to current weather data."}}]}',
|
||||
"[DONE]",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle single embedding chunk", async () => {
|
||||
const proxy = new ContinueProxy({
|
||||
apiKey: "test-api-key",
|
||||
model: "test-model",
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: proxy,
|
||||
methodToTest: "embed",
|
||||
params: [["single text"]],
|
||||
expectedRequest: {
|
||||
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
input: ["single text"],
|
||||
model: "test-model",
|
||||
continueProperties: {
|
||||
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
|
||||
apiKeyLocation: undefined,
|
||||
env: undefined,
|
||||
envSecretLocations: undefined,
|
||||
orgScopeId: null,
|
||||
},
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [{ embedding: [0.1, 0.2, 0.3] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
375
core/llm/llms/test-utils/openai-test-utils.ts
Normal file
375
core/llm/llms/test-utils/openai-test-utils.ts
Normal file
|
|
@ -0,0 +1,375 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../../index.js";
|
||||
import OpenAI from "../OpenAI.js";
|
||||
|
||||
interface LlmTestCase {
|
||||
llm: ILLM;
|
||||
methodToTest: keyof ILLM;
|
||||
params: any[];
|
||||
expectedRequest: {
|
||||
url: string;
|
||||
method: string;
|
||||
headers?: Record<string, string>;
|
||||
body?: Record<string, any>;
|
||||
};
|
||||
mockResponse?: any;
|
||||
mockStream?: any[];
|
||||
}
|
||||
|
||||
function createMockStream(mockStream: any[]) {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream({
|
||||
start(controller) {
|
||||
for (const chunk of mockStream) {
|
||||
controller.enqueue(
|
||||
encoder.encode(
|
||||
`data: ${
|
||||
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
|
||||
}\n\n`,
|
||||
),
|
||||
);
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
if (mockStream) {
|
||||
const stream = createMockStream(mockStream);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockResponse), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return mockFetch;
|
||||
}
|
||||
|
||||
function setupReadableStreamPolyfill() {
|
||||
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
|
||||
// @ts-ignore
|
||||
const originalFrom = ReadableStream.from;
|
||||
// @ts-ignore
|
||||
ReadableStream.from = (body) => {
|
||||
if (body?.source) {
|
||||
return body;
|
||||
}
|
||||
return originalFrom(body);
|
||||
};
|
||||
}
|
||||
|
||||
async function executeLlmMethod(
|
||||
llm: ILLM,
|
||||
methodToTest: keyof ILLM,
|
||||
params: any[],
|
||||
) {
|
||||
if (typeof (llm as any)[methodToTest] !== "function") {
|
||||
throw new Error(
|
||||
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await (llm as any)[methodToTest](...params);
|
||||
if (result?.next) {
|
||||
for await (const _ of result) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertFetchCall(mockFetch: any, expectedRequest: any) {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
|
||||
expect(url.toString()).toBe(expectedRequest.url);
|
||||
expect(options.method).toBe(expectedRequest.method);
|
||||
|
||||
if (expectedRequest.headers) {
|
||||
expect(options.headers).toEqual(
|
||||
expect.objectContaining(expectedRequest.headers),
|
||||
);
|
||||
}
|
||||
|
||||
if (expectedRequest.body) {
|
||||
const actualBody = JSON.parse(options.body as string);
|
||||
expect(actualBody).toEqual(expectedRequest.body);
|
||||
}
|
||||
}
|
||||
|
||||
async function runLlmTest(testCase: LlmTestCase) {
|
||||
const {
|
||||
llm,
|
||||
methodToTest,
|
||||
params,
|
||||
expectedRequest,
|
||||
mockResponse,
|
||||
mockStream,
|
||||
} = testCase;
|
||||
|
||||
const mockFetch = setupMockFetch(mockResponse, mockStream);
|
||||
setupReadableStreamPolyfill();
|
||||
|
||||
(llm as any).fetch = mockFetch;
|
||||
|
||||
// Disable OpenAI adapter to use our custom fetch mock
|
||||
(llm as any).useOpenAIAdapterFor = [];
|
||||
|
||||
await executeLlmMethod(llm, methodToTest, params);
|
||||
assertFetchCall(mockFetch, expectedRequest);
|
||||
}
|
||||
|
||||
export interface OpenAISubclassConfig {
|
||||
providerName: string;
|
||||
defaultApiBase?: string;
|
||||
modelConversions?: { [key: string]: string };
|
||||
customOptions?: any;
|
||||
modelConversionContent?: string;
|
||||
modelConversionMaxTokens?: number;
|
||||
customStreamCompleteEndpoint?: string;
|
||||
customEmbeddingsUrl?: string;
|
||||
customEmbeddingsHeaders?: { [key: string]: string };
|
||||
customEmbeddingsBody?: any;
|
||||
customBodyOptions?: any;
|
||||
}
|
||||
|
||||
function getExpectedUrl(
|
||||
config: OpenAISubclassConfig,
|
||||
endpoint: string,
|
||||
model: string = "gpt-4",
|
||||
) {
|
||||
let baseUrl = config.defaultApiBase || "https://api.openai.com/v1/";
|
||||
if (config.providerName === "azure") {
|
||||
return `${baseUrl}openai/deployments/${model}/${endpoint}?api-version=2023-07-01-preview`;
|
||||
} else if (config.providerName === "ncompass") {
|
||||
return `${baseUrl}${endpoint}`;
|
||||
}
|
||||
return `${baseUrl}${endpoint}`;
|
||||
}
|
||||
|
||||
export const createOpenAISubclassTests = (
|
||||
ProviderClass: typeof OpenAI,
|
||||
config: OpenAISubclassConfig,
|
||||
) => {
|
||||
describe(config.providerName, () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("should have correct provider name", () => {
|
||||
expect(ProviderClass.providerName).toBe(config.providerName);
|
||||
});
|
||||
|
||||
if (config.defaultApiBase) {
|
||||
test("should have correct default API base", () => {
|
||||
expect(ProviderClass.defaultOptions?.apiBase).toBe(
|
||||
config.defaultApiBase,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: getExpectedUrl(config, "chat/completions"),
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
...config.customBodyOptions,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chat should send a valid request", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: getExpectedUrl(config, "chat/completions"),
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
...config.customBodyOptions,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamComplete should send a valid request", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: getExpectedUrl(
|
||||
config,
|
||||
config.customStreamCompleteEndpoint || "chat/completions",
|
||||
),
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body:
|
||||
config.customStreamCompleteEndpoint === "completions"
|
||||
? {
|
||||
model: "gpt-4",
|
||||
prompt: "Hello",
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
...config.customBodyOptions,
|
||||
}
|
||||
: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "Hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
...config.customBodyOptions,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("complete should send a valid request", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "gpt-4",
|
||||
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "complete",
|
||||
params: ["Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: getExpectedUrl(config, "chat/completions"),
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-api-key",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: {
|
||||
model: "gpt-4",
|
||||
messages: [{ role: "user", content: "Hello" }],
|
||||
stream: true,
|
||||
max_tokens: 2048,
|
||||
...config.customBodyOptions,
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
{ choices: [{ delta: { content: "Hello" } }] },
|
||||
{ choices: [{ delta: { content: " world" } }] },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle embeddings", async () => {
|
||||
const provider = new ProviderClass({
|
||||
apiKey: "test-api-key",
|
||||
model: "text-embedding-ada-002",
|
||||
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
|
||||
});
|
||||
|
||||
// Skip test if provider doesn't support embeddings (e.g., ncompass with undefined endpoint)
|
||||
if (config.providerName === "ncompass" && !config.customEmbeddingsUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
await runLlmTest({
|
||||
llm: provider,
|
||||
methodToTest: "embed",
|
||||
params: [["Hello", "World"]],
|
||||
expectedRequest: {
|
||||
url:
|
||||
config.customEmbeddingsUrl ||
|
||||
`${config.defaultApiBase || "https://api.openai.com/v1/"}embeddings`,
|
||||
method: "POST",
|
||||
headers: config.customEmbeddingsHeaders || {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
"api-key": "test-api-key",
|
||||
},
|
||||
body: config.customEmbeddingsBody || {
|
||||
input: ["Hello", "World"],
|
||||
model: "text-embedding-ada-002",
|
||||
},
|
||||
},
|
||||
mockResponse: {
|
||||
data: [
|
||||
{ embedding: [0.1, 0.2, 0.3] },
|
||||
{ embedding: [0.4, 0.5, 0.6] },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
|
@ -44,6 +44,7 @@ describe("LLMLogFormatter", () => {
|
|||
content: "You are a helpful assistant",
|
||||
},
|
||||
],
|
||||
provider: "watsonx",
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
|
|
@ -79,6 +80,7 @@ describe("LLMLogFormatter", () => {
|
|||
promptTokens: 10,
|
||||
generatedTokens: 20,
|
||||
thinkingTokens: 0,
|
||||
usage: undefined,
|
||||
});
|
||||
|
||||
expect(output.getText()).toBe(
|
||||
|
|
@ -113,6 +115,7 @@ describe("LLMLogFormatter", () => {
|
|||
model: "granite3.2-dense:8b",
|
||||
},
|
||||
prompt: "A horse is a horse",
|
||||
provider: "watsonx",
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
|
|
@ -149,6 +152,7 @@ describe("LLMLogFormatter", () => {
|
|||
},
|
||||
prefix: "A\nB",
|
||||
suffix: "D\nE",
|
||||
provider: "watsonx",
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "1",
|
||||
|
|
@ -225,6 +229,7 @@ describe("LLMLogFormatter", () => {
|
|||
promptTokens: 10,
|
||||
generatedTokens: 20,
|
||||
thinkingTokens: 0,
|
||||
usage: undefined,
|
||||
});
|
||||
logger._logItem({
|
||||
interactionId: "3",
|
||||
|
|
|
|||
181
core/llm/utils/calculateRequestCost.ts
Normal file
181
core/llm/utils/calculateRequestCost.ts
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
import { Usage } from "../..";
|
||||
|
||||
export interface CostBreakdown {
|
||||
cost: number;
|
||||
breakdown: string;
|
||||
}
|
||||
|
||||
function calculateAnthropicCost(
|
||||
model: string,
|
||||
usage: Usage,
|
||||
): CostBreakdown | null {
|
||||
// Normalize model name to handle various formats
|
||||
const normalizedModel = model.toLowerCase();
|
||||
|
||||
// Define pricing per million tokens (MTok)
|
||||
const pricing: Record<
|
||||
string,
|
||||
{ input: number; output: number; cacheWrite: number; cacheRead: number }
|
||||
> = {
|
||||
// Claude Opus 4 (most intelligent model)
|
||||
"claude-3-opus": {
|
||||
input: 15,
|
||||
output: 75,
|
||||
cacheWrite: 18.75,
|
||||
cacheRead: 1.5,
|
||||
},
|
||||
"claude-3-opus-20240229": {
|
||||
input: 15,
|
||||
output: 75,
|
||||
cacheWrite: 18.75,
|
||||
cacheRead: 1.5,
|
||||
},
|
||||
|
||||
// Claude Sonnet 4 (optimal balance)
|
||||
"claude-3-5-sonnet": {
|
||||
input: 3,
|
||||
output: 15,
|
||||
cacheWrite: 3.75,
|
||||
cacheRead: 0.3,
|
||||
},
|
||||
"claude-3-5-sonnet-20241022": {
|
||||
input: 3,
|
||||
output: 15,
|
||||
cacheWrite: 3.75,
|
||||
cacheRead: 0.3,
|
||||
},
|
||||
"claude-3-5-sonnet-20240620": {
|
||||
input: 3,
|
||||
output: 15,
|
||||
cacheWrite: 3.75,
|
||||
cacheRead: 0.3,
|
||||
},
|
||||
|
||||
// Claude Haiku 3.5 (fastest, most cost-effective)
|
||||
"claude-3-5-haiku": {
|
||||
input: 0.8,
|
||||
output: 4,
|
||||
cacheWrite: 1,
|
||||
cacheRead: 0.08,
|
||||
},
|
||||
"claude-3-5-haiku-20241022": {
|
||||
input: 0.8,
|
||||
output: 4,
|
||||
cacheWrite: 1,
|
||||
cacheRead: 0.08,
|
||||
},
|
||||
|
||||
// Legacy Claude 3 Haiku
|
||||
"claude-3-haiku": {
|
||||
input: 0.25,
|
||||
output: 1.25,
|
||||
cacheWrite: 0.3,
|
||||
cacheRead: 0.03,
|
||||
},
|
||||
"claude-3-haiku-20240307": {
|
||||
input: 0.25,
|
||||
output: 1.25,
|
||||
cacheWrite: 0.3,
|
||||
cacheRead: 0.03,
|
||||
},
|
||||
};
|
||||
|
||||
// Find matching pricing model
|
||||
let modelPricing = pricing[normalizedModel];
|
||||
|
||||
// If exact match not found, try to find by partial match
|
||||
if (!modelPricing) {
|
||||
for (const [key, value] of Object.entries(pricing)) {
|
||||
if (normalizedModel.includes(key) || key.includes(normalizedModel)) {
|
||||
modelPricing = value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If still no match, try common patterns
|
||||
if (!modelPricing) {
|
||||
if (normalizedModel.includes("opus")) {
|
||||
modelPricing = pricing["claude-3-opus"];
|
||||
} else if (normalizedModel.includes("sonnet")) {
|
||||
modelPricing = pricing["claude-3-5-sonnet"];
|
||||
} else if (normalizedModel.includes("haiku")) {
|
||||
modelPricing = pricing["claude-3-5-haiku"];
|
||||
}
|
||||
}
|
||||
|
||||
if (!modelPricing) {
|
||||
return null; // Unknown model
|
||||
}
|
||||
|
||||
// Calculate costs
|
||||
const inputCost = (usage.promptTokens / 1_000_000) * modelPricing.input;
|
||||
const outputCost = (usage.completionTokens / 1_000_000) * modelPricing.output;
|
||||
|
||||
// Build breakdown components
|
||||
const breakdownParts: string[] = [];
|
||||
|
||||
// Input tokens breakdown
|
||||
if (usage.promptTokens > 0) {
|
||||
breakdownParts.push(
|
||||
`Input: ${usage.promptTokens.toLocaleString()} tokens × $${modelPricing.input}/MTok = $${inputCost.toFixed(6)}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Output tokens breakdown
|
||||
if (usage.completionTokens > 0) {
|
||||
breakdownParts.push(
|
||||
`Output: ${usage.completionTokens.toLocaleString()} tokens × $${modelPricing.output}/MTok = $${outputCost.toFixed(6)}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Handle prompt caching costs if available
|
||||
let cacheCost = 0;
|
||||
if (usage.promptTokensDetails) {
|
||||
const { cachedTokens, cacheWriteTokens } = usage.promptTokensDetails;
|
||||
|
||||
if (cacheWriteTokens && cacheWriteTokens > 0) {
|
||||
const cacheWriteCost =
|
||||
(cacheWriteTokens / 1_000_000) * modelPricing.cacheWrite;
|
||||
cacheCost += cacheWriteCost;
|
||||
breakdownParts.push(
|
||||
`Cache Write: ${cacheWriteTokens.toLocaleString()} tokens × $${modelPricing.cacheWrite}/MTok = $${cacheWriteCost.toFixed(6)}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (cachedTokens && cachedTokens > 0) {
|
||||
const cacheReadCost = (cachedTokens / 1_000_000) * modelPricing.cacheRead;
|
||||
cacheCost += cacheReadCost;
|
||||
breakdownParts.push(
|
||||
`Cache Read: ${cachedTokens.toLocaleString()} tokens × $${modelPricing.cacheRead}/MTok = $${cacheReadCost.toFixed(6)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const totalCost = inputCost + outputCost + cacheCost;
|
||||
|
||||
// Build final breakdown string
|
||||
let breakdown = `Model: ${model}\n`;
|
||||
breakdown += breakdownParts.join("\n");
|
||||
if (breakdownParts.length > 1) {
|
||||
breakdown += `\nTotal: $${totalCost.toFixed(6)}`;
|
||||
}
|
||||
|
||||
return {
|
||||
cost: totalCost,
|
||||
breakdown,
|
||||
};
|
||||
}
|
||||
|
||||
export function calculateRequestCost(
|
||||
provider: string,
|
||||
model: string,
|
||||
usage: Usage,
|
||||
): CostBreakdown | null {
|
||||
switch (provider) {
|
||||
case "anthropic":
|
||||
return calculateAnthropicCost(model, usage);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
3
core/package-lock.json
generated
3
core/package-lock.json
generated
|
|
@ -190,7 +190,8 @@
|
|||
"@types/json-schema": "^7.0.15",
|
||||
"cross-env": "^7.0.3",
|
||||
"ts-jest": "^29.2.3",
|
||||
"ts-node": "^10.9.2"
|
||||
"ts-node": "^10.9.2",
|
||||
"vitest": "^1.6.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
|
|
|
|||
|
|
@ -102,7 +102,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
),
|
||||
void,
|
||||
];
|
||||
"config/openProfile": [{ profileId: string | undefined }, void];
|
||||
"config/openProfile": [
|
||||
{ profileId: string | undefined; element?: { sourceFile?: string } },
|
||||
void,
|
||||
];
|
||||
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
|
||||
"config/updateSelectedModel": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import type {
|
|||
Problem,
|
||||
Range,
|
||||
RangeInFile,
|
||||
SignatureHelp,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
} from "../";
|
||||
|
|
@ -82,6 +83,8 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
getFileStats: [{ files: string[] }, FileStatsMap];
|
||||
|
||||
gotoDefinition: [{ location: Location }, RangeInFile[]];
|
||||
gotoTypeDefinition: [{ location: Location }, RangeInFile[]];
|
||||
getSignatureHelp: [{ location: Location }, SignatureHelp | null];
|
||||
|
||||
getControlPlaneSessionInfo: [
|
||||
{ silent: boolean; useOnboarding: boolean },
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import type {
|
|||
Problem,
|
||||
Range,
|
||||
RangeInFile,
|
||||
SignatureHelp,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
} from "../..";
|
||||
|
|
@ -45,6 +46,14 @@ export class MessageIde implements IDE {
|
|||
return this.request("gotoDefinition", { location });
|
||||
}
|
||||
|
||||
async gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
|
||||
return this.request("gotoTypeDefinition", { location });
|
||||
}
|
||||
|
||||
async getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
|
||||
return this.request("getSignatureHelp", { location });
|
||||
}
|
||||
|
||||
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
|
||||
this.on("didChangeActiveTextEditor", (data) => callback(data.filepath));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ export const createRuleBlock: Tool = {
|
|||
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.\n\nRule Types:\n- Always: Include only "rule" (always included in model context)\n- Auto Attached: Include "rule", "globs", and/or "regex" (included when files match patterns)\n- Agent Requested: Include "rule" and "description" (AI decides when to apply based on description)\n- Manual: Include only "rule" (only included when explicitly mentioned using @ruleName)',
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["name", "rule", "description"],
|
||||
required: ["name", "rule"],
|
||||
properties: {
|
||||
name: {
|
||||
type: "string",
|
||||
|
|
|
|||
|
|
@ -16,12 +16,11 @@ export const lsTool: Tool = {
|
|||
description: "List files and folders in a given directory",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["dirPath", "recursive"],
|
||||
properties: {
|
||||
dirPath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The directory path relative to the root of the project. Always use forward slash paths like '/'. rather than e.g. '.'",
|
||||
"The directory path relative to the root of the project. Use forward slash paths like '/'. rather than e.g. '.'",
|
||||
},
|
||||
recursive: {
|
||||
type: "boolean",
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ export function getPreferredShell(): string {
|
|||
}
|
||||
}
|
||||
|
||||
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`;
|
||||
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`;
|
||||
|
||||
export const runTerminalCommandTool: Tool = {
|
||||
type: "function",
|
||||
|
|
|
|||
|
|
@ -1,22 +1,15 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { RangeInFile } from "../..";
|
||||
import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
export const codebaseToolImpl: ToolImpl = async (args, extras) => {
|
||||
if (!args.query || args.query.trim() === "") {
|
||||
return [
|
||||
{
|
||||
name: "Error",
|
||||
description: "Codebase search error",
|
||||
content: "Query parameter is required and cannot be empty.",
|
||||
},
|
||||
];
|
||||
}
|
||||
const query = getStringArg(args, "query");
|
||||
|
||||
try {
|
||||
const contextExtras = {
|
||||
config: extras.config,
|
||||
fullInput: args.query,
|
||||
fullInput: query,
|
||||
embeddingsProvider: extras.config.selectedModelByRole.embed,
|
||||
reranker: extras.config.selectedModelByRole.rerank,
|
||||
llm: extras.llm,
|
||||
|
|
@ -39,7 +32,7 @@ export const codebaseToolImpl: ToolImpl = async (args, extras) => {
|
|||
{
|
||||
name: "No Results",
|
||||
description: "Codebase search",
|
||||
content: `No relevant code found for query: "${args.query}". This could mean:
|
||||
content: `No relevant code found for query: "${query}". This could mean:
|
||||
- The codebase hasn't been indexed yet
|
||||
- No code matches the search criteria
|
||||
- Embeddings provider is not configured
|
||||
|
|
|
|||
|
|
@ -2,20 +2,24 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
|
|||
|
||||
import { ToolImpl } from ".";
|
||||
import { getCleanUriPath, getUriPathBasename } from "../../util/uri";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
export const createNewFileImpl: ToolImpl = async (args, extras) => {
|
||||
const filepath = getStringArg(args, "filepath");
|
||||
const contents = getStringArg(args, "contents", true);
|
||||
|
||||
const resolvedFileUri = await inferResolvedUriFromRelativePath(
|
||||
args.filepath,
|
||||
filepath,
|
||||
extras.ide,
|
||||
);
|
||||
if (resolvedFileUri) {
|
||||
const exists = await extras.ide.fileExists(resolvedFileUri);
|
||||
if (exists) {
|
||||
throw new Error(
|
||||
`File ${args.filepath} already exists. Use the edit tool to edit this file`,
|
||||
`File ${filepath} already exists. Use the edit tool to edit this file`,
|
||||
);
|
||||
}
|
||||
await extras.ide.writeFile(resolvedFileUri, args.contents);
|
||||
await extras.ide.writeFile(resolvedFileUri, contents);
|
||||
await extras.ide.openFile(resolvedFileUri);
|
||||
await extras.ide.saveFile(resolvedFileUri);
|
||||
if (extras.codeBaseIndexer) {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,11 @@ import { createRuleMarkdown } from "@continuedev/config-yaml";
|
|||
import { ToolImpl } from ".";
|
||||
import { RuleWithSource } from "../..";
|
||||
import { createRuleFilePath } from "../../config/markdown/utils";
|
||||
import {
|
||||
getBooleanArg,
|
||||
getOptionalStringArg,
|
||||
getStringArg,
|
||||
} from "../parseArgs";
|
||||
|
||||
export type CreateRuleBlockArgs = Pick<
|
||||
Required<RuleWithSource>,
|
||||
|
|
@ -9,11 +14,21 @@ export type CreateRuleBlockArgs = Pick<
|
|||
> &
|
||||
Pick<RuleWithSource, "globs" | "regex" | "description" | "alwaysApply">;
|
||||
|
||||
export const createRuleBlockImpl: ToolImpl = async (
|
||||
{ name, rule, ...otherArgs }: CreateRuleBlockArgs,
|
||||
extras,
|
||||
) => {
|
||||
const fileContent = createRuleMarkdown(name, rule, otherArgs);
|
||||
export const createRuleBlockImpl: ToolImpl = async (args, extras) => {
|
||||
const name = getStringArg(args, "name");
|
||||
const rule = getStringArg(args, "rule");
|
||||
|
||||
const description = getOptionalStringArg(args, "description");
|
||||
const regex = getOptionalStringArg(args, "regex");
|
||||
const globs = getOptionalStringArg(args, "globs");
|
||||
const alwaysApply = getBooleanArg(args, "alwaysApply", false);
|
||||
|
||||
const fileContent = createRuleMarkdown(name, rule, {
|
||||
alwaysApply,
|
||||
description,
|
||||
globs,
|
||||
regex,
|
||||
});
|
||||
|
||||
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
|
||||
const ruleFilePath = createRuleFilePath(localContinueDir, name);
|
||||
|
|
@ -24,7 +39,7 @@ export const createRuleBlockImpl: ToolImpl = async (
|
|||
return [
|
||||
{
|
||||
name: "New Rule Block",
|
||||
description: otherArgs.description || "",
|
||||
description: description || "",
|
||||
uri: {
|
||||
type: "file",
|
||||
value: ruleFilePath,
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
|
||||
|
||||
export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
|
||||
const contextItems = await getUrlContextItems(args.url, extras.fetch);
|
||||
const url = getStringArg(args, "url");
|
||||
|
||||
const contextItems = await getUrlContextItems(url, extras.fetch);
|
||||
|
||||
// Track truncated content
|
||||
const truncatedUrls: string[] = [];
|
||||
|
|
@ -12,7 +15,7 @@ export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
|
|||
// Check and truncate each context item
|
||||
const processedItems = contextItems.map((item) => {
|
||||
if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) {
|
||||
truncatedUrls.push(args.url);
|
||||
truncatedUrls.push(url);
|
||||
return {
|
||||
...item,
|
||||
content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT),
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { ContextItem } from "../..";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
const MAX_AGENT_GLOB_RESULTS = 100;
|
||||
|
||||
export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const pattern = getStringArg(args, "pattern");
|
||||
const results = await extras.ide.getFileResults(
|
||||
args.pattern,
|
||||
pattern,
|
||||
MAX_AGENT_GLOB_RESULTS,
|
||||
);
|
||||
const contextItems: ContextItem[] = [
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { ContextItem } from "../..";
|
||||
import { formatGrepSearchResults } from "../../util/grepSearch";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
|
||||
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
|
||||
|
|
@ -41,8 +42,10 @@ function splitGrepResultsByFile(content: string): ContextItem[] {
|
|||
}
|
||||
|
||||
export const grepSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const query = getStringArg(args, "query");
|
||||
|
||||
const results = await extras.ide.getSearchResults(
|
||||
args.query,
|
||||
query,
|
||||
DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
|
||||
);
|
||||
const { formatted, numResults, truncated } = formatGrepSearchResults(
|
||||
|
|
@ -63,7 +66,7 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => {
|
|||
|
||||
let contextItems: ContextItem[] = [];
|
||||
|
||||
const splitByFile: boolean = args.splitByFile || false;
|
||||
const splitByFile: boolean = args?.splitByFile || false;
|
||||
if (splitByFile) {
|
||||
contextItems = splitGrepResultsByFile(formatted);
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -2,28 +2,28 @@ import { resolveRelativePathInDir } from "../../util/ideUtils";
|
|||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
|
||||
|
||||
export const readFileImpl: ToolImpl = async (args, extras) => {
|
||||
const firstUriMatch = await resolveRelativePathInDir(
|
||||
args.filepath,
|
||||
extras.ide,
|
||||
);
|
||||
const filepath = getStringArg(args, "filepath");
|
||||
|
||||
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
|
||||
if (!firstUriMatch) {
|
||||
throw new Error(`Could not find file ${args.filepath}`);
|
||||
throw new Error(`Could not find file ${filepath}`);
|
||||
}
|
||||
const content = await extras.ide.readFile(firstUriMatch);
|
||||
|
||||
await throwIfFileExceedsHalfOfContext(
|
||||
args.filepath,
|
||||
filepath,
|
||||
content,
|
||||
extras.config.selectedModelByRole.chat,
|
||||
);
|
||||
|
||||
return [
|
||||
{
|
||||
name: getUriPathBasename(args.filepath),
|
||||
description: args.filepath,
|
||||
name: getUriPathBasename(firstUriMatch),
|
||||
description: filepath,
|
||||
content,
|
||||
uri: {
|
||||
type: "file",
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
export const requestRuleImpl: ToolImpl = async (args, extras) => {
|
||||
const name = getStringArg(args, "name");
|
||||
|
||||
// Find the rule by name in the config
|
||||
const rule = extras.config.rules.find((r) => r.name === args.name);
|
||||
const rule = extras.config.rules.find((r) => r.name === name);
|
||||
|
||||
if (!rule || !rule.ruleFile) {
|
||||
throw new Error(
|
||||
`Rule with name "${args.name}" not found or has no file path`,
|
||||
);
|
||||
throw new Error(`Rule with name "${name}" not found or has no file path`);
|
||||
}
|
||||
|
||||
return [
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ import {
|
|||
isProcessBackgrounded,
|
||||
removeBackgroundedProcess,
|
||||
} from "../../util/processTerminalBackgroundStates";
|
||||
import { getBooleanArg, getStringArg } from "../parseArgs";
|
||||
|
||||
const asyncExec = util.promisify(childProcess.exec);
|
||||
|
||||
|
|
@ -50,8 +51,11 @@ const ENABLED_FOR_REMOTES = [
|
|||
];
|
||||
|
||||
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
||||
const command = getStringArg(args, "command");
|
||||
// Default to waiting for completion if not specified
|
||||
const waitForCompletion = args.waitForCompletion !== false;
|
||||
const waitForCompletion =
|
||||
getBooleanArg(args, "waitForCompletion", false) ?? true;
|
||||
|
||||
const ideInfo = await extras.ide.getIdeInfo();
|
||||
const toolCallId = extras.toolCallId || "";
|
||||
|
||||
|
|
@ -84,7 +88,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
}
|
||||
|
||||
// Use spawn with color environment
|
||||
const childProc = childProcess.spawn(args.command, {
|
||||
const childProc = childProcess.spawn(command, {
|
||||
cwd,
|
||||
shell: true,
|
||||
env: getColorEnv(), // Add enhanced environment for colors
|
||||
|
|
@ -229,7 +233,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
// Standard execution, waiting for completion
|
||||
try {
|
||||
// Use color environment for exec as well
|
||||
const output = await asyncExec(args.command, {
|
||||
const output = await asyncExec(command, {
|
||||
cwd,
|
||||
env: getColorEnv(),
|
||||
});
|
||||
|
|
@ -258,7 +262,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
// but don't attach any listeners other than error
|
||||
try {
|
||||
// Use spawn with color environment
|
||||
const childProc = childProcess.spawn(args.command, {
|
||||
const childProc = childProcess.spawn(command, {
|
||||
cwd,
|
||||
shell: true,
|
||||
env: getColorEnv(), // Add color environment
|
||||
|
|
@ -309,7 +313,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
|
||||
// For remote environments, just run the command
|
||||
// Note: waitForCompletion is not supported in remote environments yet
|
||||
await extras.ide.runCommand(args.command);
|
||||
await extras.ide.runCommand(command);
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { fetchSearchResults } from "../../context/providers/WebContextProvider";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
|
||||
|
||||
export const searchWebImpl: ToolImpl = async (args, extras) => {
|
||||
const webResults = await fetchSearchResults(args.query, 5, extras.fetch);
|
||||
const query = getStringArg(args, "query");
|
||||
|
||||
const webResults = await fetchSearchResults(query, 5, extras.fetch);
|
||||
|
||||
// Track truncated results
|
||||
const truncatedResults: string[] = [];
|
||||
|
|
|
|||
|
|
@ -2,9 +2,11 @@ import generateRepoMap from "../../util/generateRepoMap";
|
|||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => {
|
||||
const { directory_path } = args;
|
||||
const directory_path = getStringArg(args, "directory_path");
|
||||
|
||||
const uri = await resolveRelativePathInDir(directory_path, extras.ide);
|
||||
|
||||
if (!uri) {
|
||||
|
|
|
|||
|
|
@ -12,3 +12,52 @@ export function safeParseToolCallArgs(
|
|||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function getStringArg(
|
||||
args: any,
|
||||
argName: string,
|
||||
allowEmpty = false,
|
||||
): string {
|
||||
if (!args || !(argName in args) || typeof args[argName] !== "string") {
|
||||
throw new Error(
|
||||
`\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty"}. (type string)`,
|
||||
);
|
||||
}
|
||||
if (!allowEmpty && !args[argName].trim()) {
|
||||
throw new Error(`Argument ${argName} must not be empty`);
|
||||
}
|
||||
return args[argName];
|
||||
}
|
||||
|
||||
export function getOptionalStringArg(
|
||||
args: any,
|
||||
argName: string,
|
||||
allowEmpty = false,
|
||||
) {
|
||||
if (typeof args?.[argName] === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
return getStringArg(args, argName, allowEmpty);
|
||||
}
|
||||
|
||||
export function getBooleanArg(args: any, argName: string, required = false) {
|
||||
if (!args || !(argName in args)) {
|
||||
if (required) {
|
||||
throw new Error(`Argument \`${argName}\` is required (type boolean)`);
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
if (typeof args[argName] === "string") {
|
||||
if (args[argName].toLowerCase() === "false") {
|
||||
return false;
|
||||
}
|
||||
if (args[argName].toLowerCase() === "true") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (typeof args[argName] !== "boolean") {
|
||||
throw new Error(`Argument \`${argName}\` must be a boolean true or false`);
|
||||
}
|
||||
return args[argName];
|
||||
}
|
||||
|
|
|
|||
248
core/tools/parseArgs.vitest.ts
Normal file
248
core/tools/parseArgs.vitest.ts
Normal file
|
|
@ -0,0 +1,248 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { ToolCallDelta } from "..";
|
||||
import {
|
||||
getBooleanArg,
|
||||
getOptionalStringArg,
|
||||
getStringArg,
|
||||
safeParseToolCallArgs,
|
||||
} from "./parseArgs";
|
||||
|
||||
describe("safeParseToolCallArgs", () => {
|
||||
it("should parse valid JSON arguments", () => {
|
||||
const toolCall: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: '{"name": "test", "value": 123}',
|
||||
},
|
||||
};
|
||||
|
||||
const result = safeParseToolCallArgs(toolCall);
|
||||
expect(result).toEqual({ name: "test", value: 123 });
|
||||
});
|
||||
|
||||
it("should parse valid JSON arguments with whitespace", () => {
|
||||
const toolCall: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: ' {"name": "test", "value": 123} ',
|
||||
},
|
||||
};
|
||||
|
||||
const result = safeParseToolCallArgs(toolCall);
|
||||
expect(result).toEqual({ name: "test", value: 123 });
|
||||
});
|
||||
|
||||
it("should return empty object for invalid JSON", () => {
|
||||
const toolCall: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: '{"name": "test", value: 123', // Invalid JSON
|
||||
},
|
||||
};
|
||||
|
||||
const result = safeParseToolCallArgs(toolCall);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it("should return empty object when arguments is empty", () => {
|
||||
const toolCall: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: "",
|
||||
},
|
||||
};
|
||||
|
||||
const result = safeParseToolCallArgs(toolCall);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it("should return empty object when arguments is null or undefined", () => {
|
||||
const toolCall1: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: null as any,
|
||||
},
|
||||
};
|
||||
|
||||
const toolCall2: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: undefined,
|
||||
},
|
||||
};
|
||||
|
||||
expect(safeParseToolCallArgs(toolCall1)).toEqual({});
|
||||
expect(safeParseToolCallArgs(toolCall2)).toEqual({});
|
||||
});
|
||||
|
||||
it("should handle case when function is undefined", () => {
|
||||
const toolCall: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: undefined,
|
||||
};
|
||||
|
||||
const result = safeParseToolCallArgs(toolCall);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStringArg", () => {
|
||||
it("should return string argument when valid", () => {
|
||||
const args = { name: "test" };
|
||||
const result = getStringArg(args, "name");
|
||||
expect(result).toBe("test");
|
||||
});
|
||||
|
||||
it("should throw error when argument is missing", () => {
|
||||
const args = { otherArg: "test" };
|
||||
expect(() => getStringArg(args, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is not a string", () => {
|
||||
const args = { name: 123 };
|
||||
expect(() => getStringArg(args, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is empty and empty not allowed", () => {
|
||||
const args = { name: "" };
|
||||
expect(() => getStringArg(args, "name")).toThrowError(
|
||||
"Argument name must not be empty",
|
||||
);
|
||||
|
||||
const argsWithSpace = { name: " " };
|
||||
expect(() => getStringArg(argsWithSpace, "name")).toThrowError(
|
||||
"Argument name must not be empty",
|
||||
);
|
||||
});
|
||||
|
||||
it("should accept empty string when allowEmpty is true", () => {
|
||||
const args = { name: "" };
|
||||
const result = getStringArg(args, "name", true);
|
||||
expect(result).toBe("");
|
||||
|
||||
const argsWithSpace = { name: " " };
|
||||
const resultWithSpace = getStringArg(argsWithSpace, "name", true);
|
||||
expect(resultWithSpace).toBe(" ");
|
||||
});
|
||||
|
||||
it("should handle null or undefined args", () => {
|
||||
expect(() => getStringArg(null, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
);
|
||||
expect(() => getStringArg(undefined, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getOptionalStringArg", () => {
|
||||
it("should return undefined when argument is not provided", () => {
|
||||
const args = { otherArg: "test" };
|
||||
const result = getOptionalStringArg(args, "name");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return string argument when valid", () => {
|
||||
const args = { name: "test" };
|
||||
const result = getOptionalStringArg(args, "name");
|
||||
expect(result).toBe("test");
|
||||
});
|
||||
|
||||
it("should throw error when argument is not a string", () => {
|
||||
const args = { name: 123 };
|
||||
expect(() => getOptionalStringArg(args, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is empty and empty not allowed", () => {
|
||||
const args = { name: "" };
|
||||
expect(() => getOptionalStringArg(args, "name")).toThrowError(
|
||||
"Argument name must not be empty",
|
||||
);
|
||||
});
|
||||
|
||||
it("should accept empty string when allowEmpty is true", () => {
|
||||
const args = { name: "" };
|
||||
const result = getOptionalStringArg(args, "name", true);
|
||||
expect(result).toBe("");
|
||||
});
|
||||
|
||||
it("should handle null or undefined args", () => {
|
||||
expect(getOptionalStringArg(null, "name")).toBeUndefined();
|
||||
expect(getOptionalStringArg(undefined, "name")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getBooleanArg", () => {
|
||||
it("should return boolean argument when valid", () => {
|
||||
const argsTrue = { flag: true };
|
||||
const argsFalse = { flag: false };
|
||||
|
||||
expect(getBooleanArg(argsTrue, "flag")).toBe(true);
|
||||
expect(getBooleanArg(argsFalse, "flag")).toBe(false);
|
||||
});
|
||||
|
||||
it("should return undefined when argument is not provided and not required", () => {
|
||||
const args = { otherArg: true };
|
||||
const result = getBooleanArg(args, "flag");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should throw error when argument is not provided and required", () => {
|
||||
const args = { otherArg: true };
|
||||
expect(() => getBooleanArg(args, "flag", true)).toThrowError(
|
||||
"Argument `flag` is required (type boolean)",
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle string "true" and "false" values', () => {
|
||||
const argsStringTrue = { flag: "true" };
|
||||
const argsStringFalse = { flag: "false" };
|
||||
const argsStringTrueUppercase = { flag: "TRUE" };
|
||||
const argsStringFalseUppercase = { flag: "FALSE" };
|
||||
|
||||
expect(getBooleanArg(argsStringTrue, "flag")).toBe(true);
|
||||
expect(getBooleanArg(argsStringFalse, "flag")).toBe(false);
|
||||
expect(getBooleanArg(argsStringTrueUppercase, "flag")).toBe(true);
|
||||
expect(getBooleanArg(argsStringFalseUppercase, "flag")).toBe(false);
|
||||
});
|
||||
|
||||
it("should throw error when argument is not a boolean or valid boolean string", () => {
|
||||
const argsNumber = { flag: 1 };
|
||||
const argsInvalidString = { flag: "yes" };
|
||||
const argsObject = { flag: {} };
|
||||
|
||||
expect(() => getBooleanArg(argsNumber, "flag")).toThrowError(
|
||||
"Argument `flag` must be a boolean true or false",
|
||||
);
|
||||
expect(() => getBooleanArg(argsInvalidString, "flag")).toThrowError(
|
||||
"Argument `flag` must be a boolean true or false",
|
||||
);
|
||||
expect(() => getBooleanArg(argsObject, "flag")).toThrowError(
|
||||
"Argument `flag` must be a boolean true or false",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle null or undefined args", () => {
|
||||
expect(getBooleanArg(null, "flag")).toBeUndefined();
|
||||
expect(getBooleanArg(undefined, "flag")).toBeUndefined();
|
||||
|
||||
expect(() => getBooleanArg(null, "flag", true)).toThrowError(
|
||||
"Argument `flag` is required (type boolean)",
|
||||
);
|
||||
expect(() => getBooleanArg(undefined, "flag", true)).toThrowError(
|
||||
"Argument `flag` is required (type boolean)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -13,6 +13,7 @@ import {
|
|||
Problem,
|
||||
Range,
|
||||
RangeInFile,
|
||||
SignatureHelp,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
ToastType,
|
||||
|
|
@ -44,6 +45,14 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
|
|||
experimental_includeRecentlyVisitedRanges: true,
|
||||
experimental_includeRecentlyEditedRanges: true,
|
||||
experimental_includeDiff: true,
|
||||
experimental_enableStaticContextualization: false,
|
||||
};
|
||||
|
||||
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;
|
||||
|
|
|
|||
|
|
@ -94,4 +94,4 @@ If you need to force a refresh of the index, reload the VS Code window with <kbd
|
|||
|
||||
## Repository map
|
||||
|
||||
Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../custom-providers.mdx#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](../custom-providers#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.
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ The `@Docs` context provider works by
|
|||
|
||||
### Hub `docs` Blocks
|
||||
|
||||
@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs).
|
||||
@Docs uses [`docs` blocks](../../hub/blocks/block-types#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs).
|
||||
|
||||
### Through the `@Docs` Context Provider
|
||||
|
||||
|
|
@ -354,7 +354,6 @@ The following configuration example includes:
|
|||
- title: My Private Docs
|
||||
startUrl: http://10.2.1.2/docs
|
||||
faviconUrl: http://10.2.1.2/docs/assets/favicon.ico
|
||||
maxDepth: 4
|
||||
useLocalCrawling: true
|
||||
```
|
||||
</Tab>
|
||||
|
|
|
|||
|
|
@ -143,7 +143,10 @@ Reference the contents of all of your open files. Set `onlyPinned` to `true` to
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: open params: onlyPinned: true
|
||||
context:
|
||||
- provider: open
|
||||
params:
|
||||
onlyPinned: true
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -164,7 +167,10 @@ Optionally, set `n` to limit the number of results returned (default 6).
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: web params: n: 5
|
||||
context:
|
||||
- provider: web
|
||||
params:
|
||||
n: 5
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -183,7 +189,8 @@ Reference the most relevant snippets from your codebase.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: codebase
|
||||
context:
|
||||
- provider: codebase
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -223,7 +230,10 @@ Reference the results of codebase search, just like the results you would get fr
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: search params: maxResults: 100 # optional, defaults to 200
|
||||
context:
|
||||
- provider: search
|
||||
params:
|
||||
maxResults: 100 # optional, defaults to 200
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -244,7 +254,8 @@ Reference the markdown converted contents of a given URL.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: url
|
||||
context:
|
||||
- provider: url
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -263,7 +274,8 @@ Reference recent clipboard items
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: clipboard
|
||||
context:
|
||||
- provider: clipboard
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -282,7 +294,8 @@ Reference the structure of your current workspace.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: tree
|
||||
context:
|
||||
- provider: tree
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -301,7 +314,8 @@ Get Problems from the current file.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: problems
|
||||
context:
|
||||
- provider: problems
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -320,7 +334,10 @@ Reference the contents of the local variables in the debugger. Currently only av
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: debugger params: stackDepth: 3
|
||||
context:
|
||||
- provider: debugger
|
||||
params:
|
||||
stackDepth: 3
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -343,7 +360,10 @@ Reference the outline of your codebase. By default, signatures are included alon
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: repo-map params: includeSignatures: false # default true
|
||||
context:
|
||||
- provider: repo-map
|
||||
params:
|
||||
includeSignatures: false # default true
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -368,7 +388,8 @@ Reference the architecture and platform of your current operating system.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: os
|
||||
context:
|
||||
- provider: os
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -387,7 +408,13 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a
|
|||
config.yaml
|
||||
|
||||
```
|
||||
mcpServers: - name: My MCP Server command: uvx args: - mcp-server-sqlite - --db-path - /Users/NAME/test.db
|
||||
mcpServers:
|
||||
- name: My MCP Server
|
||||
command: uvx
|
||||
args:
|
||||
- mcp-server-sqlite
|
||||
- --db-path
|
||||
- /Users/NAME/test.db
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -420,7 +447,13 @@ Reference the conversation in a GitHub issue.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: issue params: repos: - owner: continuedev repo: continue githubToken: ghp_xxx
|
||||
context:
|
||||
- provider: issue
|
||||
params:
|
||||
repos:
|
||||
- owner: continuedev
|
||||
repo: continue
|
||||
githubToken: ghp_xxx
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -451,7 +484,29 @@ Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: database params: connections: - name: examplePostgres connection_type: postgres connection: user: username host: localhost database: exampleDB password: yourPassword port: 5432 - name: exampleMssql connection_type: mssql connection: user: username server: localhost database: exampleDB password: yourPassword - name: exampleSqlite connection_type: sqlite connection: filename: /path/to/your/sqlite/database.db
|
||||
context:
|
||||
- provider: database
|
||||
params:
|
||||
connections:
|
||||
- name: examplePostgres
|
||||
connection_type: postgres
|
||||
connection:
|
||||
user: username
|
||||
host: localhost
|
||||
database: exampleDB
|
||||
password: yourPassword
|
||||
port: 5432
|
||||
- name: exampleMssql
|
||||
connection_type: mssql
|
||||
connection:
|
||||
user: username
|
||||
server: localhost
|
||||
database: exampleDB
|
||||
password: yourPassword
|
||||
- name: exampleSqlite
|
||||
connection_type: sqlite
|
||||
connection:
|
||||
filename: /path/to/your/sqlite/database.db
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -514,7 +569,16 @@ Reference the schema of a table, and some sample rows
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: postgres params: host: localhost port: 5436 user: myuser password: catsarecool database: animals schema: public sampleRows: 3
|
||||
context:
|
||||
- provider: postgres
|
||||
params:
|
||||
host: localhost
|
||||
port: 5436
|
||||
user: myuser
|
||||
password: catsarecool
|
||||
database: animals
|
||||
schema: public
|
||||
sampleRows: 3
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -554,7 +618,10 @@ Reference the results of a Google search.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: google params: serperApiKey: <YOUR_SERPER.DEV_API_KEY>
|
||||
context:
|
||||
- provider: google
|
||||
params:
|
||||
serperApiKey: <YOUR_SERPER.DEV_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -584,7 +651,10 @@ Reference an open MR for this branch on GitLab.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: gitlab-mr params: token: "..."
|
||||
context:
|
||||
- provider: gitlab-mr
|
||||
params:
|
||||
token: "..."
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -605,7 +675,11 @@ You can specify the domain to communicate with by setting the `domain` parameter
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: gitlab-mr params: token: "..." domain: "gitlab.example.com"
|
||||
context:
|
||||
- provider: gitlab-mr
|
||||
params:
|
||||
token: "..."
|
||||
domain: "gitlab.example.com"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -635,7 +709,11 @@ Reference the conversation in a Jira issue.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: jira params: domain: company.atlassian.net token: ATATT...
|
||||
context:
|
||||
- provider: jira
|
||||
params:
|
||||
domain: company.atlassian.net
|
||||
token: ATATT...
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -663,7 +741,10 @@ This context provider supports both Jira API version 2 and 3. It will use versio
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: jira params: apiVersion: "2"
|
||||
context:
|
||||
- provider: jira
|
||||
params:
|
||||
apiVersion: "2"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -696,7 +777,16 @@ Reference the messages in a Discord channel.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: discord params: discordKey: "bot token" guildId: "1234567890" channels: - id: "123456" name: "example-channel" - id: "678901" name: "example-channel-2"
|
||||
context:
|
||||
- provider: discord
|
||||
params:
|
||||
discordKey: "bot token"
|
||||
guildId: "1234567890"
|
||||
channels:
|
||||
- id: "123456"
|
||||
name: "example-channel"
|
||||
- id: "678901"
|
||||
name: "example-channel-2"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -731,7 +821,10 @@ The HttpContextProvider makes a POST request to the url passed in the configurat
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: http params: url: "https://api.example.com/v1/users"
|
||||
context:
|
||||
- provider: http
|
||||
params:
|
||||
url: "https://api.example.com/v1/users"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -770,7 +863,11 @@ Reference specific git commit metadata and diff or all of the recent commits.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: commit params: Depth: 50 LastXCommitsDepth: 10
|
||||
context:
|
||||
- provider: commit
|
||||
params:
|
||||
Depth: 50
|
||||
LastXCommitsDepth: 10
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -795,7 +892,11 @@ Query a [Greptile](https://www.greptile.com/) index of the current repo/branch.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: greptile params: greptileToken: "..." githubToken: "..."
|
||||
context:
|
||||
- provider: greptile
|
||||
params:
|
||||
greptileToken: "..."
|
||||
githubToken: "..."
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ Slash commands can be combined with additional instructions, including [context
|
|||
|
||||
### Assistant prompt blocks
|
||||
|
||||
The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types.md#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx).
|
||||
The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx).
|
||||
|
||||
### Prompt files
|
||||
|
||||
|
|
|
|||
|
|
@ -48,7 +48,13 @@ We recommend configuring **GPT-4o** as your chat model.
|
|||
|
||||
## Autocomplete model
|
||||
|
||||
We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral:
|
||||
We recommend configuring **Codestral** as your autocomplete model.
|
||||
|
||||
<Info>
|
||||
**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint required for autocomplete functionality. To use Codestral for autocomplete, deploy it through **Azure Machine Learning Studio** instead, which provides the necessary `/v1/fim/completions` endpoint.
|
||||
</Info>
|
||||
|
||||
If you use Azure Machine Learning Studio to deploy Codestral:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
|
|
|
|||
|
|
@ -186,6 +186,41 @@ aws_secret_access_key = hijklmno
|
|||
aws_session_token = pqrstuvwxyz # Optional: means short term creds.
|
||||
```
|
||||
|
||||
You can also use an AWS `accessKeyId` and `secretAccessKey` for authentication instead of a local credentials profile.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Claude 3.7 Sonnet
|
||||
provider: bedrock
|
||||
model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
|
||||
env:
|
||||
region: us-east-1
|
||||
accessKeyId: ${{ secrets.AWS_ACCESS_KEY_ID }} # can also enter key inline here for local assistants
|
||||
secretAccessKey: ${{ secrets.AWS_SECRET_ACCESS_KEY }} # can also enter key inline here for local assistants
|
||||
roles:
|
||||
- chat
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="JSON">
|
||||
```json title="config.json"
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Claude 3.7 Sonnet",
|
||||
"provider": "bedrock",
|
||||
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
|
||||
"region": "us-east-1",
|
||||
"accessKeyId": "[YOUR_ACCESS_KEY_ID]",
|
||||
"secretAccessKey": "[YOUR_SECRET_ACCESS_KEY]"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Custom Imported Models
|
||||
|
||||
To setup Bedrock using custom imported models, add the following to your config file:
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ You can add `embed` to a model's `roles` to specify that it can be used to embed
|
|||
|
||||
If you have the ability to use any model, we recommend `voyage-code-3`, which is listed below along with the rest of the options for embeddings models.
|
||||
|
||||
If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama.mdx#embeddings-model).
|
||||
If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama#embeddings-model).
|
||||
|
||||
### Voyage AI
|
||||
|
||||
|
|
@ -57,7 +57,7 @@ After obtaining an API key from [here](https://www.voyageai.com/), you can confi
|
|||
|
||||
### Ollama
|
||||
|
||||
See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instructions on how to use Ollama for embeddings.
|
||||
See [here](../model-providers/top-level/ollama#embeddings-model) for instructions on how to use Ollama for embeddings.
|
||||
|
||||
### Transformers.js (currently VS Code only)
|
||||
|
||||
|
|
@ -118,36 +118,36 @@ See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instruc
|
|||
|
||||
### OpenAI
|
||||
|
||||
See [here](../model-providers/top-level/openai.mdx#embeddings-model) for instructions on how to use OpenAI for embeddings.
|
||||
See [here](../model-providers/top-level/openai#embeddings-model) for instructions on how to use OpenAI for embeddings.
|
||||
|
||||
### Cohere
|
||||
|
||||
See [here](../model-providers/more/cohere.mdx#embeddings-model) for instructions on how to use Cohere for embeddings.
|
||||
See [here](../model-providers/more/cohere#embeddings-model) for instructions on how to use Cohere for embeddings.
|
||||
|
||||
### Gemini
|
||||
|
||||
See [here](../model-providers/top-level/gemini.mdx#embeddings-model) for instructions on how to use Gemini for embeddings.
|
||||
See [here](../model-providers/top-level/gemini#embeddings-model) for instructions on how to use Gemini for embeddings.
|
||||
|
||||
### Vertex
|
||||
|
||||
See [here](../model-providers/top-level/vertexai.mdx#embeddings-model) for instructions on how to use Vertex for embeddings.
|
||||
See [here](../model-providers/top-level/vertexai#embeddings-model) for instructions on how to use Vertex for embeddings.
|
||||
|
||||
### Mistral
|
||||
|
||||
See [here](../model-providers/top-level/mistral.mdx#embeddings-model) for instructions on how to use Mistral for embeddings.
|
||||
See [here](../model-providers/top-level/mistral#embeddings-model) for instructions on how to use Mistral for embeddings.
|
||||
|
||||
### NVIDIA
|
||||
|
||||
See [here](../model-providers/more/nvidia.mdx#embeddings-model) for instructions on how to use NVIDIA for embeddings.
|
||||
See [here](../model-providers/more/nvidia#embeddings-model) for instructions on how to use NVIDIA for embeddings.
|
||||
|
||||
### Bedrock
|
||||
|
||||
See [here](../model-providers/top-level/bedrock.mdx#embeddings-model) for instructions on how to use Bedrock for embeddings.
|
||||
See [here](../model-providers/top-level/bedrock#embeddings-model) for instructions on how to use Bedrock for embeddings.
|
||||
|
||||
### WatsonX
|
||||
|
||||
See [here](../model-providers/more/watsonx.mdx#embeddings-model) for instructions on how to use WatsonX for embeddings.
|
||||
See [here](../model-providers/more/watsonx#embeddings-model) for instructions on how to use WatsonX for embeddings.
|
||||
|
||||
### LMStudio
|
||||
|
||||
See [here](../model-providers/more/lmstudio.mdx#embeddings-model) for instructions on how to use LMStudio for embeddings.
|
||||
See [here](../model-providers/more/lmstudio#embeddings-model) for instructions on how to use LMStudio for embeddings.
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@
|
|||
"pages": [
|
||||
"features/agent/quick-start",
|
||||
"features/agent/how-it-works",
|
||||
"features/agent/plan-mode",
|
||||
"features/agent/model-setup",
|
||||
"features/agent/how-to-customize",
|
||||
"features/agent/context-selection"
|
||||
|
|
|
|||
|
|
@ -17,22 +17,37 @@ The following handshake describes how Agent uses tools:
|
|||
6. The model responds, potentially with another tool call and step 2 begins again
|
||||
|
||||
<Info>
|
||||
In [Chat mode](/features/chat/quick-start), tools are **not** included in the
|
||||
request to the model.
|
||||
Tool availability varies by mode:
|
||||
- **Chat mode**: No tools included
|
||||
- **Plan mode**: Only read-only tools included
|
||||
- **Agent mode**: All tools included
|
||||
</Info>
|
||||
|
||||
## Built-in tools
|
||||
|
||||
Continue includes several built-in tools which provide the model access to IDE functionality:
|
||||
Continue includes several built-in tools which provide the model access to IDE functionality.
|
||||
|
||||
- **Read file** (`read_file`): read the contents of a file within the project
|
||||
- **Read currently open file** (`read_currently_open_file`): read the contents of the currently open file
|
||||
- **Create new file** (`create_new_file`): Create a new file within the project, with path and contents specified by the model
|
||||
- **Exact search** (`exact_search`): perform a `ripgrep` search within the project
|
||||
- **Glob search** (`file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached.
|
||||
- **Run terminal command** (`run_terminal_command`): run a terminal command from the workspace root
|
||||
- **Search web** (`search_web`): Perform a web search to get top results
|
||||
- **View diff** (`view_diff`): View the current working git diff
|
||||
- **View repo map** (`view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](/customize/custom-providers#repository-map)
|
||||
- **View subdirectory** (`view_subdirectory`): request a copy of a repo map for a specific directory within the project
|
||||
- **Create Rule Block** (`create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation
|
||||
### Plan mode tools (read-only)
|
||||
|
||||
In Plan mode, only these read-only tools are available:
|
||||
- **Read file** (`read_file`)
|
||||
- **Read currently open file** (`read_currently_open_file`)
|
||||
- **List directory** (`ls`)
|
||||
- **Glob search** (`glob_search`)
|
||||
- **Grep search** (`grep_search`)
|
||||
- **Fetch URL content** (`fetch_url_content`)
|
||||
- **Search web** (`search_web`)
|
||||
- **View diff** (`view_diff`)
|
||||
- **View repo map** (`view_repo_map`)
|
||||
- **View subdirectory** (`view_subdirectory`)
|
||||
- **Codebase tool** (`codebase_tool`)
|
||||
|
||||
### Agent mode tools (all tools)
|
||||
|
||||
In Agent mode, all tools are available including the read-only tools above plus:
|
||||
|
||||
- **Create new file** (`create_new_file`): Create a new file within the project
|
||||
- **Edit file** (`edit_file`): Make changes to existing files
|
||||
- **Run terminal command** (`run_terminal_command`): Run commands from the workspace root
|
||||
- **Create Rule Block** (`create_rule_block`): Create a new rule block in `.continue/rules`
|
||||
- All other write/execute tools for modifying the codebase
|
||||
|
|
|
|||
49
docs/features/agent/plan-mode.mdx
Normal file
49
docs/features/agent/plan-mode.mdx
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
---
|
||||
title: "Plan Mode"
|
||||
description: "Explore and understand code safely with read-only tools"
|
||||
---
|
||||
|
||||
## What is Plan mode?
|
||||
|
||||
Plan mode is a restricted environment that provides read-only access to your codebase. It's designed for safe exploration, understanding code, and planning changes without making any modifications.
|
||||
|
||||

|
||||
|
||||
### Key features
|
||||
|
||||
- **Read-only tools**: Access files, search, and analyze without risk
|
||||
- **Safe exploration**: Perfect for understanding unfamiliar codebases
|
||||
- **Planning focus**: Develop implementation strategies before execution
|
||||
- **MCP support**: Works with all MCP tools alongside built-in read-only tools
|
||||
|
||||
### How it works
|
||||
|
||||
Plan mode filters the available tools to only include read-only operations. This means you can:
|
||||
- Read any file in your project
|
||||
- Search through code with grep and glob patterns
|
||||
- View repository structure and diffs
|
||||
- Fetch web content for additional context
|
||||
- Use all MCP tools
|
||||
|
||||
But you cannot:
|
||||
- Create, edit, or delete files
|
||||
- Run terminal commands
|
||||
- Make any system changes
|
||||
|
||||
### Getting started
|
||||
|
||||
Select "Plan" from the mode selector below the chat input, or use `Cmd/Ctrl + .` to cycle through modes.
|
||||
|
||||

|
||||
|
||||
For detailed information about tools and usage, see the [Agent documentation](/features/agent/how-it-works), which covers both Agent and Plan modes.
|
||||
|
||||
### Common workflow
|
||||
|
||||
1. **Start in Plan mode** to explore and understand
|
||||
2. **Develop your approach** with the model's help
|
||||
3. **Switch to Agent mode** when ready to implement
|
||||
|
||||
<Tip>
|
||||
Plan mode shares the same interface and context features as Chat and Agent modes. You can use `@` context providers and highlight code just like in other modes.
|
||||
</Tip>
|
||||
|
|
@ -6,18 +6,39 @@ title: "Quick Start"
|
|||
|
||||
Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions.
|
||||
|
||||
### When to use each mode
|
||||
|
||||
- **Plan mode**: Use when you want to explore code, understand systems, or plan changes without making modifications. Perfect for:
|
||||
- Understanding unfamiliar codebases
|
||||
- Planning complex refactors
|
||||
- Debugging and investigation
|
||||
- Creating implementation strategies
|
||||
|
||||
- **Agent mode**: Use when you're ready to make changes. Ideal for:
|
||||
- Implementing features
|
||||
- Fixing bugs
|
||||
- Running tests and commands
|
||||
- Executing plans developed in Plan mode
|
||||
|
||||
### Use Agent
|
||||
|
||||
You can switch to `Agent` in the mode selector below the chat input box.
|
||||
You can switch to `Agent` in the mode selector below the chat input box. The mode selector offers three options:
|
||||
- **Chat**: No tools available, pure conversation
|
||||
- **Plan**: Read-only tools for safe exploration and planning
|
||||
- **Agent**: All tools available for making changes
|
||||
|
||||

|
||||
|
||||
<Info>
|
||||
If Agent is disabled with a `Not Supported` message, the selected model or
|
||||
If Agent or Plan is disabled with a `Not Supported` message, the selected model or
|
||||
provider doesn't support tools, or Continue doesn't yet support tools with it.
|
||||
See [Model Blocks](/customization/models) for more information.
|
||||
</Info>
|
||||
|
||||
<Tip>
|
||||
Use the keyboard shortcut `Cmd/Ctrl + .` to quickly cycle between modes.
|
||||
</Tip>
|
||||
|
||||
### Chat with Agent
|
||||
|
||||
Agent lives within the same interface as [Chat](/features/chat/how-it-works), so the same [input](/features/chat/quick-start#1-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#3-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#2-include-code-context).
|
||||
|
|
|
|||
|
|
@ -25,6 +25,13 @@ These models have varying tool calling and reasoning capabilities.
|
|||
3. Add `GEMINI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) from Moonshot AI
|
||||
|
||||
1. Get your API key from [Together AI](https://api.together.ai)
|
||||
2. Add [Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) to your assistant on Continue Hub
|
||||
3. Add `TOGETHER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[o3](https://hub.continue.dev/openai/o3) from OpenAI
|
||||
|
||||
1. Get your API key from [OpenAI](https://platform.openai.com)
|
||||
|
|
@ -46,10 +53,10 @@ These models have varying tool calling and reasoning capabilities.
|
|||
3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) from Moonshot AI
|
||||
[DeepSeek-V3](https://hub.continue.dev/togetherai/deepseek-v3) from DeepSeek
|
||||
|
||||
1. Get your API key from [TogetherAI](https://api.together.ai)
|
||||
2. Add [Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) to your assistant on Continue Hub
|
||||
1. Get your API key from [Together AI](https://api.together.ai)
|
||||
2. Add [DeepSeek-V3](https://hub.continue.dev/togetherai/deepseek-v3) to your assistant on Continue Hub
|
||||
3. Add `TOGETHER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
|
|
@ -59,6 +66,18 @@ These models can be run on your computer if you have enough VRAM.
|
|||
|
||||
Their limited tool calling and reasoning capabilities will make it challenging to use Agent mode.
|
||||
|
||||
[Qwen2.5-Coder 32B](https://hub.continue.dev/ollama/qwen2.5-coder-32b)
|
||||
|
||||
1. Add [Qwen2.5-Coder 32B](https://hub.continue.dev/ollama/qwen2.5-coder-32b) to your assistant on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[Devstral Small 27B](https://hub.continue.dev/ollama/devstral)
|
||||
|
||||
1. Add [Devstral Small](https://hub.continue.dev/ollama/devstral) to your assistant on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) from Qwen
|
||||
|
||||
1. Add [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) to your assistant on Continue Hub
|
||||
|
|
@ -71,10 +90,4 @@ Their limited tool calling and reasoning capabilities will make it challenging t
|
|||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[Llama 3.1 8B](https://hub.continue.dev/ollama/llama3.1-8b) from Meta
|
||||
|
||||
1. Add [Llama 3.1 8B](https://hub.continue.dev/ollama/llama3.1-8b) to your assistant on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model)
|
||||
|
|
|
|||
|
|
@ -4,8 +4,4 @@ The input you provide is included in the prompt.
|
|||
|
||||
## Code to Edit
|
||||
|
||||
The **entire contents** of each file (the current file for Jetbrains inline Edit, the `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
|
||||
|
||||
## Context Providers
|
||||
|
||||
In VS Code Edit mode, you can use `@` to add context using [Context Providers](/customize/custom-providers), similar to [Chat](/features/chat/context-selection). Some context providers may be disabled in Edit mode.
|
||||
The **entire contents** of the current file are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
|
||||
|
|
|
|||
|
|
@ -6,4 +6,6 @@ You can configure particular models from your Assistant to be used for Edit and
|
|||
2. Click the cube icon to expand the "Models" section
|
||||
3. Use the dropdowns to select models for Edit and Apply
|
||||
|
||||

|
||||
|
||||
Learn more about the [Edit role](/customize/model-roles/edit) and [Apply role](/customize/model-roles/apply).
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ Edit is recommended for small, targeted changes, such as
|
|||
|
||||
## Highlight code and activate
|
||||
|
||||
Highlight the block of code you would like to modify and press `cmd/ctrl` + `i` to active Edit mode. You can also enter Edit mode by pressing `cmd/ctrl` + `i` with no code highlighted, which will default to editing the current file.
|
||||
Highlight the block of code you would like to modify and press `Cmd+I` (Mac) or `Ctrl+I` (Windows/Linux) to activate Edit mode. You can also press `Cmd/Ctrl+I` with no code highlighted, which will default to inserting code at the current cursor location.
|
||||
|
||||
## Describe code changes
|
||||
|
||||
|
|
@ -24,23 +24,12 @@ Describe the changes you would like the model to make to your highlighted code.
|
|||
|
||||
Proposed changes appear as inline diffs within your highlighted text.
|
||||
|
||||
You can navigate through each proposed change, accepting or rejecting them using `cmd/ctrl` + `opt` + `y` (to accept) or `cmd/ctrl` + `opt` + `n` (to reject).
|
||||
You can navigate through each proposed change, accepting or rejecting them using `Cmd+Opt+Y` (Mac) or `Ctrl+Alt+Y` (Windows/Linux) to accept, or `Cmd+Opt+N` (Mac) or `Ctrl+Alt+N` (Windows/Linux) to reject.
|
||||
|
||||
You can also accept or reject all changes at once using `cmd/ctrl` + `shift` + `enter` (to accept) or `cmd/ctrl` + `shift` + `delete/backspace` (to reject).
|
||||
You can also accept or reject all changes at once using `Cmd+Shift+Enter` (Mac) or `Ctrl+Shift+Enter` (Windows/Linux) to accept, or `Cmd+Shift+Delete` (Mac) or `Ctrl+Shift+Backspace` (Windows/Linux) to reject.
|
||||
|
||||
If you want to request a new suggestion for the same highlighted code section, you can use `cmd/ctrl` + `i` to re-prompt the model.
|
||||
If you want to request a new suggestion for the same highlighted code section, you can use `Cmd+I` (Mac) or `Ctrl+I` (Windows/Linux) to re-prompt the model.
|
||||
|
||||
## VS Code
|
||||
|
||||
In VS Code, Edit is implemented in the extension sidebar with a similar interface to [Chat](/features/chat/how-it-works), and you can also enter Edit mode by using the Mode Selector below the main Chat input to select `Edit`.
|
||||
|
||||

|
||||
|
||||
You can also reject and accept diffs using the `Reject All` and `Accept All` buttons that show up in the Chat when diffs are present (see examples below).
|
||||
|
||||
### Adding Code to Edit
|
||||
|
||||
Along with adding highlighted code, you can also manually add files to edit using the `Add file` combobox or by clicking the dropdown and selecting `Add all open files` to add all files that are currently open in the editor.
|
||||
|
||||
## Jetbrains
|
||||
|
||||
|
|
|
|||
112
docs/features/plan/how-it-works.mdx
Normal file
112
docs/features/plan/how-it-works.mdx
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
---
|
||||
title: "How Plan Works"
|
||||
description: "Plan mode provides a restricted environment with read-only tools, enabling safe exploration and planning without making changes to your codebase."
|
||||
---
|
||||
|
||||
## Understanding Plan mode
|
||||
|
||||
Plan mode is designed to help you understand code and construct plans before making changes. It sits between Chat mode (no tools) and Agent mode (all tools), providing a middle ground where you can explore and analyze without risk.
|
||||
|
||||
### The key difference: Read-only tools
|
||||
|
||||
While Agent mode has access to all tools including those that modify files, Plan mode restricts access to only read-only tools. This ensures that:
|
||||
|
||||
- No files are created, modified, or deleted
|
||||
- No commands are executed that could change system state
|
||||
- All exploration is safe and non-destructive
|
||||
- You can confidently investigate without unintended consequences
|
||||
|
||||
## How Plan mode works
|
||||
|
||||
When you select Plan mode:
|
||||
|
||||
1. Continue sends a special system message instructing the model to focus on understanding and planning
|
||||
2. The tool list is filtered to include only read-only tools
|
||||
3. The model can use these tools to explore and analyze your codebase
|
||||
4. When you're ready to implement changes, you switch to Agent mode
|
||||
|
||||
### Available tools in Plan mode
|
||||
|
||||
Plan mode includes these read-only built-in tools:
|
||||
|
||||
- **Read file** (`read_file`): Read the contents of any file in the project
|
||||
- **Read currently open file** (`read_currently_open_file`): Read the contents of the currently open file
|
||||
- **List directory** (`ls`): List files and directories
|
||||
- **Glob search** (`glob_search`): Search for files matching a pattern
|
||||
- **Grep search** (`grep_search`): Search file contents using regex patterns
|
||||
- **Fetch URL content** (`fetch_url_content`): Retrieve content from web URLs
|
||||
- **Search web** (`search_web`): Perform web searches for additional context
|
||||
- **View diff** (`view_diff`): View the current git diff
|
||||
- **View repo map** (`view_repo_map`): Get an overview of the repository structure
|
||||
- **View subdirectory** (`view_subdirectory`): Get a detailed view of a specific directory
|
||||
- **Codebase tool** (`codebase_tool`): Advanced codebase analysis capabilities
|
||||
|
||||
### MCP tools support
|
||||
|
||||
In addition to built-in read-only tools, Plan mode also supports all MCP (Model Context Protocol) tools. This allows integration with external services that provide additional context or analysis capabilities without modifying your local environment.
|
||||
|
||||
<Info>
|
||||
While Plan mode restricts built-in tools to read-only operations, MCP tools are not filtered by Continue. Some MCP tools may have write capabilities that could modify your system or external services. Always verify what actions your MCP tools can perform before using them in Plan mode.
|
||||
</Info>
|
||||
|
||||
## The planning workflow
|
||||
|
||||
A typical Plan mode workflow follows these steps:
|
||||
|
||||
1. **Exploration**: Use read-only tools to understand the current state
|
||||
2. **Analysis**: Identify what needs to change and potential impacts
|
||||
3. **Planning**: Develop a detailed plan for implementation
|
||||
4. **Verification**: Review the plan and ensure it addresses all requirements
|
||||
5. **Execution**: Switch to Agent mode to implement the plan
|
||||
|
||||
### Example: Planning a refactor
|
||||
|
||||
```
|
||||
User: Help me plan a refactor to extract the authentication logic into a separate module
|
||||
|
||||
Plan mode:
|
||||
1. Reads relevant files to understand current structure
|
||||
2. Analyzes dependencies and usage patterns
|
||||
3. Identifies all places that need updates
|
||||
4. Creates a step-by-step refactoring plan
|
||||
5. Suggests: "Switch to Agent mode to implement this plan"
|
||||
```
|
||||
|
||||
## System message and behavior
|
||||
|
||||
Plan mode uses a dedicated system message that:
|
||||
|
||||
- Instructs the model to focus on understanding and planning
|
||||
- Emphasizes using only read-only tools
|
||||
- Reminds the model to suggest switching to Agent mode for implementation
|
||||
- Encourages thorough analysis before suggesting changes
|
||||
|
||||
<Info>
|
||||
The system message can be customized per model. See [How to
|
||||
Customize](/features/plan/how-to-customize) for details or see it [directly in
|
||||
the
|
||||
code](https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts).
|
||||
</Info>
|
||||
|
||||
## When to use Plan mode vs other modes
|
||||
|
||||
### Use Plan mode when:
|
||||
|
||||
- Exploring unfamiliar codebases
|
||||
- Planning complex refactors or features
|
||||
- Debugging and understanding issues
|
||||
- Reviewing code architecture
|
||||
- Creating implementation strategies
|
||||
|
||||
### Use Chat mode when:
|
||||
|
||||
- Having discussions without needing file access
|
||||
- Asking general programming questions
|
||||
- Getting explanations without exploring code
|
||||
|
||||
### Use Agent mode when:
|
||||
|
||||
- Ready to implement changes
|
||||
- Need to create or modify files
|
||||
- Want to run commands or tests
|
||||
- Implementing a plan developed in Plan mode
|
||||
60
docs/features/plan/quick-start.mdx
Normal file
60
docs/features/plan/quick-start.mdx
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
---
|
||||
title: "Quick Start"
|
||||
---
|
||||
|
||||
## How to use it
|
||||
|
||||
Plan mode provides a safe environment for understanding and constructing plans without making changes. It equips the Chat model with read-only tools, allowing you to explore, analyze, and plan modifications before executing them.
|
||||
|
||||
### Use Plan
|
||||
|
||||
You can switch to `Plan` in the mode selector below the chat input box.
|
||||
|
||||

|
||||
|
||||
<Info>
|
||||
If Plan is disabled with a `Not Supported` message, the selected model or
|
||||
provider doesn't support tools. See [Model Setup](/features/plan/model-setup)
|
||||
for more information.
|
||||
</Info>
|
||||
|
||||
### Chat with Plan
|
||||
|
||||
Plan mode lives within the same interface as [Chat](/features/chat/how-it-works) and [Agent](/features/agent/how-it-works), so the same [input](/features/chat/quick-start#1-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#3-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#2-include-code-context).
|
||||
|
||||
#### What makes Plan different
|
||||
|
||||
Unlike Agent mode, Plan mode:
|
||||
- Only uses read-only tools (file reading, searching, analysis)
|
||||
- Cannot modify, create, or delete files
|
||||
- Focuses on understanding and planning rather than execution
|
||||
- Provides a safe environment for exploration
|
||||
|
||||
### Common use cases
|
||||
|
||||
Plan mode is ideal for:
|
||||
- **Code exploration**: Understanding how a codebase works
|
||||
- **Planning refactors**: Analyzing impact before making changes
|
||||
- **Debugging**: Investigating issues without modifying code
|
||||
- **Architecture review**: Understanding system design and dependencies
|
||||
- **Pre-implementation planning**: Thinking through changes before executing
|
||||
|
||||
### Example workflow
|
||||
|
||||
1. **Start in Plan mode** to explore and understand the task
|
||||
2. **Develop a plan** with the model's help
|
||||
3. **Switch to Agent mode** when ready to implement changes
|
||||
|
||||
For example, you might say:
|
||||
|
||||
> Help me understand how the authentication system works and plan improvements to add OAuth support
|
||||
|
||||
Plan mode will analyze the existing code, understand the current implementation, and help you create a detailed plan—all without making any changes.
|
||||
|
||||
## Switching to execution
|
||||
|
||||
When you're ready to implement your plan, simply switch to Agent mode using the mode selector or keyboard shortcut (`Cmd/Ctrl + .`). The conversation context carries over, so Agent mode can immediately start implementing the plan you developed.
|
||||
|
||||
<Tip>
|
||||
Use the keyboard shortcut `Cmd/Ctrl + .` to quickly cycle between Chat, Plan, and Agent modes.
|
||||
</Tip>
|
||||
|
|
@ -27,7 +27,7 @@ description: "To quickly understand what you can do with Continue, check out eac
|
|||
<Tab title="Edit">
|
||||
[Edit](/features/edit/quick-start) is a convenient way to modify code without leaving your current file
|
||||
|
||||

|
||||

|
||||
|
||||
<Info>
|
||||
Learn more about [Edit](/features/edit/quick-start)
|
||||
|
|
@ -43,4 +43,14 @@ description: "To quickly understand what you can do with Continue, check out eac
|
|||
Learn more about [Agent](/features/agent/quick-start)
|
||||
</Info>
|
||||
</Tab>
|
||||
|
||||
<Tab title="Plan">
|
||||
[Plan](/features/agent/plan-mode) provides a safe environment with read-only tools for exploring code and planning changes
|
||||
|
||||

|
||||
|
||||
<Info>
|
||||
Learn more about [Plan](/features/agent/plan-mode)
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
|
|
|||
|
|
@ -79,7 +79,13 @@ After you've set up your server, you can configure Continue to use it by adding
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: http params: url: https://myserver.com/retrieve name: http description: Custom HTTP Context Provider displayTitle: My Custom Context
|
||||
context:
|
||||
- provider: http
|
||||
params:
|
||||
url: https://myserver.com/retrieve
|
||||
name: http
|
||||
description: Custom HTTP Context Provider
|
||||
displayTitle: My Custom Context
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
|
|
@ -25,7 +25,11 @@ Basic authentication can be done with any provider using the `apiKey` field:
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Ollama provider: ollama model: llama2-7b apiKey: <YOUR_CUSTOM_OLLAMA_SERVER_API_KEY>
|
||||
models:
|
||||
- name: Ollama
|
||||
provider: ollama
|
||||
model: llama2-7b
|
||||
apiKey: <YOUR_CUSTOM_OLLAMA_SERVER_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -53,7 +57,13 @@ If you need to send custom headers for authentication, you may use the `requestO
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Ollama provider: ollama model: llama2-7b requestOptions: headers: X-Auth-Token: xxx
|
||||
models:
|
||||
- name: Ollama
|
||||
provider: ollama
|
||||
model: llama2-7b
|
||||
requestOptions:
|
||||
headers:
|
||||
X-Auth-Token: xxx
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -79,7 +89,15 @@ Similarly if your model requires a Certificate for authentication, you may use t
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Ollama provider: ollama model: llama2-7b requestOptions: clientCertificate: cert: C:\tempollama.pem key: C:\tempollama.key passphrase: c0nt!nu3
|
||||
models:
|
||||
- name: Ollama
|
||||
provider: ollama
|
||||
model: llama2-7b
|
||||
requestOptions:
|
||||
clientCertificate:
|
||||
cert: C:\tempollama.pem
|
||||
key: C:\tempollama.key
|
||||
passphrase: c0nt!nu3
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
|
|
@ -21,7 +21,10 @@ Ollama is the fastest way to get up and running with local language models. We r
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Llama 3.1 8b provider: ollama model: llama3.1-8b
|
||||
models:
|
||||
- name: Llama 3.1 8b
|
||||
provider: ollama
|
||||
model: llama3.1-8b
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -53,7 +56,11 @@ Groq provides the fastest available inference for open-source language models, i
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Llama 3.3 70b Versatile provider: groq model: llama-3.3-70b-versatile apiKey: <YOUR_GROQ_API_KEY>
|
||||
models:
|
||||
- name: Llama 3.3 70b Versatile
|
||||
provider: groq
|
||||
model: llama-3.3-70b-versatile
|
||||
apiKey: <YOUR_GROQ_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -85,7 +92,11 @@ Together AI provides fast and reliable inference of open-source models. You'll b
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Llama 3.1 405b provider: together model: llama3.1-405b apiKey: <YOUR_TOGETHER_API_KEY>
|
||||
models:
|
||||
- name: Llama 3.1 405b
|
||||
provider: together
|
||||
model: llama3.1-405b
|
||||
apiKey: <YOUR_TOGETHER_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -116,7 +127,11 @@ Replicate makes it easy to host and run open-source AI with an API.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Llama 3.1 405b provider: replicate model: llama3.1-405b apiKey: <YOUR_REPLICATE_API_KEY>
|
||||
models:
|
||||
- name: Llama 3.1 405b
|
||||
provider: replicate
|
||||
model: llama3.1-405b
|
||||
apiKey: <YOUR_REPLICATE_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -148,7 +163,11 @@ SambaNova Cloud provides world record Llama3.1 70B/405B serving.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: SambaNova Llama 3.1 405B provider: sambanova model: llama3.1-405b apiKey: <YOUR_SAMBA_API_KEY>
|
||||
models:
|
||||
- name: SambaNova Llama 3.1 405B
|
||||
provider: sambanova
|
||||
model: llama3.1-405b
|
||||
apiKey: <YOUR_SAMBA_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -180,7 +199,11 @@ Cerebras Inference uses specialized silicon to provides fast inference for the L
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Cerebras Llama 3.1 70B provider: cerebras model: llama3.1-70b apiKey: <YOUR_CEREBRAS_API_KEY>
|
||||
models:
|
||||
- name: Cerebras Llama 3.1 70B
|
||||
provider: cerebras
|
||||
model: llama3.1-70b
|
||||
apiKey: <YOUR_CEREBRAS_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
|
|
@ -19,7 +19,14 @@ Before getting started, ensure your system meets these requirements:
|
|||
Choose the installation method for your operating system:
|
||||
|
||||
```
|
||||
# macOSbrew install ollama# Linuxcurl -fsSL https://ollama.ai/install.sh | sh# Windows# Download from ollama.ai
|
||||
# macOS
|
||||
brew install ollama
|
||||
|
||||
# Linux
|
||||
curl -fsSL https://ollama.ai/install.sh | sh
|
||||
|
||||
# Windows
|
||||
# Download from ollama.ai
|
||||
```
|
||||
|
||||
### Step 2: Download Models
|
||||
|
|
@ -27,7 +34,10 @@ Choose the installation method for your operating system:
|
|||
After installing Ollama, download the models you want to use. Here are some popular options:
|
||||
|
||||
```
|
||||
# Popular models for developmentollama pull llama2ollama pull codellamaollama pull mistral
|
||||
# Popular models for development
|
||||
ollama pull llama2
|
||||
ollama pull codellama
|
||||
ollama pull mistral
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
|
|
|||
|
|
@ -18,7 +18,15 @@ title: "How to Set Up Codestral"
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Codestral provider: mistral model: codestral-latest apiKey: <YOUR_CODESTRAL_API_KEY> apiBase: https://codestral.mistral.ai/v1 roles: - chat - autocomplete
|
||||
models:
|
||||
- name: Codestral
|
||||
provider: mistral
|
||||
model: codestral-latest
|
||||
apiKey: <YOUR_CODESTRAL_API_KEY>
|
||||
apiBase: https://codestral.mistral.ai/v1
|
||||
roles:
|
||||
- chat
|
||||
- autocomplete
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
BIN
docs/images/edit-model.png
Normal file
BIN
docs/images/edit-model.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 127 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 6 MiB After Width: | Height: | Size: 3.6 MiB |
BIN
docs/images/plan-mode-compressed.gif
Normal file
BIN
docs/images/plan-mode-compressed.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 MiB |
BIN
docs/images/plan-mode-selector.png
Normal file
BIN
docs/images/plan-mode-selector.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 69 KiB |
BIN
docs/images/plan-mode.gif
Normal file
BIN
docs/images/plan-mode.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9 MiB |
|
|
@ -61,7 +61,7 @@ Blocks:
|
|||
- `.continue/models` - for models
|
||||
- `.continue/prompts` - for prompts
|
||||
- `.continue/context` - for context providers
|
||||
- `.continue/docs` - for docs~~~~
|
||||
- `.continue/docs` - for docs
|
||||
- `.continue/data` - for data
|
||||
- `.continue/mcpServers` - for MCP Servers
|
||||
|
||||
|
|
@ -357,8 +357,6 @@ List of documentation sites to index.
|
|||
|
||||
- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc.
|
||||
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
|
||||
|
||||
- `maxDepth`: Maximum link depth for crawling. Default `4`
|
||||
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
|
||||
- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler.
|
||||
|
||||
|
|
@ -507,7 +505,6 @@ context:
|
|||
params:
|
||||
startUrl: https://docs.example.com/introduction
|
||||
rootUrl: https://docs.example.com
|
||||
maxDepth: 3
|
||||
mcpServers:
|
||||
- name: DevServer
|
||||
command: npm
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue