Merge branch 'main' of https://github.com/continuedev/continue into pe/contributing-docs-update
This commit is contained in:
commit
be7a7732fc
291 changed files with 23223 additions and 4926 deletions
|
|
@ -1,11 +0,0 @@
|
|||
name: Continue Documentation MCP
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
mcpServers:
|
||||
- name: Continue Docs Search
|
||||
type: stdio
|
||||
command: npx
|
||||
args:
|
||||
- mint-mcp
|
||||
- add
|
||||
- continue-docs
|
||||
2
.github/workflows/cla.yaml
vendored
2
.github/workflows/cla.yaml
vendored
|
|
@ -24,7 +24,7 @@ jobs:
|
|||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
path-to-signatures: "signatures/version1/cla.json"
|
||||
path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
|
||||
path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md"
|
||||
branch: cla-signatures
|
||||
# Bots and CLAs signed outside of GitHub
|
||||
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline
|
||||
|
|
|
|||
4
.github/workflows/compliance.yaml
vendored
4
.github/workflows/compliance.yaml
vendored
|
|
@ -31,6 +31,8 @@ jobs:
|
|||
uses: wagoid/commitlint-github-action@v6
|
||||
with:
|
||||
configFile: .commitlintrc.warning.json
|
||||
# Only check the last commit instead of all commits in the PR
|
||||
commitDepth: 1
|
||||
continue-on-error: true
|
||||
|
||||
- name: Add commit message guidance comment
|
||||
|
|
@ -57,7 +59,7 @@ jobs:
|
|||
body: [
|
||||
"## ⚠️ Conventional Commit Format",
|
||||
"",
|
||||
"Your commit messages don't follow the conventional commit format, but **this won't block your PR from being merged**. We recommend downloading [this extension](https://marketplace.visualstudio.com/items?itemName=vivaxy.vscode-conventional-commits) if you are using VS Code.",
|
||||
"Your latest commit message doesn't follow the conventional commit format, but **this won't block your PR from being merged**. We recommend downloading [this extension](https://marketplace.visualstudio.com/items?itemName=vivaxy.vscode-conventional-commits) if you are using VS Code.",
|
||||
"",
|
||||
"### Expected Format:",
|
||||
"```",
|
||||
|
|
|
|||
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
|
||||
|
|
|
|||
48
CLA.md
Normal file
48
CLA.md
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
# Individual Contributor License Agreement (v1.0, Continue)
|
||||
|
||||
_Based on the Apache Software Foundation Individual CLA v 2.2._
|
||||
|
||||
By commenting **“I have read the CLA Document and I hereby sign the CLA”**
|
||||
on a Pull Request, **you (“Contributor”) agree to the following terms** for any
|
||||
past and future “Contributions” submitted to **Continue (the “Project”)**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Definitions
|
||||
|
||||
- **“Contribution”** – any original work of authorship submitted to the Project
|
||||
(code, documentation, designs, etc.).
|
||||
- **“You” / “Your”** – the individual (or legal entity) posting the acceptance
|
||||
comment.
|
||||
|
||||
## 2. Copyright License
|
||||
|
||||
You grant **Continue Dev, Inc.** and all recipients of software distributed by the
|
||||
Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable
|
||||
license to reproduce, prepare derivative works of, publicly display, publicly
|
||||
perform, sublicense, and distribute Your Contributions and derivative works.
|
||||
|
||||
## 3. Patent License
|
||||
|
||||
You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual,
|
||||
worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent
|
||||
license to make, have made, use, sell, offer to sell, import, and otherwise
|
||||
transfer Your Contributions alone or in combination with the Project.
|
||||
|
||||
If any entity brings patent litigation alleging that the Project or a
|
||||
Contribution infringes a patent, the patent licenses granted by You to that
|
||||
entity under this CLA terminate.
|
||||
|
||||
## 4. Representations
|
||||
|
||||
1. You are legally entitled to grant the licenses above.
|
||||
2. Each Contribution is either Your original creation or You have authority to
|
||||
submit it under this CLA.
|
||||
3. Your Contributions are provided **“AS IS”** without warranties of any kind.
|
||||
4. You will notify the Project if any statement above becomes inaccurate.
|
||||
|
||||
## 5. Miscellany
|
||||
|
||||
This Agreement is governed by the laws of the **State of California**, USA,
|
||||
excluding its conflict‑of‑laws rules. If any provision is held unenforceable,
|
||||
the remaining provisions remain in force.
|
||||
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,9 +9,7 @@
|
|||
* creating a render of it.
|
||||
*/
|
||||
import {
|
||||
transformerMetaHighlight,
|
||||
transformerNotationDiff,
|
||||
transformerNotationFocus,
|
||||
transformerNotationHighlight,
|
||||
} from "@shikijs/transformers";
|
||||
import { JSDOM } from "jsdom";
|
||||
|
|
@ -21,6 +19,7 @@ import {
|
|||
getSingletonHighlighter,
|
||||
Highlighter,
|
||||
} from "shiki";
|
||||
import { DiffLine } from "..";
|
||||
import { escapeForSVG, kebabOfStr } from "../util/text";
|
||||
|
||||
interface CodeRendererOptions {
|
||||
|
|
@ -37,6 +36,10 @@ interface HTMLOptions {
|
|||
interface ConversionOptions extends HTMLOptions {
|
||||
transparent?: boolean;
|
||||
imageType: "svg";
|
||||
fontSize: number;
|
||||
fontFamily: string;
|
||||
dimensions: Dimensions;
|
||||
lineHeight: number;
|
||||
}
|
||||
|
||||
interface Dimensions {
|
||||
|
|
@ -166,83 +169,102 @@ export class CodeRenderer {
|
|||
code: string,
|
||||
language: string = "javascript",
|
||||
currLineOffsetFromTop: number,
|
||||
newDiffLines: DiffLine[],
|
||||
): Promise<string> {
|
||||
const annotatedCode = code
|
||||
.split("\n")
|
||||
.map((line, i) =>
|
||||
i === currLineOffsetFromTop
|
||||
? line + " \/\/ \[\!code highlight\]"
|
||||
: line,
|
||||
)
|
||||
.join("\n");
|
||||
const lines = code.split("\n");
|
||||
const newDiffLineMap = new Set();
|
||||
|
||||
if (newDiffLines) {
|
||||
newDiffLines.forEach((diffLine) => {
|
||||
if (diffLine.type === "new") {
|
||||
newDiffLineMap.add(diffLine.line);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const annotatedLines = [];
|
||||
|
||||
// NOTE: Shiki's preprocessor deletes transformer annotations when applied to an empty line.
|
||||
// If you are transforming an empty line, make sure that
|
||||
// the transformation is applied to a non-empty line first.
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
|
||||
// Add highlight comment before target line.
|
||||
if (i + 1 === currLineOffsetFromTop && currLineOffsetFromTop >= 0) {
|
||||
annotatedLines.push("// [!code highlight:1]");
|
||||
}
|
||||
|
||||
// Handle diff lines
|
||||
if (newDiffLineMap.has(line)) {
|
||||
if (line.trim() === "") {
|
||||
// For empty lines, add the magic comment on a separate line before.
|
||||
annotatedLines.push("// [!code ++]");
|
||||
annotatedLines.push(line); // The empty line itself.
|
||||
} else {
|
||||
// For non-empty lines, append the magic comment.
|
||||
annotatedLines.push(line + "// [!code ++]");
|
||||
}
|
||||
newDiffLineMap.delete(line);
|
||||
} else {
|
||||
annotatedLines.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
const annotatedCode = annotatedLines.join("\n");
|
||||
|
||||
await this.highlighter!.loadLanguage(language as BundledLanguage);
|
||||
|
||||
return this.highlighter!.codeToHtml(annotatedCode, {
|
||||
lang: language,
|
||||
theme: this.currentTheme,
|
||||
transformers: [
|
||||
// transformerColorizedBrackets(),
|
||||
transformerMetaHighlight(),
|
||||
transformerNotationHighlight(),
|
||||
transformerNotationDiff(),
|
||||
transformerNotationFocus(),
|
||||
],
|
||||
transformers: [transformerNotationHighlight(), transformerNotationDiff()],
|
||||
});
|
||||
}
|
||||
|
||||
async convertToSVG(
|
||||
code: string,
|
||||
language: string = "javascript",
|
||||
fontSize: number,
|
||||
fontFamily: string,
|
||||
dimensions: Dimensions,
|
||||
lineHeight: number,
|
||||
options: ConversionOptions,
|
||||
currLineOffsetFromTop: number,
|
||||
newDiffLines: DiffLine[],
|
||||
): Promise<Buffer> {
|
||||
const strokeWidth = 1;
|
||||
const highlightedCodeHtml = await this.highlightCode(
|
||||
code,
|
||||
language,
|
||||
currLineOffsetFromTop,
|
||||
newDiffLines,
|
||||
);
|
||||
// console.log(highlightedCodeHtml);
|
||||
|
||||
const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
|
||||
highlightedCodeHtml,
|
||||
fontSize,
|
||||
fontFamily,
|
||||
lineHeight,
|
||||
dimensions,
|
||||
options,
|
||||
);
|
||||
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
|
||||
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}" shape-rendering="crispEdges">
|
||||
<style>
|
||||
:root {
|
||||
--purple: rgb(112, 114, 209);
|
||||
--green: rgb(136, 194, 163);
|
||||
--blue: rgb(107, 166, 205);
|
||||
}
|
||||
</style>
|
||||
<g>
|
||||
<rect x="0" y="0" rx="10" ry="10" width="${dimensions.width}" height="${dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
|
||||
${lineBackgrounds}
|
||||
${guts}
|
||||
</g>
|
||||
</svg>`;
|
||||
console.log(svg);
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${options.dimensions.height}" shape-rendering="crispEdges">
|
||||
<style>
|
||||
:root {
|
||||
--purple: rgb(112, 114, 209);
|
||||
--green: rgb(136, 194, 163);
|
||||
--blue: rgb(107, 166, 205);
|
||||
}
|
||||
</style>
|
||||
<g>
|
||||
<rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${options.dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
|
||||
${lineBackgrounds}
|
||||
${guts}
|
||||
</g>
|
||||
</svg>`;
|
||||
// console.log(svg);
|
||||
|
||||
return Buffer.from(svg, "utf8");
|
||||
}
|
||||
|
||||
convertShikiHtmlToSvgGut(
|
||||
shikiHtml: string,
|
||||
fontSize: number,
|
||||
fontFamily: string,
|
||||
lineHeight: number,
|
||||
dimensions: Dimensions,
|
||||
options: ConversionOptions,
|
||||
): { guts: string; lineBackgrounds: string } {
|
||||
const dom = new JSDOM(shikiHtml);
|
||||
const document = dom.window.document;
|
||||
|
|
@ -263,6 +285,7 @@ export class CodeRenderer {
|
|||
if (classes.includes("highlighted")) {
|
||||
fill = ` fill="${this.editorLineHighlight}"`;
|
||||
}
|
||||
|
||||
const content = el.textContent || "";
|
||||
return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
|
||||
})
|
||||
|
|
@ -278,8 +301,8 @@ export class CodeRenderer {
|
|||
// The first step is to add lineHeight / 2 to move the axis down.
|
||||
// The second step is to add 'dominant-baseline="central"' to vertically center the text.
|
||||
// Note that we choose "central" over "middle". "middle" will center the text too perfectly, which is actually undesirable!
|
||||
const y = index * lineHeight + lineHeight / 2;
|
||||
return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
|
||||
const y = index * options.lineHeight + options.lineHeight / 2;
|
||||
return `<text x="0" y="${y}" font-family="${options.fontFamily}" font-size="${options.fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
|
||||
});
|
||||
|
||||
const lineBackgrounds = lines
|
||||
|
|
@ -287,8 +310,11 @@ export class CodeRenderer {
|
|||
const classes = line?.getAttribute("class") || "";
|
||||
const bgColor = classes.includes("highlighted")
|
||||
? this.editorLineHighlight
|
||||
: this.editorBackground;
|
||||
const y = index * lineHeight;
|
||||
: classes.includes("diff add")
|
||||
? "rgba(255, 255, 0, 0.2)"
|
||||
: this.editorBackground;
|
||||
|
||||
const y = index * options.lineHeight;
|
||||
const isFirst = index === 0;
|
||||
const isLast = index === lines.length - 1;
|
||||
const radius = 10;
|
||||
|
|
@ -297,24 +323,24 @@ export class CodeRenderer {
|
|||
// This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
|
||||
// Turning it off with 'shape-rendering="crispEdges"' solves the issue.
|
||||
return isFirst
|
||||
? `<path d="M ${0} ${y + lineHeight}
|
||||
L ${0} ${y + radius}
|
||||
Q ${0} ${y} ${radius} ${y}
|
||||
L ${dimensions.width - radius} ${y}
|
||||
Q ${dimensions.width} ${y} ${dimensions.width} ${y + radius}
|
||||
L ${dimensions.width} ${y + lineHeight}
|
||||
Z"
|
||||
fill="${bgColor}" />`
|
||||
? `<path d="M ${0} ${y + options.lineHeight}
|
||||
L ${0} ${y + radius}
|
||||
Q ${0} ${y} ${radius} ${y}
|
||||
L ${options.dimensions.width - radius} ${y}
|
||||
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
|
||||
L ${options.dimensions.width} ${y + options.lineHeight}
|
||||
Z"
|
||||
fill="${bgColor}" />`
|
||||
: isLast
|
||||
? `<path d="M ${0} ${y}
|
||||
L ${0} ${y + lineHeight - radius}
|
||||
Q ${0} ${y + lineHeight} ${radius} ${y + lineHeight}
|
||||
L ${dimensions.width - radius} ${y + lineHeight}
|
||||
Q ${dimensions.width} ${y + lineHeight} ${dimensions.width} ${y + lineHeight - 10}
|
||||
L ${dimensions.width} ${y}
|
||||
Z"
|
||||
fill="${bgColor}" />`
|
||||
: `<rect x="0" y="${y}" rx="${radius}" ry="${radius}" width="100%" height="${lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
|
||||
? `<path d="M ${0} ${y}
|
||||
L ${0} ${y + options.lineHeight - radius}
|
||||
Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
|
||||
L ${options.dimensions.width - radius} ${y + options.lineHeight}
|
||||
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
|
||||
L ${options.dimensions.width} ${y}
|
||||
Z"
|
||||
fill="${bgColor}" />`
|
||||
: `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
|
|
@ -344,12 +370,9 @@ export class CodeRenderer {
|
|||
async getDataUri(
|
||||
code: string,
|
||||
language: string = "javascript",
|
||||
fontSize: number,
|
||||
fontFamily: string,
|
||||
dimensions: Dimensions,
|
||||
lineHeight: number,
|
||||
options: ConversionOptions,
|
||||
currLineOffsetFromTop: number,
|
||||
newDiffLines: DiffLine[],
|
||||
): Promise<DataUri> {
|
||||
switch (options.imageType) {
|
||||
// case "png":
|
||||
|
|
@ -366,12 +389,9 @@ export class CodeRenderer {
|
|||
const svgBuffer = await this.convertToSVG(
|
||||
code,
|
||||
language,
|
||||
fontSize,
|
||||
fontFamily,
|
||||
dimensions,
|
||||
lineHeight,
|
||||
options,
|
||||
currLineOffsetFromTop,
|
||||
newDiffLines,
|
||||
);
|
||||
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,12 +11,14 @@ import {
|
|||
} from "../index.js";
|
||||
import { GlobalContext } from "../util/GlobalContext.js";
|
||||
|
||||
import EventEmitter from "node:events";
|
||||
import {
|
||||
AuthType,
|
||||
ControlPlaneSessionInfo,
|
||||
} from "../control-plane/AuthTypes.js";
|
||||
import { getControlPlaneEnv } from "../control-plane/env.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import {
|
||||
ASSISTANTS,
|
||||
getAllDotContinueDefinitionFiles,
|
||||
|
|
@ -44,6 +46,16 @@ export class ConfigHandler {
|
|||
private organizations: OrgWithProfiles[] = [];
|
||||
currentProfile: ProfileLifecycleManager | null;
|
||||
currentOrg: OrgWithProfiles;
|
||||
totalConfigLoads: number = 0;
|
||||
|
||||
public isInitialized: Promise<void>;
|
||||
private initter: EventEmitter;
|
||||
|
||||
cascadeAbortController: AbortController;
|
||||
private abortCascade() {
|
||||
this.cascadeAbortController.abort();
|
||||
this.cascadeAbortController = new AbortController();
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
|
|
@ -53,9 +65,11 @@ export class ConfigHandler {
|
|||
) {
|
||||
this.ide = ide;
|
||||
this.ideSettingsPromise = ideSettingsPromise;
|
||||
|
||||
this.controlPlaneClient = new ControlPlaneClient(
|
||||
sessionInfoPromise,
|
||||
ideSettingsPromise,
|
||||
this.ide.getIdeInfo(),
|
||||
);
|
||||
|
||||
// This profile manager will always be available
|
||||
|
|
@ -80,7 +94,13 @@ export class ConfigHandler {
|
|||
this.currentOrg = personalOrg;
|
||||
this.organizations = [personalOrg];
|
||||
|
||||
void this.cascadeInit();
|
||||
this.initter = new EventEmitter();
|
||||
this.isInitialized = new Promise((resolve) => {
|
||||
this.initter.on("init", resolve);
|
||||
});
|
||||
|
||||
this.cascadeAbortController = new AbortController();
|
||||
void this.cascadeInit("Config handler initialization");
|
||||
}
|
||||
|
||||
private workspaceDirs: string[] | null = null;
|
||||
|
|
@ -96,54 +116,71 @@ export class ConfigHandler {
|
|||
return `${workspaceId}:::${orgId}`;
|
||||
}
|
||||
|
||||
private async cascadeInit() {
|
||||
private async cascadeInit(reason: string) {
|
||||
const signal = this.cascadeAbortController.signal;
|
||||
this.workspaceDirs = null; // forces workspace dirs reload
|
||||
|
||||
const orgs = await this.getOrgs();
|
||||
try {
|
||||
const orgs = await this.getOrgs();
|
||||
|
||||
// Figure out selected org
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
const currentSelection = selectedOrgs[workspaceId];
|
||||
// Figure out selected org
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
const currentSelection = selectedOrgs[workspaceId];
|
||||
|
||||
const firstNonPersonal = orgs.find(
|
||||
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
|
||||
);
|
||||
const fallback = firstNonPersonal ?? orgs[0];
|
||||
// note, ignoring case of zero orgs since should never happen
|
||||
const firstNonPersonal = orgs.find(
|
||||
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
|
||||
);
|
||||
const fallback = firstNonPersonal ?? orgs[0];
|
||||
// note, ignoring case of zero orgs since should never happen
|
||||
|
||||
let selectedOrg: OrgWithProfiles;
|
||||
if (!currentSelection) {
|
||||
selectedOrg = fallback;
|
||||
} else {
|
||||
const match = orgs.find((org) => org.id === currentSelection);
|
||||
if (match) {
|
||||
selectedOrg = match;
|
||||
} else {
|
||||
let selectedOrg: OrgWithProfiles;
|
||||
if (!currentSelection) {
|
||||
selectedOrg = fallback;
|
||||
} else {
|
||||
const match = orgs.find((org) => org.id === currentSelection);
|
||||
if (match) {
|
||||
selectedOrg = match;
|
||||
} else {
|
||||
selectedOrg = fallback;
|
||||
}
|
||||
}
|
||||
|
||||
if (signal.aborted) {
|
||||
return; // local only case, no`fetch to throw abort error
|
||||
}
|
||||
this.initter.emit("init");
|
||||
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
|
||||
...selectedOrgs,
|
||||
[workspaceId]: selectedOrg.id,
|
||||
});
|
||||
|
||||
this.organizations = orgs;
|
||||
this.currentOrg = selectedOrg;
|
||||
this.currentProfile = selectedOrg.currentProfile;
|
||||
|
||||
await this.reloadConfig(reason);
|
||||
} catch (e) {
|
||||
if (e instanceof Error && e.message.includes("AbortError")) {
|
||||
return;
|
||||
} else {
|
||||
this.initter.emit("init"); // Error case counts for initialization
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
|
||||
...selectedOrgs,
|
||||
[workspaceId]: selectedOrg.id,
|
||||
});
|
||||
|
||||
this.organizations = orgs;
|
||||
this.currentOrg = selectedOrg;
|
||||
this.currentProfile = selectedOrg.currentProfile;
|
||||
await this.reloadConfig();
|
||||
}
|
||||
|
||||
private async getOrgs(): Promise<OrgWithProfiles[]> {
|
||||
if (await this.controlPlaneClient.isSignedIn()) {
|
||||
const isSignedIn = await this.controlPlaneClient.isSignedIn();
|
||||
if (isSignedIn) {
|
||||
const orgDescs = await this.controlPlaneClient.listOrganizations();
|
||||
const personalHubOrg = await this.getPersonalHubOrg();
|
||||
const hubOrgs = await Promise.all(
|
||||
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
|
||||
);
|
||||
return [...hubOrgs, personalHubOrg];
|
||||
const orgs = await Promise.all([
|
||||
this.getPersonalHubOrg(),
|
||||
...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
|
||||
]);
|
||||
return orgs;
|
||||
} else {
|
||||
return [await this.getLocalOrg()];
|
||||
}
|
||||
|
|
@ -312,13 +349,14 @@ export class ConfigHandler {
|
|||
// Should not be used internally
|
||||
//////////////////
|
||||
async refreshAll() {
|
||||
await this.cascadeInit();
|
||||
await this.cascadeInit("External refresh all");
|
||||
}
|
||||
|
||||
// Ide settings change: refresh session and cascade refresh from the top
|
||||
async updateIdeSettings(ideSettings: IdeSettings) {
|
||||
this.ideSettingsPromise = Promise.resolve(ideSettings);
|
||||
await this.cascadeInit();
|
||||
this.abortCascade();
|
||||
await this.cascadeInit("IDE settings update");
|
||||
}
|
||||
|
||||
// Session change: refresh session and cascade refresh from the top
|
||||
|
|
@ -328,8 +366,10 @@ export class ConfigHandler {
|
|||
this.controlPlaneClient = new ControlPlaneClient(
|
||||
Promise.resolve(sessionInfo),
|
||||
this.ideSettingsPromise,
|
||||
this.ide.getIdeInfo(),
|
||||
);
|
||||
await this.cascadeInit();
|
||||
this.abortCascade();
|
||||
await this.cascadeInit("Control plane session info update");
|
||||
}
|
||||
|
||||
// Org id: check id validity, save selection, switch and reload
|
||||
|
|
@ -356,7 +396,7 @@ export class ConfigHandler {
|
|||
await this.setSelectedProfileId(profileId);
|
||||
} else {
|
||||
this.currentProfile = org.currentProfile;
|
||||
await this.reloadConfig();
|
||||
await this.reloadConfig("Selected org changed");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -384,14 +424,17 @@ export class ConfigHandler {
|
|||
});
|
||||
|
||||
this.currentProfile = profile;
|
||||
await this.reloadConfig();
|
||||
await this.reloadConfig("Selected profile changed");
|
||||
}
|
||||
|
||||
// Bottom level of cascade: refresh the current profile
|
||||
// IMPORTANT - must always refresh when switching profiles
|
||||
// Because of e.g. MCP singleton and docs service using things from config
|
||||
// Could improve this
|
||||
async reloadConfig() {
|
||||
async reloadConfig(reason: string) {
|
||||
const startTime = performance.now();
|
||||
this.totalConfigLoads += 1;
|
||||
// console.log(`Reloading config (#${this.totalConfigLoads}): ${reason}`); // Uncomment to see config loading logs
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
|
|
@ -415,6 +458,17 @@ export class ConfigHandler {
|
|||
await this.currentProfile.reloadConfig(this.additionalContextProviders);
|
||||
|
||||
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
|
||||
|
||||
// Track config loading telemetry
|
||||
const endTime = performance.now();
|
||||
const duration = endTime - startTime;
|
||||
void Telemetry.capture("config_reload", {
|
||||
duration,
|
||||
reason,
|
||||
totalConfigLoads: this.totalConfigLoads,
|
||||
configLoadInterrupted,
|
||||
});
|
||||
|
||||
return { config, errors, configLoadInterrupted };
|
||||
}
|
||||
|
||||
|
|
@ -457,6 +511,7 @@ export class ConfigHandler {
|
|||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
await this.isInitialized;
|
||||
const config = await this.currentProfile.loadConfig(
|
||||
this.additionalContextProviders,
|
||||
);
|
||||
|
|
@ -487,7 +542,7 @@ export class ConfigHandler {
|
|||
private additionalContextProviders: IContextProvider[] = [];
|
||||
registerCustomContextProvider(contextProvider: IContextProvider) {
|
||||
this.additionalContextProviders.push(contextProvider);
|
||||
void this.reloadConfig();
|
||||
void this.reloadConfig("Custom context provider registered");
|
||||
}
|
||||
/**
|
||||
* Retrieves the titles of additional context providers that are of type "submenu".
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
|
|||
}`;
|
||||
fs.writeFileSync(getConfigTsPath(), configTs);
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
const config = await testConfigHandler.reloadConfig();
|
||||
const config = await testConfigHandler.reloadConfig("test");
|
||||
/**
|
||||
* @ts-ignore is applied because this test is skipped
|
||||
*/
|
||||
|
|
@ -45,7 +45,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
|
|||
path.join(TEST_DIR, ".continuerc.json"),
|
||||
JSON.stringify({ systemMessage: "SYSTEM2" }),
|
||||
);
|
||||
const config = await testConfigHandler.reloadConfig();
|
||||
const config = await testConfigHandler.reloadConfig("test");
|
||||
/**
|
||||
* @ts-ignore is applied because this test is skipped
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -7,6 +7,43 @@ import { walkDirs } from "../../indexing/walkDir";
|
|||
import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
export class CodebaseRulesCache {
|
||||
private static instance: CodebaseRulesCache | null = null;
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): CodebaseRulesCache {
|
||||
if (CodebaseRulesCache.instance === null) {
|
||||
CodebaseRulesCache.instance = new CodebaseRulesCache();
|
||||
}
|
||||
return CodebaseRulesCache.instance;
|
||||
}
|
||||
rules: RuleWithSource[] = [];
|
||||
errors: ConfigValidationError[] = [];
|
||||
async refresh(ide: IDE) {
|
||||
const { rules, errors } = await loadCodebaseRules(ide);
|
||||
this.rules = rules;
|
||||
this.errors = errors;
|
||||
}
|
||||
async update(ide: IDE, uri: string) {
|
||||
const content = await ide.readFile(uri);
|
||||
const rule = markdownToRule(content, { uriType: "file", filePath: uri });
|
||||
const ruleWithSource: RuleWithSource = {
|
||||
...rule,
|
||||
source: "colocated-markdown",
|
||||
ruleFile: uri,
|
||||
};
|
||||
const matchIdx = this.rules.findIndex((r) => r.ruleFile === uri);
|
||||
if (matchIdx === -1) {
|
||||
this.rules.push(ruleWithSource);
|
||||
} else {
|
||||
this.rules[matchIdx] = ruleWithSource;
|
||||
}
|
||||
}
|
||||
remove(uri: string) {
|
||||
this.rules = this.rules.filter((r) => r.ruleFile !== uri);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads rules from rules.md files colocated in the codebase
|
||||
*/
|
||||
|
|
@ -33,7 +70,11 @@ export async function loadCodebaseRules(ide: IDE): Promise<{
|
|||
const content = await ide.readFile(filePath);
|
||||
const rule = markdownToRule(content, { uriType: "file", filePath });
|
||||
|
||||
rules.push({ ...rule, source: "rules-block", ruleFile: filePath });
|
||||
rules.push({
|
||||
...rule,
|
||||
source: "colocated-markdown",
|
||||
ruleFile: filePath,
|
||||
});
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
|
|
|
|||
|
|
@ -45,27 +45,27 @@ describe("loadCodebaseRules", () => {
|
|||
"src/rules.md": {
|
||||
name: "General Rules",
|
||||
rule: "Follow coding standards",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/rules.md",
|
||||
},
|
||||
"src/redux/rules.md": {
|
||||
name: "Redux Rules",
|
||||
rule: "Use Redux Toolkit",
|
||||
globs: "**/*.{ts,tsx}",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/redux/rules.md",
|
||||
},
|
||||
"src/components/rules.md": {
|
||||
name: "Component Rules",
|
||||
rule: "Use functional components",
|
||||
globs: ["**/*.tsx", "**/*.jsx"],
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
},
|
||||
".continue/rules.md": {
|
||||
name: "Global Rules",
|
||||
rule: "Follow project guidelines",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: ".continue/rules.md",
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ describe("Rule Colocation Application", () => {
|
|||
{
|
||||
name: "Root Rule",
|
||||
rule: "Follow project standards",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: ".continue/rules.md",
|
||||
},
|
||||
|
||||
|
|
@ -24,7 +24,7 @@ describe("Rule Colocation Application", () => {
|
|||
{
|
||||
name: "React Components Rule",
|
||||
rule: "Use functional components with hooks",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
// No explicit globs - should implicitly only apply to files in that directory
|
||||
},
|
||||
|
|
@ -34,7 +34,7 @@ describe("Rule Colocation Application", () => {
|
|||
name: "Redux Rule",
|
||||
rule: "Use Redux Toolkit for state management",
|
||||
globs: "src/redux/**/*.{ts,tsx}",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/redux/rules.md",
|
||||
},
|
||||
|
||||
|
|
@ -43,7 +43,7 @@ describe("Rule Colocation Application", () => {
|
|||
name: "TypeScript Components Rule",
|
||||
rule: "Use TypeScript with React components",
|
||||
globs: "**/*.tsx", // Only apply to .tsx files
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
},
|
||||
|
||||
|
|
@ -52,7 +52,7 @@ describe("Rule Colocation Application", () => {
|
|||
name: "API Utils Rule",
|
||||
rule: "Follow API utility conventions",
|
||||
globs: "**/*.ts", // Only TypeScript files in this directory
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/utils/api/rules.md",
|
||||
},
|
||||
];
|
||||
|
|
@ -183,7 +183,7 @@ describe("Rule Colocation Application", () => {
|
|||
const impliedComponentRule: RuleWithSource = {
|
||||
name: "Implied Components Rule",
|
||||
rule: "Use React component best practices",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
// No explicit globs - should infer from directory
|
||||
};
|
||||
|
|
@ -233,7 +233,7 @@ describe("Rule Colocation Application", () => {
|
|||
name: "TypeScript Component Rule",
|
||||
rule: "Use TypeScript with React components",
|
||||
globs: "**/*.tsx", // Only apply to .tsx files
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
|
|
@ -280,7 +280,7 @@ describe("Rule Colocation Application", () => {
|
|||
name: "API Utils Rule",
|
||||
rule: "Follow API utility conventions",
|
||||
globs: "**/*.ts", // Only TypeScript files in this directory
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/utils/api/rules.md",
|
||||
};
|
||||
|
||||
|
|
@ -323,7 +323,7 @@ describe("Rule Colocation Application", () => {
|
|||
return {
|
||||
name: `Inferred Rule for ${directory}`,
|
||||
rule: `Follow standards for ${directory}`,
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: ruleFilePath,
|
||||
// In a fixed implementation, these globs would be automatically inferred
|
||||
// globs: expectedGlob,
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ import { Telemetry } from "../../util/posthog";
|
|||
import { TTS } from "../../util/tts";
|
||||
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
|
||||
import { loadContinueConfigFromJson } from "../load";
|
||||
import { loadCodebaseRules } from "../markdown/loadCodebaseRules";
|
||||
import { CodebaseRulesCache } from "../markdown/loadCodebaseRules";
|
||||
import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
|
||||
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
|
||||
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
|
||||
|
|
@ -165,10 +165,9 @@ export default async function doLoadConfig(options: {
|
|||
}
|
||||
|
||||
// Add rules from colocated rules.md files in the codebase
|
||||
const { rules: codebaseRules, errors: codebaseRulesErrors } =
|
||||
await loadCodebaseRules(ide);
|
||||
newConfig.rules.unshift(...codebaseRules);
|
||||
errors.push(...codebaseRulesErrors);
|
||||
const codebaseRulesCache = CodebaseRulesCache.getInstance();
|
||||
newConfig.rules.unshift(...codebaseRulesCache.rules);
|
||||
errors.push(...codebaseRulesCache.errors);
|
||||
|
||||
// Rectify model selections for each role
|
||||
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
|
||||
|
|
|
|||
|
|
@ -19,7 +19,6 @@ export const sharedConfigSchema = z
|
|||
readResponseTTS: z.boolean(),
|
||||
promptPath: z.string(),
|
||||
useCurrentFileAsContext: z.boolean(),
|
||||
logEditingData: z.boolean(),
|
||||
optInNextEditFeature: z.boolean(),
|
||||
enableExperimentalTools: z.boolean(),
|
||||
codebaseToolCallingOnly: z.boolean(),
|
||||
|
|
@ -181,9 +180,6 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
configCopy.experimental.useCurrentFileAsContext =
|
||||
sharedConfig.useCurrentFileAsContext;
|
||||
}
|
||||
if (sharedConfig.logEditingData !== undefined) {
|
||||
configCopy.experimental.logEditingData = sharedConfig.logEditingData;
|
||||
}
|
||||
if (sharedConfig.optInNextEditFeature !== undefined) {
|
||||
configCopy.experimental.optInNextEditFeature =
|
||||
sharedConfig.optInNextEditFeature;
|
||||
|
|
|
|||
|
|
@ -235,6 +235,8 @@ async function configYamlToContinueConfig(options: {
|
|||
startUrl: doc.startUrl,
|
||||
rootUrl: doc.rootUrl,
|
||||
faviconUrl: doc.faviconUrl,
|
||||
maxDepth: doc.maxDepth,
|
||||
useLocalCrawling: doc.useLocalCrawling,
|
||||
}));
|
||||
|
||||
config.mcpServers?.forEach((mcpServer) => {
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ import { BuiltInToolNames } from "../../../tools/builtIn";
|
|||
import { callBuiltInTool } from "../../../tools/callTool";
|
||||
import { globSearchTool } from "../../../tools/definitions/globSearch";
|
||||
import { grepSearchTool } from "../../../tools/definitions/grepSearch";
|
||||
import { lsTool } from "../../../tools/definitions/lsTool";
|
||||
import { lsTool } from "../../../tools/definitions/ls";
|
||||
import { readFileTool } from "../../../tools/definitions/readFile";
|
||||
import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap";
|
||||
import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory";
|
||||
|
|
@ -60,12 +60,13 @@ export interface IRetrievalPipeline {
|
|||
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
||||
private ftsIndex = new FullTextSearchCodebaseIndex();
|
||||
private lanceDbIndex: LanceDbIndex | null = null;
|
||||
private lanceDbInitPromise: Promise<void> | null = null;
|
||||
|
||||
constructor(protected readonly options: RetrievalPipelineOptions) {
|
||||
void this.initLanceDb();
|
||||
}
|
||||
|
||||
private async initLanceDb() {
|
||||
protected async initLanceDb() {
|
||||
const embedModel = this.options.config.selectedModelByRole.embed;
|
||||
|
||||
if (!embedModel) {
|
||||
|
|
@ -77,6 +78,23 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
);
|
||||
}
|
||||
|
||||
protected async ensureLanceDbInitialized(): Promise<boolean> {
|
||||
if (this.lanceDbIndex) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (this.lanceDbInitPromise) {
|
||||
await this.lanceDbInitPromise;
|
||||
return this.lanceDbIndex !== null;
|
||||
}
|
||||
|
||||
this.lanceDbInitPromise = this.initLanceDb();
|
||||
await this.lanceDbInitPromise;
|
||||
this.lanceDbInitPromise = null; // clear after init
|
||||
|
||||
return this.lanceDbIndex !== null;
|
||||
}
|
||||
|
||||
private getCleanedTrigrams(
|
||||
query: RetrievalPipelineRunArguments["query"],
|
||||
): string[] {
|
||||
|
|
@ -163,7 +181,9 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
input: string,
|
||||
n: number,
|
||||
): Promise<Chunk[]> {
|
||||
if (!this.lanceDbIndex) {
|
||||
const initialized = await this.ensureLanceDbInitialized();
|
||||
|
||||
if (!initialized || !this.lanceDbIndex) {
|
||||
console.warn(
|
||||
"LanceDB index not available, skipping embeddings retrieval",
|
||||
);
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import {
|
|||
import fetch, { RequestInit, Response } from "node-fetch";
|
||||
|
||||
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
|
||||
import { IdeSettings, ModelDescription } from "../index.js";
|
||||
import { IdeInfo, IdeSettings, ModelDescription } from "../index.js";
|
||||
|
||||
import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
|
||||
import { getControlPlaneEnv } from "./env.js";
|
||||
|
|
@ -40,6 +40,7 @@ export class ControlPlaneClient {
|
|||
ControlPlaneSessionInfo | undefined
|
||||
>,
|
||||
private readonly ideSettingsPromise: Promise<IdeSettings>,
|
||||
private readonly ideInfoPromise: Promise<IdeInfo>,
|
||||
) {}
|
||||
|
||||
async resolveFQSNs(
|
||||
|
|
@ -86,11 +87,17 @@ export class ControlPlaneClient {
|
|||
|
||||
const env = await getControlPlaneEnv(this.ideSettingsPromise);
|
||||
const url = new URL(path, env.CONTROL_PLANE_URL).toString();
|
||||
const ideInfo = await this.ideInfoPromise;
|
||||
|
||||
const resp = await fetch(url, {
|
||||
...init,
|
||||
headers: {
|
||||
...init.headers,
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
...{
|
||||
"x-extension-version": ideInfo.extensionVersion,
|
||||
"x-is-prerelease": String(ideInfo.isPrerelease),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -132,7 +132,10 @@ function readMdmKeysWindows(): MdmKeys | undefined {
|
|||
try {
|
||||
// Use REG QUERY command to read registry values
|
||||
const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
|
||||
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
|
||||
const licenseKeyOutput = execSync(licenseKeyCmd, {
|
||||
encoding: "utf8",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
// Extract values from command output
|
||||
const licenseKey = extractRegValue(licenseKeyOutput);
|
||||
if (licenseKey) {
|
||||
|
|
@ -145,7 +148,10 @@ function readMdmKeysWindows(): MdmKeys | undefined {
|
|||
// Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
|
||||
try {
|
||||
const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
|
||||
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
|
||||
const licenseKeyOutput = execSync(licenseKeyCmd, {
|
||||
encoding: "utf8",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
// Extract values from command output
|
||||
const licenseKey = extractRegValue(licenseKeyOutput);
|
||||
if (licenseKey) {
|
||||
|
|
|
|||
147
core/core.ts
147
core/core.ts
|
|
@ -24,6 +24,7 @@ import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
|
|||
import { callTool } from "./tools/callTool";
|
||||
import { ChatDescriber } from "./util/chatDescriber";
|
||||
import { clipboardCache } from "./util/clipboardCache";
|
||||
import { compactConversation } from "./util/conversationCompaction";
|
||||
import { GlobalContext } from "./util/GlobalContext";
|
||||
import historyManager from "./util/history";
|
||||
import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
|
||||
|
|
@ -52,6 +53,7 @@ import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
|
|||
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
|
||||
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
|
||||
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
|
||||
import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
|
||||
import {
|
||||
setupLocalConfig,
|
||||
setupProviderConfig,
|
||||
|
|
@ -69,6 +71,7 @@ import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
|
|||
import { llmStreamChat } from "./llm/streamChat";
|
||||
import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
|
||||
import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
|
||||
import { NextEditProvider } from "./nextEdit/NextEditProvider";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import { OnboardingModes } from "./protocol/core";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
|
|
@ -88,6 +91,7 @@ export class Core {
|
|||
configHandler: ConfigHandler;
|
||||
codeBaseIndexer: CodebaseIndexer;
|
||||
completionProvider: CompletionProvider;
|
||||
nextEditProvider: NextEditProvider;
|
||||
private docsService: DocsService;
|
||||
private globalContext = new GlobalContext();
|
||||
llmLogger = new LLMLogger();
|
||||
|
|
@ -150,7 +154,7 @@ export class Core {
|
|||
);
|
||||
|
||||
MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
|
||||
void this.configHandler.reloadConfig();
|
||||
void this.configHandler.reloadConfig("MCP Connections refreshed");
|
||||
|
||||
// Refresh @mention dropdown submenu items for MCP providers
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
|
|
@ -233,6 +237,24 @@ export class Core {
|
|||
(..._) => Promise.resolve([]),
|
||||
);
|
||||
|
||||
const codebaseRulesCache = CodebaseRulesCache.getInstance();
|
||||
void codebaseRulesCache
|
||||
.refresh(ide)
|
||||
.catch((e) => console.error("Failed to initialize colocated rules cache"))
|
||||
.then(() => {
|
||||
void this.configHandler.reloadConfig(
|
||||
"Initial codebase rules post-walkdir/load reload",
|
||||
);
|
||||
});
|
||||
this.nextEditProvider = NextEditProvider.initialize(
|
||||
this.configHandler,
|
||||
ide,
|
||||
getLlm,
|
||||
(e) => {},
|
||||
(..._) => Promise.resolve([]),
|
||||
"fineTuned",
|
||||
);
|
||||
|
||||
this.registerMessageHandlers(ideSettingsPromise);
|
||||
}
|
||||
|
||||
|
|
@ -299,23 +321,31 @@ export class Core {
|
|||
on("config/addModel", (msg) => {
|
||||
const model = msg.data.model;
|
||||
addModel(model, msg.data.role);
|
||||
void this.configHandler.reloadConfig();
|
||||
void this.configHandler.reloadConfig(
|
||||
"Model added (config/addModel message)",
|
||||
);
|
||||
});
|
||||
|
||||
on("config/deleteModel", (msg) => {
|
||||
deleteModel(msg.data.title);
|
||||
void this.configHandler.reloadConfig();
|
||||
void this.configHandler.reloadConfig(
|
||||
"Model removed (config/deleteModel message)",
|
||||
);
|
||||
});
|
||||
|
||||
on("config/newPromptFile", async (msg) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
await createNewPromptFileV2(this.ide, config?.experimental?.promptPath);
|
||||
await this.configHandler.reloadConfig();
|
||||
await this.configHandler.reloadConfig(
|
||||
"Prompt file created (config/newPromptFile message)",
|
||||
);
|
||||
});
|
||||
|
||||
on("config/addLocalWorkspaceBlock", async (msg) => {
|
||||
await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
|
||||
await this.configHandler.reloadConfig();
|
||||
await this.configHandler.reloadConfig(
|
||||
"Local block created (config/addLocalWorkspaceBlock message)",
|
||||
);
|
||||
});
|
||||
|
||||
on("config/openProfile", async (msg) => {
|
||||
|
|
@ -323,8 +353,12 @@ export class Core {
|
|||
});
|
||||
|
||||
on("config/reload", async (msg) => {
|
||||
void this.configHandler.reloadConfig();
|
||||
return await this.configHandler.getSerializedConfig();
|
||||
// User force reloading will retrigger colocated rules
|
||||
const codebaseRulesCache = CodebaseRulesCache.getInstance();
|
||||
await codebaseRulesCache.refresh(this.ide);
|
||||
void this.configHandler.reloadConfig(
|
||||
"Force reloaded (config/reload message)",
|
||||
);
|
||||
});
|
||||
|
||||
on("config/ideSettingsUpdate", async (msg) => {
|
||||
|
|
@ -343,7 +377,9 @@ export class Core {
|
|||
|
||||
on("config/updateSharedConfig", async (msg) => {
|
||||
const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
|
||||
await this.configHandler.reloadConfig();
|
||||
await this.configHandler.reloadConfig(
|
||||
"Shared config update (config/updateSharedConfig message)",
|
||||
);
|
||||
return newSharedConfig;
|
||||
});
|
||||
|
||||
|
|
@ -353,7 +389,9 @@ export class Core {
|
|||
msg.data.role,
|
||||
msg.data.title,
|
||||
);
|
||||
await this.configHandler.reloadConfig();
|
||||
await this.configHandler.reloadConfig(
|
||||
"Selected model update (config/updateSelectedModel message)",
|
||||
);
|
||||
return newSelectedModels;
|
||||
});
|
||||
|
||||
|
|
@ -481,6 +519,18 @@ export class Core {
|
|||
});
|
||||
on("llm/listModels", this.handleListModels.bind(this));
|
||||
|
||||
on("llm/compileChat", async (msg) => {
|
||||
const { messages, options } = msg.data;
|
||||
const model = (await this.configHandler.loadConfig()).config
|
||||
?.selectedModelByRole.chat;
|
||||
|
||||
if (!model) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
return model.compileChatMessages(messages, options);
|
||||
});
|
||||
|
||||
// Provide messenger to utils so they can interact with GUI + state
|
||||
TTS.messenger = this.messenger;
|
||||
ChatDescriber.messenger = this.messenger;
|
||||
|
|
@ -500,6 +550,28 @@ export class Core {
|
|||
return await ChatDescriber.describe(currentModel, {}, msg.data.text);
|
||||
});
|
||||
|
||||
on("conversation/compact", async (msg) => {
|
||||
const currentModel = (await this.configHandler.loadConfig()).config
|
||||
?.selectedModelByRole.chat;
|
||||
|
||||
if (!currentModel) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
try {
|
||||
await compactConversation({
|
||||
sessionId: msg.data.sessionId,
|
||||
index: msg.data.index,
|
||||
historyManager,
|
||||
currentModel,
|
||||
});
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
console.error("Error compacting conversation:", error);
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
|
||||
// Autocomplete
|
||||
on("autocomplete/complete", async (msg) => {
|
||||
const outcome =
|
||||
|
|
@ -516,6 +588,21 @@ export class Core {
|
|||
this.completionProvider.cancel();
|
||||
});
|
||||
|
||||
// Next Edit
|
||||
on("nextEdit/predict", async (msg) => {
|
||||
const outcome = await this.nextEditProvider.provideInlineCompletionItems(
|
||||
msg.data,
|
||||
undefined,
|
||||
);
|
||||
return outcome ? [outcome.completion, outcome.originalEditableRange] : [];
|
||||
});
|
||||
on("nextEdit/accept", async (msg) => {
|
||||
this.nextEditProvider.accept(msg.data.completionId);
|
||||
});
|
||||
on("nextEdit/reject", async (msg) => {
|
||||
this.nextEditProvider.reject(msg.data.completionId);
|
||||
});
|
||||
|
||||
on("streamDiffLines", async (msg) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
|
|
@ -630,9 +717,12 @@ export class Core {
|
|||
void refreshIfNotIgnored(data.uris);
|
||||
|
||||
if (hasRulesFiles(data.uris)) {
|
||||
await this.configHandler.reloadConfig();
|
||||
const rulesCache = CodebaseRulesCache.getInstance();
|
||||
await Promise.all(
|
||||
data.uris.map((uri) => rulesCache.update(this.ide, uri)),
|
||||
);
|
||||
await this.configHandler.reloadConfig("Rules file created");
|
||||
}
|
||||
|
||||
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
|
||||
let localAssistantCreated = false;
|
||||
for (const uri of data.uris) {
|
||||
|
|
@ -652,7 +742,9 @@ export class Core {
|
|||
void refreshIfNotIgnored(data.uris);
|
||||
|
||||
if (hasRulesFiles(data.uris)) {
|
||||
await this.configHandler.reloadConfig();
|
||||
const rulesCache = CodebaseRulesCache.getInstance();
|
||||
data.uris.forEach((uri) => rulesCache.remove(uri));
|
||||
await this.configHandler.reloadConfig("Codebase rule file deleted");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -928,7 +1020,7 @@ export class Core {
|
|||
],
|
||||
}),
|
||||
);
|
||||
void this.configHandler.reloadConfig();
|
||||
void this.configHandler.reloadConfig("Autocomplete model added");
|
||||
}
|
||||
|
||||
private async handleFilesChanged({
|
||||
|
|
@ -958,7 +1050,9 @@ export class Core {
|
|||
this.globalContext.update("showConfigUpdateToast", false);
|
||||
}
|
||||
}
|
||||
await this.configHandler.reloadConfig();
|
||||
await this.configHandler.reloadConfig(
|
||||
"Current profile config file updated",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -966,15 +1060,24 @@ export class Core {
|
|||
uri.endsWith(".continuerc.json") ||
|
||||
uri.endsWith(".prompt") ||
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
|
||||
(uri.includes(".continue") && uri.endsWith(".yaml")) ||
|
||||
uri.endsWith(RULES_MARKDOWN_FILENAME) ||
|
||||
BLOCK_TYPES.some(
|
||||
(blockType) =>
|
||||
uri.includes(`.continue/${blockType}`) ||
|
||||
uri.includes(`.continue\\${blockType}`),
|
||||
(uri.includes(".continue") &&
|
||||
(uri.endsWith(".yaml") || uri.endsWith("yml"))) ||
|
||||
BLOCK_TYPES.some((blockType) =>
|
||||
uri.includes(`.continue/${blockType}`),
|
||||
)
|
||||
) {
|
||||
await this.configHandler.reloadConfig();
|
||||
await this.configHandler.reloadConfig(
|
||||
"Config-related file updated: continuerc, prompt, local block, etc",
|
||||
);
|
||||
} else if (uri.endsWith(RULES_MARKDOWN_FILENAME)) {
|
||||
try {
|
||||
const codebaseRulesCache = CodebaseRulesCache.getInstance();
|
||||
void codebaseRulesCache.update(this.ide, uri).then(() => {
|
||||
void this.configHandler.reloadConfig("Codebase rule update");
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Failed to update codebase rule", e);
|
||||
}
|
||||
} else if (
|
||||
uri.endsWith(".continueignore") ||
|
||||
uri.endsWith(".gitignore")
|
||||
|
|
@ -1056,7 +1159,7 @@ export class Core {
|
|||
|
||||
editConfigFile((c) => c, editConfigYamlCallback);
|
||||
|
||||
void this.configHandler.reloadConfig();
|
||||
void this.configHandler.reloadConfig("Onboarding completed");
|
||||
}
|
||||
|
||||
private getContextItems = async (
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { diffLines, type Change } from "diff";
|
||||
import { diffChars, diffLines, type Change } from "diff";
|
||||
|
||||
import { DiffLine } from "..";
|
||||
import { DiffChar, DiffLine } from "..";
|
||||
|
||||
export function convertMyersChangeToDiffLines(change: Change): DiffLine[] {
|
||||
const type: DiffLine["type"] = change.added
|
||||
|
|
@ -55,3 +55,157 @@ export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
|
|||
|
||||
return ourFormat;
|
||||
}
|
||||
|
||||
export function myersCharDiff(
|
||||
oldContent: string,
|
||||
newContent: string,
|
||||
): DiffChar[] {
|
||||
// Process the content character by character.
|
||||
// We will handle newlines separately,
|
||||
// because diffChars does not have an option to ignore eol newlines.
|
||||
const theirFormat = diffChars(oldContent, newContent);
|
||||
|
||||
// Track indices as we process the diff.
|
||||
let oldIndex = 0;
|
||||
let newIndex = 0;
|
||||
let oldLineIndex = 0;
|
||||
let newLineIndex = 0;
|
||||
let oldCharIndexInLine = 0;
|
||||
let newCharIndexInLine = 0;
|
||||
|
||||
const result: DiffChar[] = [];
|
||||
|
||||
for (const change of theirFormat) {
|
||||
// Split the change value by newlines to handle them separately.
|
||||
if (change.value.includes("\n")) {
|
||||
const parts = change.value.split(/(\n)/g); // This keeps the newlines as separate entries.
|
||||
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
if (part === "") continue;
|
||||
|
||||
if (part === "\n") {
|
||||
// Handle newline.
|
||||
if (change.added) {
|
||||
result.push({
|
||||
type: "new",
|
||||
char: part,
|
||||
newIndex: newIndex,
|
||||
newLineIndex: newLineIndex,
|
||||
newCharIndexInLine: newCharIndexInLine,
|
||||
});
|
||||
newIndex += part.length;
|
||||
newLineIndex++;
|
||||
newCharIndexInLine = 0; // Reset when moving to a new line.
|
||||
} else if (change.removed) {
|
||||
result.push({
|
||||
type: "old",
|
||||
char: part,
|
||||
oldIndex: oldIndex,
|
||||
oldLineIndex: oldLineIndex,
|
||||
oldCharIndexInLine: oldCharIndexInLine,
|
||||
});
|
||||
oldIndex += part.length;
|
||||
oldLineIndex++;
|
||||
oldCharIndexInLine = 0; // Reset when moving to a new line.
|
||||
} else {
|
||||
result.push({
|
||||
type: "same",
|
||||
char: part,
|
||||
oldIndex: oldIndex,
|
||||
newIndex: newIndex,
|
||||
oldLineIndex: oldLineIndex,
|
||||
newLineIndex: newLineIndex,
|
||||
oldCharIndexInLine: oldCharIndexInLine,
|
||||
newCharIndexInLine: newCharIndexInLine,
|
||||
});
|
||||
oldIndex += part.length;
|
||||
newIndex += part.length;
|
||||
oldLineIndex++;
|
||||
newLineIndex++;
|
||||
oldCharIndexInLine = 0;
|
||||
newCharIndexInLine = 0;
|
||||
}
|
||||
} else {
|
||||
// Handle regular text.
|
||||
if (change.added) {
|
||||
result.push({
|
||||
type: "new",
|
||||
char: part,
|
||||
newIndex: newIndex,
|
||||
newLineIndex: newLineIndex,
|
||||
newCharIndexInLine: newCharIndexInLine,
|
||||
});
|
||||
newIndex += part.length;
|
||||
newCharIndexInLine += part.length;
|
||||
} else if (change.removed) {
|
||||
result.push({
|
||||
type: "old",
|
||||
char: part,
|
||||
oldIndex: oldIndex,
|
||||
oldLineIndex: oldLineIndex,
|
||||
oldCharIndexInLine: oldCharIndexInLine,
|
||||
});
|
||||
oldIndex += part.length;
|
||||
oldCharIndexInLine += part.length;
|
||||
} else {
|
||||
result.push({
|
||||
type: "same",
|
||||
char: part,
|
||||
oldIndex: oldIndex,
|
||||
newIndex: newIndex,
|
||||
oldLineIndex: oldLineIndex,
|
||||
newLineIndex: newLineIndex,
|
||||
oldCharIndexInLine: oldCharIndexInLine,
|
||||
newCharIndexInLine: newCharIndexInLine,
|
||||
});
|
||||
oldIndex += part.length;
|
||||
newIndex += part.length;
|
||||
oldCharIndexInLine += part.length;
|
||||
newCharIndexInLine += part.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No newlines, handle as a simple change.
|
||||
if (change.added) {
|
||||
result.push({
|
||||
type: "new",
|
||||
char: change.value,
|
||||
newIndex: newIndex,
|
||||
newLineIndex: newLineIndex,
|
||||
newCharIndexInLine: newCharIndexInLine,
|
||||
});
|
||||
newIndex += change.value.length;
|
||||
newCharIndexInLine += change.value.length;
|
||||
} else if (change.removed) {
|
||||
result.push({
|
||||
type: "old",
|
||||
char: change.value,
|
||||
oldIndex: oldIndex,
|
||||
oldLineIndex: oldLineIndex,
|
||||
oldCharIndexInLine: oldCharIndexInLine,
|
||||
});
|
||||
oldIndex += change.value.length;
|
||||
oldCharIndexInLine += change.value.length;
|
||||
} else {
|
||||
result.push({
|
||||
type: "same",
|
||||
char: change.value,
|
||||
oldIndex: oldIndex,
|
||||
newIndex: newIndex,
|
||||
oldLineIndex: oldLineIndex,
|
||||
newLineIndex: newLineIndex,
|
||||
oldCharIndexInLine: oldCharIndexInLine,
|
||||
newCharIndexInLine: newCharIndexInLine,
|
||||
});
|
||||
oldIndex += change.value.length;
|
||||
newIndex += change.value.length;
|
||||
oldCharIndexInLine += change.value.length;
|
||||
newCharIndexInLine += change.value.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
|
|||
|
||||
import { dedent } from "../util";
|
||||
|
||||
import { myersDiff } from "./myers";
|
||||
import { myersCharDiff, myersDiff } from "./myers";
|
||||
|
||||
describe("Test myers diff function", () => {
|
||||
test("should ...", () => {
|
||||
|
|
@ -56,3 +56,589 @@ describe("Test myers diff function", () => {
|
|||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Test myersCharDiff function on the same line", () => {
|
||||
test("should differentiate character changes", () => {
|
||||
const oldContent = "hello world";
|
||||
const newContent = "hello earth";
|
||||
|
||||
const diffChars = myersCharDiff(oldContent, newContent);
|
||||
expect(diffChars).toEqual([
|
||||
{
|
||||
type: "same",
|
||||
char: "hello ",
|
||||
oldIndex: 0,
|
||||
newIndex: 0,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "wo",
|
||||
oldIndex: 6,
|
||||
oldCharIndexInLine: 6,
|
||||
oldLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "ea",
|
||||
newIndex: 6,
|
||||
newCharIndexInLine: 6,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "r",
|
||||
oldIndex: 8,
|
||||
newIndex: 8,
|
||||
oldCharIndexInLine: 8,
|
||||
newCharIndexInLine: 8,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "ld",
|
||||
oldIndex: 9,
|
||||
oldCharIndexInLine: 9,
|
||||
oldLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "th",
|
||||
newIndex: 9,
|
||||
newCharIndexInLine: 9,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("should handle insertions", () => {
|
||||
const oldContent = "abc";
|
||||
const newContent = "abxyzc";
|
||||
|
||||
const diffChars = myersCharDiff(oldContent, newContent);
|
||||
expect(diffChars).toEqual([
|
||||
{
|
||||
type: "same",
|
||||
char: "ab",
|
||||
oldIndex: 0,
|
||||
newIndex: 0,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "xyz",
|
||||
newIndex: 2,
|
||||
newCharIndexInLine: 2,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "c",
|
||||
oldIndex: 2,
|
||||
newIndex: 5,
|
||||
oldCharIndexInLine: 2,
|
||||
newCharIndexInLine: 5,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("should handle deletions", () => {
|
||||
const oldContent = "abxyzc";
|
||||
const newContent = "abc";
|
||||
|
||||
const diffChars = myersCharDiff(oldContent, newContent);
|
||||
expect(diffChars).toEqual([
|
||||
{
|
||||
type: "same",
|
||||
char: "ab",
|
||||
oldIndex: 0,
|
||||
newIndex: 0,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "xyz",
|
||||
oldIndex: 2,
|
||||
oldCharIndexInLine: 2,
|
||||
oldLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "c",
|
||||
oldIndex: 5,
|
||||
newIndex: 2,
|
||||
oldCharIndexInLine: 5,
|
||||
newCharIndexInLine: 2,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("should handle empty strings", () => {
|
||||
const oldContent = "";
|
||||
const newContent = "abc";
|
||||
|
||||
const diffChars = myersCharDiff(oldContent, newContent);
|
||||
expect(diffChars).toEqual([
|
||||
{
|
||||
type: "new",
|
||||
char: "abc",
|
||||
newIndex: 0,
|
||||
newCharIndexInLine: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("should handle identical strings", () => {
|
||||
const content = "no changes here";
|
||||
|
||||
const diffChars = myersCharDiff(content, content);
|
||||
expect(diffChars).toEqual([
|
||||
{
|
||||
type: "same",
|
||||
char: "no changes here",
|
||||
oldIndex: 0,
|
||||
newIndex: 0,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("should handle whitespace changes", () => {
|
||||
const oldContent = "hello world";
|
||||
const newContent = "hello world";
|
||||
|
||||
const diffChars = myersCharDiff(oldContent, newContent);
|
||||
expect(diffChars).toEqual([
|
||||
{
|
||||
type: "same",
|
||||
char: "hello ",
|
||||
oldIndex: 0,
|
||||
newIndex: 0,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: " ",
|
||||
newIndex: 6,
|
||||
newCharIndexInLine: 6,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "world",
|
||||
oldIndex: 6,
|
||||
newIndex: 7,
|
||||
oldCharIndexInLine: 6,
|
||||
newCharIndexInLine: 7,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("should handle complex changes", () => {
|
||||
const oldContent = "The quick brown fox jumps over the lazy dog";
|
||||
const newContent = "The fast brown fox leaps over the sleeping dog";
|
||||
|
||||
const diffChars = myersCharDiff(oldContent, newContent);
|
||||
expect(diffChars).toEqual([
|
||||
{
|
||||
type: "same",
|
||||
char: "The ",
|
||||
oldIndex: 0,
|
||||
newIndex: 0,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "quick",
|
||||
oldIndex: 4,
|
||||
oldCharIndexInLine: 4,
|
||||
oldLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "fast",
|
||||
newIndex: 4,
|
||||
newCharIndexInLine: 4,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: " brown fox ",
|
||||
oldIndex: 9,
|
||||
newIndex: 8,
|
||||
oldCharIndexInLine: 9,
|
||||
newCharIndexInLine: 8,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "jum",
|
||||
oldIndex: 20,
|
||||
oldCharIndexInLine: 20,
|
||||
oldLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "lea",
|
||||
newIndex: 19,
|
||||
newCharIndexInLine: 19,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "ps over the ",
|
||||
oldIndex: 23,
|
||||
newIndex: 22,
|
||||
oldCharIndexInLine: 23,
|
||||
newCharIndexInLine: 22,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "s",
|
||||
newIndex: 34,
|
||||
newCharIndexInLine: 34,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "l",
|
||||
oldIndex: 35,
|
||||
newIndex: 35,
|
||||
oldCharIndexInLine: 35,
|
||||
newCharIndexInLine: 35,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "azy",
|
||||
oldIndex: 36,
|
||||
oldCharIndexInLine: 36,
|
||||
oldLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "eeping",
|
||||
newIndex: 36,
|
||||
newCharIndexInLine: 36,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: " dog",
|
||||
oldIndex: 39,
|
||||
newIndex: 42,
|
||||
oldCharIndexInLine: 39,
|
||||
newCharIndexInLine: 42,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Test myersCharDiff function on different lines", () => {
|
||||
test("should track line indices for multi-line changes", () => {
|
||||
const oldContent = ["Line one", "Line two", "Line three"].join("\n");
|
||||
|
||||
const newContent = ["Line one", "Modified line", "Line three"].join("\n");
|
||||
|
||||
const diffChars = myersCharDiff(oldContent, newContent);
|
||||
expect(diffChars).toEqual([
|
||||
{
|
||||
type: "same",
|
||||
char: "Line one",
|
||||
oldIndex: 0,
|
||||
newIndex: 0,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "\n",
|
||||
oldIndex: 8,
|
||||
newIndex: 8,
|
||||
oldCharIndexInLine: 8,
|
||||
newCharIndexInLine: 8,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "L",
|
||||
oldIndex: 9,
|
||||
oldCharIndexInLine: 0,
|
||||
oldLineIndex: 1,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "Mod",
|
||||
newIndex: 9,
|
||||
newCharIndexInLine: 0,
|
||||
newLineIndex: 1,
|
||||
},
|
||||
{
|
||||
char: "i",
|
||||
newCharIndexInLine: 3,
|
||||
newIndex: 12,
|
||||
newLineIndex: 1,
|
||||
oldCharIndexInLine: 1,
|
||||
oldIndex: 10,
|
||||
oldLineIndex: 1,
|
||||
type: "same",
|
||||
},
|
||||
{
|
||||
char: "n",
|
||||
oldCharIndexInLine: 2,
|
||||
oldIndex: 11,
|
||||
oldLineIndex: 1,
|
||||
type: "old",
|
||||
},
|
||||
{
|
||||
char: "fi",
|
||||
newCharIndexInLine: 4,
|
||||
newIndex: 13,
|
||||
newLineIndex: 1,
|
||||
type: "new",
|
||||
},
|
||||
{
|
||||
char: "e",
|
||||
newCharIndexInLine: 6,
|
||||
newIndex: 15,
|
||||
newLineIndex: 1,
|
||||
oldCharIndexInLine: 3,
|
||||
oldIndex: 12,
|
||||
oldLineIndex: 1,
|
||||
type: "same",
|
||||
},
|
||||
{
|
||||
char: "d",
|
||||
newCharIndexInLine: 7,
|
||||
newIndex: 16,
|
||||
newLineIndex: 1,
|
||||
type: "new",
|
||||
},
|
||||
{
|
||||
char: " ",
|
||||
newCharIndexInLine: 8,
|
||||
newIndex: 17,
|
||||
newLineIndex: 1,
|
||||
oldCharIndexInLine: 4,
|
||||
oldIndex: 13,
|
||||
oldLineIndex: 1,
|
||||
type: "same",
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "two",
|
||||
oldCharIndexInLine: 5,
|
||||
oldIndex: 14,
|
||||
oldLineIndex: 1,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "line",
|
||||
newCharIndexInLine: 9,
|
||||
newIndex: 18,
|
||||
newLineIndex: 1,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "\n",
|
||||
oldIndex: 17,
|
||||
oldCharIndexInLine: 8,
|
||||
oldLineIndex: 1,
|
||||
newIndex: 22,
|
||||
newCharIndexInLine: 13,
|
||||
newLineIndex: 1,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "Line three",
|
||||
oldIndex: 18,
|
||||
newIndex: 23,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 2,
|
||||
newLineIndex: 2,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("should track line indices when adding new lines", () => {
|
||||
const oldContent = ["First line", "Last line"].join("\n");
|
||||
|
||||
const newContent = [
|
||||
"First line",
|
||||
"Middle line",
|
||||
"Another middle",
|
||||
"Last line",
|
||||
].join("\n");
|
||||
|
||||
const diffChars = myersCharDiff(oldContent, newContent);
|
||||
expect(diffChars).toEqual([
|
||||
{
|
||||
type: "same",
|
||||
char: "First line",
|
||||
oldIndex: 0,
|
||||
newIndex: 0,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "\n",
|
||||
oldIndex: 10,
|
||||
newIndex: 10,
|
||||
oldCharIndexInLine: 10,
|
||||
newCharIndexInLine: 10,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "Middle line",
|
||||
newIndex: 11,
|
||||
newCharIndexInLine: 0,
|
||||
newLineIndex: 1,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "\n",
|
||||
newIndex: 22,
|
||||
newCharIndexInLine: 11,
|
||||
newLineIndex: 1,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "Another middle",
|
||||
newCharIndexInLine: 0,
|
||||
newIndex: 23,
|
||||
newLineIndex: 2,
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
char: "\n",
|
||||
newCharIndexInLine: 14,
|
||||
newIndex: 37,
|
||||
newLineIndex: 2,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "Last line",
|
||||
oldIndex: 11,
|
||||
oldCharIndexInLine: 0,
|
||||
oldLineIndex: 1,
|
||||
newIndex: 38,
|
||||
newCharIndexInLine: 0,
|
||||
newLineIndex: 3,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("should track line indices when removing lines", () => {
|
||||
const oldContent = [
|
||||
"Start",
|
||||
"Line to remove",
|
||||
"Another to remove",
|
||||
"End",
|
||||
].join("\n");
|
||||
|
||||
const newContent = ["Start", "End"].join("\n");
|
||||
|
||||
const diffChars = myersCharDiff(oldContent, newContent);
|
||||
expect(diffChars).toEqual([
|
||||
{
|
||||
type: "same",
|
||||
char: "Start",
|
||||
oldIndex: 0,
|
||||
newIndex: 0,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "\n",
|
||||
oldIndex: 5,
|
||||
newIndex: 5,
|
||||
oldCharIndexInLine: 5,
|
||||
newCharIndexInLine: 5,
|
||||
oldLineIndex: 0,
|
||||
newLineIndex: 0,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "Line to remove",
|
||||
oldIndex: 6,
|
||||
oldCharIndexInLine: 0,
|
||||
oldLineIndex: 1,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "\n",
|
||||
oldCharIndexInLine: 14,
|
||||
oldIndex: 20,
|
||||
oldLineIndex: 1,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "Another to remove",
|
||||
oldCharIndexInLine: 0,
|
||||
oldIndex: 21,
|
||||
oldLineIndex: 2,
|
||||
},
|
||||
{
|
||||
type: "old",
|
||||
char: "\n",
|
||||
oldCharIndexInLine: 17,
|
||||
oldIndex: 38,
|
||||
oldLineIndex: 2,
|
||||
},
|
||||
{
|
||||
type: "same",
|
||||
char: "End",
|
||||
oldIndex: 39,
|
||||
newIndex: 6,
|
||||
oldCharIndexInLine: 0,
|
||||
newCharIndexInLine: 0,
|
||||
oldLineIndex: 3,
|
||||
newLineIndex: 1,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { DiffLine, DiffLineType } from "../index.js";
|
||||
import { DiffLine, DiffType } from "../index.js";
|
||||
|
||||
import { LineStream, matchLine } from "./util.js";
|
||||
|
||||
|
|
@ -33,7 +33,7 @@ export async function* streamDiff(
|
|||
seenIndentationMistake = true;
|
||||
}
|
||||
|
||||
let type: DiffLineType;
|
||||
let type: DiffType;
|
||||
|
||||
const isNewLine = matchIndex === -1;
|
||||
|
||||
|
|
|
|||
|
|
@ -6,11 +6,11 @@ import { describe, expect, test } from "vitest";
|
|||
// @ts-ignore no typings available
|
||||
import { changed, diff as myersDiff } from "myers-diff";
|
||||
import { streamDiff } from "../diff/streamDiff.js";
|
||||
import { DiffLine, DiffLineType } from "../index.js";
|
||||
import { DiffLine, DiffType } from "../index.js";
|
||||
import { generateLines } from "./util.js";
|
||||
|
||||
// "modification" is an extra type used to represent an "old" + "new" diff line
|
||||
type MyersDiffTypes = Extract<DiffLineType, "new" | "old"> | "modification";
|
||||
type MyersDiffTypes = Extract<DiffType, "new" | "old"> | "modification";
|
||||
|
||||
const UNIFIED_DIFF_SYMBOLS = {
|
||||
same: "",
|
||||
|
|
|
|||
84
core/index.d.ts
vendored
84
core/index.d.ts
vendored
|
|
@ -122,6 +122,7 @@ export interface ILLM
|
|||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options?: LLMFullCompletionOptions,
|
||||
messageOptions?: MessageOption,
|
||||
): AsyncGenerator<ChatMessage, PromptLog>;
|
||||
|
||||
chat(
|
||||
|
|
@ -130,6 +131,11 @@ export interface ILLM
|
|||
options?: LLMFullCompletionOptions,
|
||||
): Promise<ChatMessage>;
|
||||
|
||||
compileChatMessages(
|
||||
messages: ChatMessage[],
|
||||
options: LLMFullCompletionOpeions,
|
||||
): CompiledChatMessagesReport;
|
||||
|
||||
embed(chunks: string[]): Promise<number[][]>;
|
||||
|
||||
rerank(query: string, chunks: Chunk[]): Promise<number[]>;
|
||||
|
|
@ -363,10 +369,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 {
|
||||
|
|
@ -432,12 +460,12 @@ export interface PromptLog {
|
|||
export type MessageModes = "chat" | "agent" | "plan";
|
||||
|
||||
export type ToolStatus =
|
||||
| "generating"
|
||||
| "generated"
|
||||
| "calling"
|
||||
| "errored"
|
||||
| "done"
|
||||
| "canceled";
|
||||
| "generating" // Tool call arguments are being streamed from the LLM
|
||||
| "generated" // Tool call is complete and ready for execution (awaiting approval)
|
||||
| "calling" // Tool is actively being executed
|
||||
| "errored" // Tool execution failed with an error
|
||||
| "done" // Tool execution completed successfully
|
||||
| "canceled"; // Tool call was canceled by user or system
|
||||
|
||||
// Will exist only on "assistant" messages with tool calls
|
||||
interface ToolCallState {
|
||||
|
|
@ -462,10 +490,11 @@ export interface ChatHistoryItem {
|
|||
editorState?: any;
|
||||
modifiers?: InputModifiers;
|
||||
promptLogs?: PromptLog[];
|
||||
toolCallState?: ToolCallState;
|
||||
toolCallStates?: ToolCallState[];
|
||||
isGatheringContext?: boolean;
|
||||
reasoning?: Reasoning;
|
||||
appliedRules?: RuleWithSource[];
|
||||
conversationSummary?: string;
|
||||
}
|
||||
|
||||
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
|
||||
|
|
@ -484,12 +513,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 {
|
||||
|
|
@ -497,6 +528,7 @@ export interface LLMInteractionStartFim extends LLMInteractionBase {
|
|||
prefix: string;
|
||||
suffix: string;
|
||||
options: CompletionOptions;
|
||||
provider: string;
|
||||
}
|
||||
|
||||
export interface LLMInteractionChunk extends LLMInteractionBase {
|
||||
|
|
@ -513,6 +545,7 @@ export interface LLMInteractionEnd extends LLMInteractionBase {
|
|||
promptTokens: number;
|
||||
generatedTokens: number;
|
||||
thinkingTokens: number;
|
||||
usage: Usage | undefined;
|
||||
}
|
||||
|
||||
export interface LLMInteractionSuccess extends LLMInteractionEnd {
|
||||
|
|
@ -666,13 +699,26 @@ export type CustomLLM = RequireAtLeastOne<
|
|||
|
||||
// IDE
|
||||
|
||||
export type DiffLineType = "new" | "old" | "same";
|
||||
export type DiffType = "new" | "old" | "same";
|
||||
|
||||
export interface DiffLine {
|
||||
type: DiffLineType;
|
||||
export interface DiffObject {
|
||||
type: DiffType;
|
||||
}
|
||||
|
||||
export interface DiffLine extends DiffObject {
|
||||
line: string;
|
||||
}
|
||||
|
||||
interface DiffChar extends DiffObject {
|
||||
char: string;
|
||||
oldIndex?: number; // Character index assuming a flattened line string.
|
||||
newIndex?: number;
|
||||
oldCharIndexInLine?: number; // Character index assuming new lines reset the character index to 0.
|
||||
newCharIndexInLine?: number;
|
||||
oldLineIndex?: number;
|
||||
newLineIndex?: number;
|
||||
}
|
||||
|
||||
export interface Problem {
|
||||
filepath: string;
|
||||
range: Range;
|
||||
|
|
@ -692,6 +738,7 @@ export interface IdeInfo {
|
|||
version: string;
|
||||
remoteName: string;
|
||||
extensionVersion: string;
|
||||
isPrerelease: boolean;
|
||||
}
|
||||
|
||||
export interface BranchAndDir {
|
||||
|
|
@ -1269,7 +1316,6 @@ export interface ContinueUIConfig {
|
|||
codeWrap?: boolean;
|
||||
showSessionTabs?: boolean;
|
||||
autoAcceptEditToolDiffs?: boolean;
|
||||
logEditingData?: boolean;
|
||||
}
|
||||
|
||||
export interface ContextMenuConfig {
|
||||
|
|
@ -1422,11 +1468,6 @@ export interface ExperimentalConfig {
|
|||
*/
|
||||
useCurrentFileAsContext?: boolean;
|
||||
|
||||
/**
|
||||
* If enabled, will save data on the user's editing processes
|
||||
*/
|
||||
logEditingData?: boolean;
|
||||
|
||||
/**
|
||||
* If enabled, will enable next edit in place of autocomplete
|
||||
*/
|
||||
|
|
@ -1650,6 +1691,7 @@ export type RuleSource =
|
|||
| "model-options-plan"
|
||||
| "model-options-agent"
|
||||
| "rules-block"
|
||||
| "colocated-markdown"
|
||||
| "json-systemMessage"
|
||||
| ".continuerules";
|
||||
|
||||
|
|
@ -1669,3 +1711,13 @@ export interface CompleteOnboardingPayload {
|
|||
provider?: string;
|
||||
apiKey?: string;
|
||||
}
|
||||
|
||||
export interface CompiledMessagesResult {
|
||||
compiledChatMessages: ChatMessage[];
|
||||
didPrune: boolean;
|
||||
contextPercentage: number;
|
||||
}
|
||||
|
||||
export interface MessageOption {
|
||||
precompiled: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
/* eslint-disable max-lines-per-function */
|
||||
/* lint is not useful for test classes */
|
||||
import { jest } from "@jest/globals";
|
||||
import { execSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
|
|
@ -14,8 +16,11 @@ import {
|
|||
} from "../test/testDir.js";
|
||||
import { getIndexSqlitePath } from "../util/paths.js";
|
||||
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
|
||||
import { ContinueConfig } from "../index.js";
|
||||
import { localPathToUri } from "../util/pathToUri.js";
|
||||
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
|
||||
import { CodebaseIndexer } from "./CodebaseIndexer.js";
|
||||
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
|
||||
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
|
||||
import { CodebaseIndex } from "./types.js";
|
||||
|
|
@ -57,6 +62,17 @@ class TestCodebaseIndexer extends CodebaseIndexer {
|
|||
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
|
||||
return [new TestCodebaseIndex()];
|
||||
}
|
||||
|
||||
// Add public methods to test private methods
|
||||
public testHasCodebaseContextProvider() {
|
||||
return (this as any).hasCodebaseContextProvider();
|
||||
}
|
||||
|
||||
public async testHandleConfigUpdate(
|
||||
configResult: ConfigResult<ContinueConfig>,
|
||||
) {
|
||||
return (this as any).handleConfigUpdate({ config: configResult.config });
|
||||
}
|
||||
}
|
||||
|
||||
// Create a mock messenger type that doesn't require actual protocol imports
|
||||
|
|
@ -71,8 +87,6 @@ type MockMessengerType = {
|
|||
// These are more like integration tests, whereas we should separately test
|
||||
// the individual CodebaseIndex classes
|
||||
describe("CodebaseIndexer", () => {
|
||||
const pauseToken = new PauseToken(false);
|
||||
|
||||
// Replace mockProgressReporter with mockMessenger
|
||||
const mockMessenger: MockMessengerType = {
|
||||
send: jest.fn(),
|
||||
|
|
@ -82,13 +96,8 @@ describe("CodebaseIndexer", () => {
|
|||
onError: jest.fn(),
|
||||
};
|
||||
|
||||
const codebaseIndexer = new TestCodebaseIndexer(
|
||||
testConfigHandler,
|
||||
testIde,
|
||||
mockMessenger as any,
|
||||
false,
|
||||
);
|
||||
const testIndex = new TestCodebaseIndex();
|
||||
let codebaseIndexer: TestCodebaseIndexer;
|
||||
let testIndex: TestCodebaseIndex;
|
||||
|
||||
beforeAll(async () => {
|
||||
tearDownTestDir();
|
||||
|
|
@ -99,6 +108,15 @@ describe("CodebaseIndexer", () => {
|
|||
cwd: TEST_DIR_PATH,
|
||||
});
|
||||
execSync('git config user.name "Test"', { cwd: TEST_DIR_PATH });
|
||||
|
||||
codebaseIndexer = new TestCodebaseIndexer(
|
||||
testConfigHandler,
|
||||
testIde,
|
||||
mockMessenger as any,
|
||||
false,
|
||||
);
|
||||
await codebaseIndexer.initPromise;
|
||||
testIndex = new TestCodebaseIndex();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
|
|
@ -161,6 +179,7 @@ describe("CodebaseIndexer", () => {
|
|||
}
|
||||
|
||||
test("should index test folder without problem", async () => {
|
||||
walkDirCache.invalidate();
|
||||
addToTestDir([
|
||||
["test.ts", TEST_TS],
|
||||
["py/main.py", TEST_PY],
|
||||
|
|
@ -403,4 +422,270 @@ describe("CodebaseIndexer", () => {
|
|||
expect(codebaseIndexer.currentIndexingState).toEqual(testState);
|
||||
});
|
||||
});
|
||||
|
||||
// New describe block for testing handleConfigUpdate functionality
|
||||
describe("handleConfigUpdate functionality", () => {
|
||||
let testIndexer: TestCodebaseIndexer;
|
||||
let mockRefreshCodebaseIndex: jest.MockedFunction<any>;
|
||||
let mockGetWorkspaceDirs: jest.MockedFunction<any>;
|
||||
|
||||
beforeEach(() => {
|
||||
testIndexer = new TestCodebaseIndexer(
|
||||
testConfigHandler,
|
||||
testIde,
|
||||
mockMessenger as any,
|
||||
false,
|
||||
);
|
||||
|
||||
// Mock the refreshCodebaseIndex method to avoid actual indexing
|
||||
mockRefreshCodebaseIndex = jest
|
||||
.spyOn(testIndexer, "refreshCodebaseIndex")
|
||||
.mockImplementation(async () => {});
|
||||
|
||||
// Mock getWorkspaceDirs to return test directories
|
||||
mockGetWorkspaceDirs = jest
|
||||
.spyOn(testIde, "getWorkspaceDirs")
|
||||
.mockResolvedValue(["/test/workspace"]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("hasCodebaseContextProvider", () => {
|
||||
test("should return true when codebase context provider is present", () => {
|
||||
// Set up config with codebase context provider
|
||||
(testIndexer as any).config = {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: CodebaseContextProvider.description.title,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = testIndexer.testHasCodebaseContextProvider();
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
test("should return false when no context providers are configured", () => {
|
||||
(testIndexer as any).config = {
|
||||
contextProviders: undefined,
|
||||
};
|
||||
|
||||
const result = testIndexer.testHasCodebaseContextProvider();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("should return false when context providers exist but no codebase provider", () => {
|
||||
(testIndexer as any).config = {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: "SomeOtherProvider",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = testIndexer.testHasCodebaseContextProvider();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("should return false when context providers is empty array", () => {
|
||||
(testIndexer as any).config = {
|
||||
contextProviders: [],
|
||||
};
|
||||
|
||||
const result = testIndexer.testHasCodebaseContextProvider();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleConfigUpdate", () => {
|
||||
test("should return early when newConfig is null", async () => {
|
||||
const configResult: ConfigResult<ContinueConfig> = {
|
||||
config: null as any,
|
||||
errors: [],
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, so we want them to not get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("should return early when newConfig is undefined", async () => {
|
||||
const configResult: ConfigResult<ContinueConfig> = {
|
||||
config: undefined as any,
|
||||
errors: [],
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, so we want them to not get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("should return early when no codebase context provider is present", async () => {
|
||||
const configResult: ConfigResult<ContinueConfig> = {
|
||||
config: {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: "SomeOtherProvider",
|
||||
},
|
||||
},
|
||||
],
|
||||
selectedModelByRole: {
|
||||
embed: {
|
||||
model: "test-model",
|
||||
provider: "test-provider",
|
||||
},
|
||||
},
|
||||
} as unknown as ContinueConfig,
|
||||
errors: [],
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, so we want them to not get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("should return early when no embed model is configured", async () => {
|
||||
const configResult: ConfigResult<ContinueConfig> = {
|
||||
config: {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: CodebaseContextProvider.description.title,
|
||||
},
|
||||
},
|
||||
],
|
||||
selectedModelByRole: {
|
||||
embed: undefined,
|
||||
},
|
||||
} as unknown as ContinueConfig,
|
||||
errors: [],
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, so we want them to not get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("should call refreshCodebaseIndex when all conditions are met", async () => {
|
||||
const configResult: ConfigResult<ContinueConfig> = {
|
||||
config: {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: CodebaseContextProvider.description.title,
|
||||
},
|
||||
},
|
||||
],
|
||||
selectedModelByRole: {
|
||||
embed: {
|
||||
model: "test-model",
|
||||
provider: "test-provider",
|
||||
},
|
||||
},
|
||||
} as unknown as ContinueConfig,
|
||||
errors: [],
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, and we want them to get called again
|
||||
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(2);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
|
||||
"/test/workspace",
|
||||
]);
|
||||
});
|
||||
|
||||
test("should set config property before checking conditions", async () => {
|
||||
const testConfig = {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: CodebaseContextProvider.description.title,
|
||||
},
|
||||
},
|
||||
],
|
||||
selectedModelByRole: {
|
||||
embed: {
|
||||
model: "test-model",
|
||||
provider: "test-provider",
|
||||
},
|
||||
},
|
||||
} as unknown as ContinueConfig;
|
||||
|
||||
const configResult: ConfigResult<ContinueConfig> = {
|
||||
config: testConfig,
|
||||
errors: [],
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// Verify that the config was set
|
||||
expect((testIndexer as any).config).toBe(testConfig);
|
||||
// These get called once on init, and we want them to get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("should handle multiple context providers correctly", async () => {
|
||||
const configResult: ConfigResult<ContinueConfig> = {
|
||||
config: {
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
title: "SomeOtherProvider",
|
||||
},
|
||||
},
|
||||
{
|
||||
description: {
|
||||
title: CodebaseContextProvider.description.title,
|
||||
},
|
||||
},
|
||||
{
|
||||
description: {
|
||||
title: "AnotherProvider",
|
||||
},
|
||||
},
|
||||
],
|
||||
selectedModelByRole: {
|
||||
embed: {
|
||||
model: "test-model",
|
||||
provider: "test-provider",
|
||||
},
|
||||
},
|
||||
} as unknown as ContinueConfig,
|
||||
errors: [],
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
|
||||
await testIndexer.testHandleConfigUpdate(configResult);
|
||||
|
||||
// These get called once on init, and we want them to get called again
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
|
||||
expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
|
||||
"/test/workspace",
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,7 +1,12 @@
|
|||
import * as fs from "fs/promises";
|
||||
|
||||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
|
||||
import {
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
IndexingProgressUpdate,
|
||||
IndexTag,
|
||||
} from "../index.js";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
|
||||
import type { IMessenger } from "../protocol/messenger";
|
||||
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
|
||||
|
|
@ -9,11 +14,14 @@ import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
|
|||
import { Telemetry } from "../util/posthog.js";
|
||||
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
|
||||
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
|
||||
import { ContinueServerClient } from "../continueServer/stubs/client";
|
||||
import { LLMError } from "../llm/index.js";
|
||||
import { getRootCause } from "../util/errors.js";
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
|
||||
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
|
||||
import { embedModelsAreEqual } from "./docs/DocsService.js";
|
||||
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
|
||||
import { LanceDbIndex } from "./LanceDbIndex.js";
|
||||
import { getComputeDeleteAddRemove, IndexLock } from "./refreshIndex.js";
|
||||
|
|
@ -44,6 +52,10 @@ export class CodebaseIndexer {
|
|||
* - To make as few requests as possible to the embeddings providers
|
||||
*/
|
||||
filesPerBatch = 200;
|
||||
// We normally allow this to run in the background,
|
||||
// and only need to `await` it for tests.
|
||||
public initPromise: Promise<void>;
|
||||
private config!: ContinueConfig;
|
||||
private indexingCancellationController: AbortController | undefined;
|
||||
private codebaseIndexingState: IndexingProgressUpdate;
|
||||
private readonly pauseToken: PauseToken;
|
||||
|
|
@ -83,6 +95,17 @@ export class CodebaseIndexer {
|
|||
|
||||
// Initialize pause token
|
||||
this.pauseToken = new PauseToken(initialPaused);
|
||||
|
||||
this.initPromise = this.init(configHandler);
|
||||
}
|
||||
|
||||
// Initialization - load config and attach config listener
|
||||
private async init(configHandler: ConfigHandler) {
|
||||
const result = await configHandler.loadConfig();
|
||||
await this.handleConfigUpdate(result);
|
||||
configHandler.onConfigUpdate(
|
||||
this.handleConfigUpdate.bind(this) as (arg: any) => void,
|
||||
);
|
||||
}
|
||||
|
||||
set paused(value: boolean) {
|
||||
|
|
@ -192,7 +215,7 @@ export class CodebaseIndexer {
|
|||
workspaceDirs: string[],
|
||||
): Promise<void> {
|
||||
if (this.pauseToken.paused) {
|
||||
// NOTE: by returning here, there is a chance that while paused a file is modified and
|
||||
// FIXME: by returning here, there is a chance that while paused a file is modified and
|
||||
// then after unpausing the file is not reindexed
|
||||
return;
|
||||
}
|
||||
|
|
@ -763,4 +786,49 @@ export class CodebaseIndexer {
|
|||
public get currentIndexingState(): IndexingProgressUpdate {
|
||||
return this.codebaseIndexingState;
|
||||
}
|
||||
|
||||
private hasCodebaseContextProvider() {
|
||||
return !!this.config.contextProviders?.some(
|
||||
(provider) =>
|
||||
provider.description.title ===
|
||||
CodebaseContextProvider.description.title,
|
||||
);
|
||||
}
|
||||
|
||||
private isIndexingConfigSame(
|
||||
config1: ContinueConfig | undefined,
|
||||
config2: ContinueConfig,
|
||||
) {
|
||||
return embedModelsAreEqual(
|
||||
config1?.selectedModelByRole.embed,
|
||||
config2.selectedModelByRole.embed,
|
||||
);
|
||||
}
|
||||
|
||||
private async handleConfigUpdate({
|
||||
config: newConfig,
|
||||
}: ConfigResult<ContinueConfig>) {
|
||||
if (newConfig) {
|
||||
const needsReindex = !this.isIndexingConfigSame(this.config, newConfig);
|
||||
|
||||
this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
|
||||
|
||||
// No point in indexing if no codebase context provider
|
||||
const hasCodebaseContextProvider = this.hasCodebaseContextProvider();
|
||||
if (!hasCodebaseContextProvider) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip codebase indexing if not supported
|
||||
// No warning message here because would show on ANY config update
|
||||
if (!this.config.selectedModelByRole.embed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (needsReindex) {
|
||||
const dirs = await this.ide.getWorkspaceDirs();
|
||||
await this.refreshCodebaseIndex(dirs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,15 @@ export interface SiteIndexingResults {
|
|||
title: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip off the trailing forward slash from the given URL
|
||||
* @param url The URL of the document
|
||||
* @returns A sanitized URL without trailing forward slash
|
||||
*/
|
||||
const stripTrailingSlash = (url: string): string => {
|
||||
return url.replace(/\/+$/, "");
|
||||
};
|
||||
|
||||
export class DocsCache {
|
||||
static readonly AWS_REGION: string = "us-west-1";
|
||||
static readonly BUCKET_NAME: string = "continue-preindexed-docs";
|
||||
|
|
@ -33,7 +42,8 @@ export class DocsCache {
|
|||
url: string,
|
||||
): string {
|
||||
const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId);
|
||||
const normalizedUrl = encodeURIComponent(url.replace(/\//g, "_"));
|
||||
const sanitizedUrl = stripTrailingSlash(url);
|
||||
const normalizedUrl = encodeURIComponent(sanitizedUrl.replace(/\//g, "_"));
|
||||
return normalizedEmbeddingId + "/" + normalizedUrl;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => {
|
|||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const newFailedDocs = failedDocs.filter(
|
||||
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
(d) => !docConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
newFailedDocs.push(siteIndexingConfig);
|
||||
globalContext.update("failedDocs", newFailedDocs);
|
||||
|
|
@ -81,7 +81,7 @@ const removeFromFailedGlobalContext = (
|
|||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
const newFailedDocs = failedDocs.filter(
|
||||
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
(d) => !docConfigsAreEqual(siteIndexingConfig, d),
|
||||
);
|
||||
globalContext.update("failedDocs", newFailedDocs);
|
||||
};
|
||||
|
|
@ -89,32 +89,69 @@ const removeFromFailedGlobalContext = (
|
|||
const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => {
|
||||
const globalContext = new GlobalContext();
|
||||
const failedDocs = globalContext.get("failedDocs") ?? [];
|
||||
return failedDocs.find((d) =>
|
||||
siteIndexingConfigsAreEqual(siteIndexingConfig, d),
|
||||
return failedDocs.find((d) => docConfigsAreEqual(siteIndexingConfig, d));
|
||||
};
|
||||
|
||||
export function embedModelsAreEqual(
|
||||
llm1: ILLM | null | undefined,
|
||||
llm2: ILLM | null | undefined,
|
||||
): boolean {
|
||||
return (
|
||||
llm1?.underlyingProviderName === llm2?.underlyingProviderName &&
|
||||
llm1?.title === llm2?.title &&
|
||||
llm1?.maxEmbeddingChunkSize === llm2?.maxEmbeddingChunkSize
|
||||
);
|
||||
}
|
||||
|
||||
const docConfigsAreEqual = (
|
||||
siteConfig1: SiteIndexingConfig,
|
||||
siteConfig2: SiteIndexingConfig,
|
||||
) => {
|
||||
return (
|
||||
siteConfig1.faviconUrl === siteConfig2.faviconUrl &&
|
||||
siteConfig1.title === siteConfig2.title &&
|
||||
docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2)
|
||||
);
|
||||
};
|
||||
|
||||
const docConfigsAreEqualExceptTitleAndFavicon = (
|
||||
siteConfig1: SiteIndexingConfig,
|
||||
siteConfig2: SiteIndexingConfig,
|
||||
) => {
|
||||
return (
|
||||
siteConfig1.startUrl === siteConfig2.startUrl &&
|
||||
siteConfig1.maxDepth === siteConfig2.maxDepth &&
|
||||
siteConfig1.useLocalCrawling === siteConfig2.useLocalCrawling
|
||||
);
|
||||
};
|
||||
|
||||
const siteIndexingConfigsAreEqual = (
|
||||
config1: SiteIndexingConfig,
|
||||
config2: SiteIndexingConfig,
|
||||
siteConfig1: SiteIndexingConfig,
|
||||
siteConfig2: SiteIndexingConfig,
|
||||
contConfig1: ContinueConfig | undefined,
|
||||
contConfig2: ContinueConfig,
|
||||
) => {
|
||||
return (
|
||||
config1.startUrl === config2.startUrl &&
|
||||
config1.faviconUrl === config2.faviconUrl &&
|
||||
config1.title === config2.title &&
|
||||
config1.maxDepth === config2.maxDepth &&
|
||||
config1.useLocalCrawling === config2.useLocalCrawling
|
||||
docConfigsAreEqual(siteConfig1, siteConfig2) &&
|
||||
embedModelsAreEqual(
|
||||
contConfig1?.selectedModelByRole.embed,
|
||||
contConfig2.selectedModelByRole.embed,
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const siteIndexingConfigsAreEqualExceptTitleAndFavicon = (
|
||||
config1: SiteIndexingConfig,
|
||||
config2: SiteIndexingConfig,
|
||||
siteConfig1: SiteIndexingConfig,
|
||||
siteConfig2: SiteIndexingConfig,
|
||||
contConfig1: ContinueConfig | undefined,
|
||||
contConfig2: ContinueConfig,
|
||||
) => {
|
||||
return (
|
||||
config1.startUrl === config2.startUrl &&
|
||||
config1.maxDepth === config2.maxDepth &&
|
||||
config1.useLocalCrawling === config2.useLocalCrawling
|
||||
docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2) &&
|
||||
embedModelsAreEqual(
|
||||
contConfig1?.selectedModelByRole.embed,
|
||||
contConfig2.selectedModelByRole.embed,
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
|
|
@ -968,7 +1005,6 @@ export default class DocsService {
|
|||
|
||||
await db.exec("PRAGMA busy_timeout = 3000;");
|
||||
|
||||
await runSqliteMigrations(db);
|
||||
// First create the table if it doesn't exist
|
||||
await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
|
|
@ -978,6 +1014,8 @@ export default class DocsService {
|
|||
embeddingsProviderId STRING
|
||||
)`);
|
||||
|
||||
await runSqliteMigrations(db);
|
||||
|
||||
this.sqliteDb = db;
|
||||
}
|
||||
|
||||
|
|
@ -1036,12 +1074,22 @@ export default class DocsService {
|
|||
);
|
||||
|
||||
// TODO: Changes to the docs config made while Continue isn't running won't be caught
|
||||
if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
|
||||
if (
|
||||
oldConfigDoc &&
|
||||
!siteIndexingConfigsAreEqual(
|
||||
oldConfigDoc,
|
||||
doc,
|
||||
oldConfig,
|
||||
newConfig,
|
||||
)
|
||||
) {
|
||||
// When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing
|
||||
if (
|
||||
siteIndexingConfigsAreEqualExceptTitleAndFavicon(
|
||||
oldConfigDoc,
|
||||
doc,
|
||||
oldConfig,
|
||||
newConfig,
|
||||
)
|
||||
) {
|
||||
await this.updateMetadataInSqlite(doc);
|
||||
|
|
@ -1261,7 +1309,7 @@ export default class DocsService {
|
|||
// Handles the case where a user has manually added the doc to config.json
|
||||
// so it already exists in the file
|
||||
const doesEquivalentDocExist = this.config.docs?.some((doc) =>
|
||||
siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
|
||||
docConfigsAreEqual(doc, siteIndexingConfig),
|
||||
);
|
||||
|
||||
if (!doesEquivalentDocExist) {
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,17 @@ import { fileURLToPath } from "url";
|
|||
|
||||
export default {
|
||||
transform: {
|
||||
"^.+\\.(ts|js)$": ["ts-jest", { useESM: true, useIsolatedModules: true }],
|
||||
"^.+\\.(ts|js)$": [
|
||||
"ts-jest",
|
||||
{
|
||||
useESM: true,
|
||||
useIsolatedModules: true,
|
||||
tsconfig: {
|
||||
experimentalDecorators: true,
|
||||
emitDecoratorMetadata: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
moduleNameMapper: {
|
||||
"^(\\.{1,2}/.*)\\.js$": "$1",
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
// @ts-nocheck
|
||||
// Generated by continue
|
||||
import { ChatMessage, MessagePart } from "../index.js";
|
||||
import { ChatMessage, MessagePart, ToolCall } from "../index.js";
|
||||
import {
|
||||
compileChatMessages,
|
||||
countTokens,
|
||||
countTokensAsync,
|
||||
extractToolSequence,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
pruneRawPromptFromTop,
|
||||
|
|
@ -174,3 +175,188 @@ describe.skip("compileChatMessages", () => {
|
|||
expect(compiled.length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractToolSequence", () => {
|
||||
// Helper function to create mock messages
|
||||
const createUserMessage = (content: string): ChatMessage => ({
|
||||
role: "user",
|
||||
content,
|
||||
});
|
||||
|
||||
const createAssistantMessage = (
|
||||
content: string,
|
||||
toolCalls?: ToolCall[],
|
||||
): ChatMessage => ({
|
||||
role: "assistant",
|
||||
content,
|
||||
toolCalls,
|
||||
});
|
||||
|
||||
const createToolMessage = (
|
||||
content: string,
|
||||
toolCallId: string,
|
||||
): ChatMessage => ({
|
||||
role: "tool",
|
||||
content,
|
||||
toolCallId,
|
||||
});
|
||||
|
||||
const createToolCall = (
|
||||
id: string,
|
||||
name: string,
|
||||
args: object,
|
||||
): ToolCall => ({
|
||||
id,
|
||||
type: "function",
|
||||
function: {
|
||||
name,
|
||||
arguments: JSON.stringify(args),
|
||||
},
|
||||
});
|
||||
|
||||
test("extractToolSequence should handle a single user message", () => {
|
||||
const messages: ChatMessage[] = [createUserMessage("Hello world!")];
|
||||
const sequence = extractToolSequence(messages);
|
||||
|
||||
expect(sequence).toHaveLength(1);
|
||||
expect(sequence[0].role).toBe("user");
|
||||
expect(sequence[0].content).toBe("Hello world!");
|
||||
expect(messages).toHaveLength(0); // Original array should be modified
|
||||
});
|
||||
|
||||
test("extractToolSequence should handle a single tool message with assistant", () => {
|
||||
const toolCall = createToolCall("tc_1", "read_file", { path: "test.txt" });
|
||||
const messages: ChatMessage[] = [
|
||||
createAssistantMessage("I'll read the file for you.", [toolCall]),
|
||||
createToolMessage("File contents here", "tc_1"),
|
||||
];
|
||||
const sequence = extractToolSequence(messages);
|
||||
|
||||
expect(sequence).toHaveLength(2);
|
||||
expect(sequence[0].role).toBe("assistant");
|
||||
expect(sequence[1].role).toBe("tool");
|
||||
expect(sequence[1].toolCallId).toBe("tc_1");
|
||||
expect(messages).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("extractToolSequence should handle multiple consecutive tool messages", () => {
|
||||
const toolCall1 = createToolCall("tc_1", "read_file", { path: "test.txt" });
|
||||
const toolCall2 = createToolCall("tc_2", "write_file", {
|
||||
path: "output.txt",
|
||||
content: "data",
|
||||
});
|
||||
const messages: ChatMessage[] = [
|
||||
createAssistantMessage("I'll read and write files.", [
|
||||
toolCall1,
|
||||
toolCall2,
|
||||
]),
|
||||
createToolMessage("File contents 1", "tc_1"),
|
||||
createToolMessage("File written successfully", "tc_2"),
|
||||
];
|
||||
const sequence = extractToolSequence(messages);
|
||||
|
||||
expect(sequence).toHaveLength(3);
|
||||
expect(sequence[0].role).toBe("assistant");
|
||||
expect(sequence[1].role).toBe("tool");
|
||||
expect(sequence[1].toolCallId).toBe("tc_1");
|
||||
expect(sequence[2].role).toBe("tool");
|
||||
expect(sequence[2].toolCallId).toBe("tc_2");
|
||||
expect(messages).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("extractToolSequence should handle tool sequence with previous context", () => {
|
||||
const toolCall = createToolCall("tc_1", "search", { query: "test" });
|
||||
const messages: ChatMessage[] = [
|
||||
createUserMessage("What's in the codebase?"),
|
||||
createAssistantMessage("Let me search for you.", [toolCall]),
|
||||
createToolMessage("Search results here", "tc_1"),
|
||||
];
|
||||
const sequence = extractToolSequence(messages);
|
||||
|
||||
expect(sequence).toHaveLength(2);
|
||||
expect(sequence[0].role).toBe("assistant");
|
||||
expect(sequence[1].role).toBe("tool");
|
||||
expect(messages).toHaveLength(1); // User message should remain
|
||||
expect(messages[0].role).toBe("user");
|
||||
});
|
||||
|
||||
test("extractToolSequence should throw error when tool message has no matching tool call", () => {
|
||||
const toolCall = createToolCall("tc_1", "read_file", { path: "test.txt" });
|
||||
const messages: ChatMessage[] = [
|
||||
createAssistantMessage("I'll read the file for you.", [toolCall]),
|
||||
createToolMessage("File contents here", "tc_2"), // Wrong tool call ID
|
||||
];
|
||||
|
||||
expect(() => extractToolSequence(messages)).toThrow(
|
||||
'Error parsing chat history: no tool call found to match tool output for id "tc_2"',
|
||||
);
|
||||
});
|
||||
|
||||
test("extractToolSequence should throw error when last message is not user or tool", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
createUserMessage("Hello"),
|
||||
createAssistantMessage("Hi there!"),
|
||||
];
|
||||
|
||||
expect(() => extractToolSequence(messages)).toThrow(
|
||||
"Error parsing chat history: no user/tool message found",
|
||||
);
|
||||
});
|
||||
|
||||
test("extractToolSequence should throw error when messages array is empty", () => {
|
||||
const messages: ChatMessage[] = [];
|
||||
|
||||
expect(() => extractToolSequence(messages)).toThrow(
|
||||
"Error parsing chat history: no user/tool message found",
|
||||
);
|
||||
});
|
||||
|
||||
test("extractToolSequence should handle tool sequence without assistant message", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
createToolMessage("Orphaned tool message", "tc_1"),
|
||||
];
|
||||
const sequence = extractToolSequence(messages);
|
||||
|
||||
expect(sequence).toHaveLength(1);
|
||||
expect(sequence[0].role).toBe("tool");
|
||||
expect(sequence[0].toolCallId).toBe("tc_1");
|
||||
expect(messages).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("extractToolSequence should handle complex tool sequence with multiple tool calls", () => {
|
||||
const toolCall1 = createToolCall("tc_1", "read_file", {
|
||||
path: "file1.txt",
|
||||
});
|
||||
const toolCall2 = createToolCall("tc_2", "read_file", {
|
||||
path: "file2.txt",
|
||||
});
|
||||
const toolCall3 = createToolCall("tc_3", "write_file", {
|
||||
path: "output.txt",
|
||||
content: "merged",
|
||||
});
|
||||
|
||||
const messages: ChatMessage[] = [
|
||||
createUserMessage("Merge these files"),
|
||||
createAssistantMessage("I'll read both files and merge them.", [
|
||||
toolCall1,
|
||||
toolCall2,
|
||||
toolCall3,
|
||||
]),
|
||||
createToolMessage("Contents of file1", "tc_1"),
|
||||
createToolMessage("Contents of file2", "tc_2"),
|
||||
createToolMessage("Files merged successfully", "tc_3"),
|
||||
];
|
||||
|
||||
const sequence = extractToolSequence(messages);
|
||||
|
||||
expect(sequence).toHaveLength(4);
|
||||
expect(sequence[0].role).toBe("assistant");
|
||||
expect(sequence[1].role).toBe("tool");
|
||||
expect(sequence[1].toolCallId).toBe("tc_1");
|
||||
expect(sequence[2].role).toBe("tool");
|
||||
expect(sequence[2].toolCallId).toBe("tc_2");
|
||||
expect(sequence[3].role).toBe("tool");
|
||||
expect(sequence[3].toolCallId).toBe("tc_3");
|
||||
expect(messages).toHaveLength(1); // User message should remain
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,22 +1,23 @@
|
|||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
|
||||
import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js";
|
||||
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import {
|
||||
AsyncEncoder,
|
||||
GPTAsyncEncoder,
|
||||
LlamaAsyncEncoder,
|
||||
} from "./asyncEncoder.js";
|
||||
ChatMessage,
|
||||
CompiledMessagesResult,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
Tool,
|
||||
} from "../index.js";
|
||||
import { autodetectTemplateType } from "./autodetect.js";
|
||||
import llamaTokenizer from "./llamaTokenizer.js";
|
||||
import {
|
||||
addSpaceToAnyEmptyMessages,
|
||||
chatMessageIsEmpty,
|
||||
flattenMessages,
|
||||
isUserOrToolMsg,
|
||||
messageHasToolCallId,
|
||||
} from "./messages.js";
|
||||
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js";
|
||||
import llamaTokenizer from "./llamaTokenizer.js";
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
decode: Tiktoken["decode"];
|
||||
|
|
@ -47,7 +48,6 @@ class NonWorkerAsyncEncoder implements AsyncEncoder {
|
|||
}
|
||||
|
||||
let gptEncoding: Encoding | null = null;
|
||||
const gptAsyncEncoder = new GPTAsyncEncoder();
|
||||
const llamaEncoding = new LlamaEncoding();
|
||||
const llamaAsyncEncoder = new LlamaAsyncEncoder();
|
||||
|
||||
|
|
@ -213,6 +213,59 @@ function countChatMessageTokens(
|
|||
return tokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts and validates the tool call sequence from the end of a message array.
|
||||
* Tool sequences consist of: [assistant_with_tool_calls, tool_response_1, tool_response_2, ...]
|
||||
* or just a single user message.
|
||||
*
|
||||
* @param messages - Array of chat messages (will be modified by popping messages)
|
||||
* @returns Array of messages that form the tool sequence
|
||||
*/
|
||||
function extractToolSequence(messages: ChatMessage[]): ChatMessage[] {
|
||||
const lastMsg = messages.pop();
|
||||
if (!lastMsg || !isUserOrToolMsg(lastMsg)) {
|
||||
throw new Error("Error parsing chat history: no user/tool message found");
|
||||
}
|
||||
|
||||
const toolSequence: ChatMessage[] = [];
|
||||
|
||||
if (lastMsg.role === "tool") {
|
||||
toolSequence.push(lastMsg);
|
||||
|
||||
// Collect all consecutive tool messages from the end
|
||||
while (
|
||||
messages.length > 0 &&
|
||||
messages[messages.length - 1].role === "tool"
|
||||
) {
|
||||
toolSequence.unshift(messages.pop()!);
|
||||
}
|
||||
|
||||
// Get the assistant message with tool calls
|
||||
const assistantMsg = messages.pop();
|
||||
if (assistantMsg) {
|
||||
toolSequence.unshift(assistantMsg);
|
||||
|
||||
// Validate that all tool messages have matching tool call IDs
|
||||
for (const toolMsg of toolSequence.slice(1)) {
|
||||
// Skip assistant message
|
||||
if (
|
||||
toolMsg.role === "tool" &&
|
||||
!messageHasToolCallId(assistantMsg, toolMsg.toolCallId)
|
||||
) {
|
||||
throw new Error(
|
||||
`Error parsing chat history: no tool call found to match tool output for id "${toolMsg.toolCallId}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single user message
|
||||
toolSequence.push(lastMsg);
|
||||
}
|
||||
|
||||
return toolSequence;
|
||||
}
|
||||
|
||||
function pruneLinesFromTop(
|
||||
prompt: string,
|
||||
maxTokens: number,
|
||||
|
|
@ -309,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,
|
||||
|
|
@ -326,13 +376,36 @@ function pruneRawPromptFromTop(
|
|||
return pruneStringFromTop(modelName, maxTokens, prompt);
|
||||
}
|
||||
|
||||
/*
|
||||
Goal: reconcile chat messages with available context length
|
||||
Guidelines:
|
||||
- Always keep last user message, system message, and tools
|
||||
- Never allow tool output without the corresponding tool call
|
||||
- Remove older messages first
|
||||
*/
|
||||
/**
|
||||
* Reconciles chat messages with available context length by intelligently pruning older messages
|
||||
* while preserving critical conversation elements.
|
||||
*
|
||||
* Core Guidelines:
|
||||
* - Always preserve the last user/tool message sequence (including any associated assistant message with tool calls)
|
||||
* - Always preserve the system message and tools
|
||||
* - Never allow orphaned tool responses without their corresponding tool calls
|
||||
* - Remove older messages first when pruning is necessary
|
||||
* - Maintain conversation coherence by flattening adjacent similar messages
|
||||
*
|
||||
* Process:
|
||||
* 1. Handle image content conversion for models that don't support images
|
||||
* 2. Extract and preserve system message
|
||||
* 3. Filter out empty messages and trailing non-user/tool messages
|
||||
* 4. Extract the complete tool sequence from the end (user message or assistant + tool responses)
|
||||
* 5. Calculate token requirements for non-negotiable elements (system, tools, last sequence)
|
||||
* 6. Prune older messages until within available token budget
|
||||
* 7. Reassemble with proper ordering and flatten adjacent similar messages
|
||||
*
|
||||
* @param params - Configuration object containing:
|
||||
* - modelName: LLM model name for token counting
|
||||
* - msgs: Array of chat messages to process
|
||||
* - contextLength: Maximum context length supported by the model
|
||||
* - maxTokens: Maximum tokens to reserve for the response
|
||||
* - supportsImages: Whether the model supports image content
|
||||
* - tools: Optional array of available tools
|
||||
* @returns Processed array of chat messages that fit within context constraints
|
||||
* @throws Error if non-negotiable elements exceed available context
|
||||
*/
|
||||
function compileChatMessages({
|
||||
modelName,
|
||||
msgs,
|
||||
|
|
@ -347,7 +420,9 @@ function compileChatMessages({
|
|||
maxTokens: number;
|
||||
supportsImages: boolean;
|
||||
tools?: Tool[];
|
||||
}): ChatMessage[] {
|
||||
}): CompiledMessagesResult {
|
||||
let didPrune = false;
|
||||
|
||||
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
|
||||
|
||||
// If images not supported, convert MessagePart[] to string
|
||||
|
|
@ -369,31 +444,13 @@ 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);
|
||||
|
||||
const lastUserOrToolMsg = msgsCopy.pop();
|
||||
if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) {
|
||||
throw new Error("Error parsing chat history: no user/tool message found"); // should never happen
|
||||
}
|
||||
|
||||
let lastToolCallsMsg: ChatMessage | undefined = undefined;
|
||||
if (lastUserOrToolMsg.role === "tool") {
|
||||
lastToolCallsMsg = msgsCopy.pop();
|
||||
if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) {
|
||||
throw new Error(
|
||||
`Error parsing chat history: no tool call found to match tool output for id "${lastUserOrToolMsg.toolCallId}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg);
|
||||
if (lastToolCallsMsg) {
|
||||
lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg);
|
||||
// Count tokens for all messages in the tool sequence
|
||||
let lastMessagesTokens = 0;
|
||||
for (const msg of toolSequence) {
|
||||
lastMessagesTokens += countChatMessageTokens(modelName, msg);
|
||||
}
|
||||
|
||||
// System message
|
||||
|
|
@ -409,7 +466,7 @@ function compileChatMessages({
|
|||
}
|
||||
|
||||
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
|
||||
const minOutputTokens = getMinResponseTokens(maxTokens);
|
||||
const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens);
|
||||
|
||||
let inputTokensAvailable = contextLength;
|
||||
|
||||
|
|
@ -426,14 +483,13 @@ function compileChatMessages({
|
|||
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}
|
||||
- last user or tool + tool call message tokens: ~${lastMessagesTokens}
|
||||
- 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}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -451,6 +507,7 @@ function compileChatMessages({
|
|||
while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
|
||||
const message = historyWithTokens.shift()!;
|
||||
currentTotal -= message.tokens;
|
||||
didPrune = true;
|
||||
|
||||
// At this point make sure no latent tool response without corresponding call
|
||||
while (historyWithTokens[0]?.role === "tool") {
|
||||
|
|
@ -465,20 +522,25 @@ function compileChatMessages({
|
|||
reassembled.push(systemMsg);
|
||||
}
|
||||
reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
|
||||
if (lastToolCallsMsg) {
|
||||
reassembled.push(lastToolCallsMsg);
|
||||
}
|
||||
reassembled.push(lastUserOrToolMsg);
|
||||
reassembled.push(...toolSequence);
|
||||
|
||||
// Flatten the messages (combines adjacent similar messages)
|
||||
const flattenedHistory = flattenMessages(reassembled);
|
||||
return flattenedHistory;
|
||||
const inputTokens =
|
||||
currentTotal + systemMsgTokens + toolTokens + lastMessagesTokens;
|
||||
const availableTokens =
|
||||
contextLength - countingSafetyBuffer - minOutputTokens;
|
||||
const contextPercentage = inputTokens / availableTokens;
|
||||
return {
|
||||
compiledChatMessages: reassembled,
|
||||
didPrune,
|
||||
contextPercentage,
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
compileChatMessages,
|
||||
countTokens,
|
||||
countTokensAsync,
|
||||
extractToolSequence,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
pruneRawPromptFromTop,
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ import {
|
|||
ILLMLogger,
|
||||
LLMFullCompletionOptions,
|
||||
LLMOptions,
|
||||
MessageOption,
|
||||
ModelCapability,
|
||||
ModelInstaller,
|
||||
PromptLog,
|
||||
|
|
@ -27,6 +28,7 @@ import {
|
|||
RequestOptions,
|
||||
TabAutocompleteOptions,
|
||||
TemplateType,
|
||||
Usage,
|
||||
} from "../index.js";
|
||||
import mergeJson from "../util/merge.js";
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
|
|
@ -326,6 +328,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);
|
||||
|
|
@ -367,6 +370,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "cancelled";
|
||||
} else {
|
||||
|
|
@ -378,6 +382,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "error";
|
||||
}
|
||||
|
|
@ -387,6 +392,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "success";
|
||||
}
|
||||
|
|
@ -573,6 +579,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
prefix,
|
||||
suffix,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, fimLog);
|
||||
|
|
@ -621,6 +628,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -629,6 +637,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -640,6 +649,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -680,6 +690,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "startComplete",
|
||||
prompt,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
|
|
@ -735,6 +746,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -743,6 +755,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -754,6 +767,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -795,6 +809,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "startComplete",
|
||||
prompt: prompt,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
|
|
@ -828,6 +843,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -836,6 +852,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -847,6 +864,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -867,6 +885,23 @@ export abstract class BaseLLM implements ILLM {
|
|||
return { role: "assistant" as const, content: completion };
|
||||
}
|
||||
|
||||
compileChatMessages(
|
||||
message: ChatMessage[],
|
||||
options: LLMFullCompletionOptions,
|
||||
) {
|
||||
let { completionOptions } = this._parseCompletionOptions(options);
|
||||
completionOptions = this._modifyCompletionOptions(completionOptions);
|
||||
|
||||
return compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: message,
|
||||
contextLength: this.contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
});
|
||||
}
|
||||
|
||||
protected modifyChatBody(
|
||||
body: ChatCompletionCreateParams,
|
||||
): ChatCompletionCreateParams {
|
||||
|
|
@ -891,6 +926,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
_messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: LLMFullCompletionOptions = {},
|
||||
messageOptions?: MessageOption,
|
||||
): AsyncGenerator<ChatMessage, PromptLog> {
|
||||
let { completionOptions, logEnabled } =
|
||||
this._parseCompletionOptions(options);
|
||||
|
|
@ -901,14 +937,21 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
completionOptions = this._modifyCompletionOptions(completionOptions);
|
||||
|
||||
const messages = compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: _messages,
|
||||
contextLength: this.contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
});
|
||||
let messages = _messages;
|
||||
|
||||
// If not precompiled, compile the chat messages
|
||||
if (!messageOptions?.precompiled) {
|
||||
const { compiledChatMessages } = compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: _messages,
|
||||
contextLength: this.contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
});
|
||||
|
||||
messages = compiledChatMessages;
|
||||
}
|
||||
|
||||
const prompt = this.templateMessages
|
||||
? this.templateMessages(messages)
|
||||
|
|
@ -918,6 +961,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "startChat",
|
||||
messages,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
|
|
@ -926,6 +970,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
let thinking = "";
|
||||
let completion = "";
|
||||
let usage: Usage | undefined = undefined;
|
||||
|
||||
try {
|
||||
if (this.templateMessages) {
|
||||
|
|
@ -992,6 +1037,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "message",
|
||||
message: chunk,
|
||||
});
|
||||
|
||||
if (chunk.role === "assistant" && chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
|
|
@ -1002,6 +1052,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
usage,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -1010,6 +1061,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
usage,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -1021,6 +1073,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.",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -11,18 +11,14 @@ import {
|
|||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
|
||||
import {
|
||||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessageContent,
|
||||
} from "../../index.js";
|
||||
import type { CompletionOptions } from "../../index.js";
|
||||
import { ChatMessage, Chunk, LLMOptions, MessageContent } from "../../index.js";
|
||||
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
|
||||
import { getSecureID } from "../utils/getSecureID.js";
|
||||
import { withLLMRetry } from "../utils/retry.js";
|
||||
|
||||
interface ModelConfig {
|
||||
formatPayload: (text: string) => any;
|
||||
|
|
@ -89,6 +85,7 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
@withLLMRetry()
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
|
|
@ -132,16 +129,9 @@ class Bedrock extends BaseLLM {
|
|||
});
|
||||
const command = new ConverseStreamCommand(input);
|
||||
|
||||
let response: ConverseStreamCommandOutput;
|
||||
try {
|
||||
response = (await client.send(command, {
|
||||
abortSignal: signal,
|
||||
})) as ConverseStreamCommandOutput;
|
||||
} catch (error: unknown) {
|
||||
console.error(error);
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
throw new Error(`Failed to communicate with Bedrock API: ${message}`);
|
||||
}
|
||||
const response = (await client.send(command, {
|
||||
abortSignal: signal,
|
||||
})) as ConverseStreamCommandOutput;
|
||||
|
||||
if (!response?.stream) {
|
||||
throw new Error("No stream received from Bedrock API");
|
||||
|
|
@ -259,19 +249,9 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
// Clean up state and let the original error bubble up to the retry decorator
|
||||
this._currentToolResponse = null;
|
||||
if (error instanceof Error) {
|
||||
if ("code" in error) {
|
||||
// AWS SDK specific errors
|
||||
throw new Error(
|
||||
`AWS Bedrock stream error (${(error as any).code}): ${error.message}`,
|
||||
);
|
||||
}
|
||||
throw new Error(`Error processing Bedrock stream: ${error.message}`);
|
||||
}
|
||||
throw new Error(
|
||||
"Error processing Bedrock stream: Unknown error occurred",
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@ import OpenAI from "../OpenAI.js";
|
|||
|
||||
import type { Chunk, LLMOptions } from "../../../index.js";
|
||||
import { LLMConfigurationStatuses } from "../../constants.js";
|
||||
import { LlmApiRequestType } from "../../openaiTypeConverters.js";
|
||||
|
||||
class ContinueProxy extends OpenAI {
|
||||
set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
|
||||
|
|
@ -23,6 +24,8 @@ class ContinueProxy extends OpenAI {
|
|||
}
|
||||
}
|
||||
|
||||
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
|
||||
|
||||
// The apiKey and apiBase are set to the values for the proxy,
|
||||
// but we need to keep track of the actual values that the proxy will use
|
||||
// to call whatever LLM API is chosen
|
||||
|
|
|
|||
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",
|
||||
|
|
|
|||
|
|
@ -1,104 +0,0 @@
|
|||
import { ChatMessage } from "..";
|
||||
import { flattenMessages } from "./messages";
|
||||
|
||||
describe("flattenMessages", () => {
|
||||
it("should return an empty array when given an empty array", () => {
|
||||
expect(flattenMessages([])).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return the same array when there is only one message", () => {
|
||||
const messages: ChatMessage[] = [{ role: "user", content: "Hello" }];
|
||||
expect(flattenMessages(messages)).toEqual(messages);
|
||||
});
|
||||
|
||||
it("should return the same array when messages have different roles", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there!" },
|
||||
{ role: "user", content: "How are you?" },
|
||||
];
|
||||
expect(flattenMessages(messages)).toEqual(messages);
|
||||
});
|
||||
|
||||
it("should combine consecutive messages with the same role", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "user", content: "How are you?" },
|
||||
{ role: "assistant", content: "I am an AI assistant." },
|
||||
{ role: "assistant", content: "How can I help you?" },
|
||||
];
|
||||
const expected: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello\n\nHow are you?" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "I am an AI assistant.\n\nHow can I help you?",
|
||||
},
|
||||
];
|
||||
expect(flattenMessages(messages)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should handle messages with undefined or empty content", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "user", content: "" },
|
||||
{ role: "assistant", content: "" },
|
||||
{ role: "assistant", content: "Sure, I can help with that." },
|
||||
];
|
||||
const expected: ChatMessage[] = [
|
||||
{ role: "user", content: "Hello\n\n" },
|
||||
{ role: "assistant", content: "\n\nSure, I can help with that." },
|
||||
];
|
||||
expect(flattenMessages(messages)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should not combine non-consecutive messages with the same role", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "First message" },
|
||||
{ role: "assistant", content: "Reply to first message" },
|
||||
{ role: "user", content: "Second message" },
|
||||
];
|
||||
expect(flattenMessages(messages)).toEqual(messages);
|
||||
});
|
||||
|
||||
it("should handle a mix of message roles and contents correctly", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "Message one" },
|
||||
{ role: "user", content: "Message two" },
|
||||
{ role: "assistant", content: "Reply one" },
|
||||
{ role: "user", content: "Message three" },
|
||||
{ role: "user", content: "Message four" },
|
||||
{ role: "assistant", content: "Reply two" },
|
||||
];
|
||||
const expected: ChatMessage[] = [
|
||||
{ role: "user", content: "Message one\n\nMessage two" },
|
||||
{ role: "assistant", content: "Reply one" },
|
||||
{ role: "user", content: "Message three\n\nMessage four" },
|
||||
{ role: "assistant", content: "Reply two" },
|
||||
];
|
||||
expect(flattenMessages(messages)).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should not combine adjacent assistant messages when one of them is a tool call", () => {
|
||||
const messages: ChatMessage[] = [
|
||||
{ role: "user", content: "What's the capital of France?" },
|
||||
{ role: "assistant", content: "Paris" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: " ",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "test",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "getCapital",
|
||||
arguments: JSON.stringify({
|
||||
country: "France",
|
||||
}),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
expect(flattenMessages(messages).length).toBe(3);
|
||||
});
|
||||
});
|
||||
|
|
@ -4,27 +4,6 @@ export function messageHasToolCalls(msg: ChatMessage): boolean {
|
|||
return msg.role === "assistant" && !!msg.toolCalls;
|
||||
}
|
||||
|
||||
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
|
||||
const flattened: ChatMessage[] = [];
|
||||
|
||||
for (let i = 0; i < msgs.length; i++) {
|
||||
const msg = msgs[i];
|
||||
|
||||
if (
|
||||
flattened.length > 0 &&
|
||||
flattened[flattened.length - 1].role === msg.role &&
|
||||
!messageHasToolCalls(msg) &&
|
||||
!messageHasToolCalls(flattened[flattened.length - 1])
|
||||
) {
|
||||
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
|
||||
} else {
|
||||
flattened.push(msg);
|
||||
}
|
||||
}
|
||||
|
||||
return flattened;
|
||||
}
|
||||
|
||||
export function messageIsEmpty(message: ChatMessage): boolean {
|
||||
if (typeof message.content === "string") {
|
||||
return message.content.trim() === "";
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
generalRule: {
|
||||
name: "General Rule",
|
||||
rule: "Follow coding standards",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/rules.md",
|
||||
},
|
||||
|
||||
|
|
@ -18,7 +18,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
name: "Redux Rule",
|
||||
rule: "Use Redux Toolkit",
|
||||
globs: "src/redux/**/*.{ts,tsx}",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/redux/rules.md",
|
||||
},
|
||||
|
||||
|
|
@ -27,7 +27,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
name: "Component Rule",
|
||||
rule: "Use functional components",
|
||||
globs: ["src/components/**/*.tsx", "src/components/**/*.jsx"],
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/components/rules.md",
|
||||
},
|
||||
|
||||
|
|
@ -37,7 +37,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
rule: "Follow these guidelines always",
|
||||
alwaysApply: true,
|
||||
globs: "src/specific/**/*.ts", // Should be ignored since alwaysApply is true
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: ".continue/rules.md",
|
||||
},
|
||||
|
||||
|
|
@ -47,7 +47,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
rule: "This rule should only apply to matching files",
|
||||
alwaysApply: false,
|
||||
// No globs, so should never apply
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: ".continue/rules.md",
|
||||
},
|
||||
|
||||
|
|
@ -57,7 +57,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
rule: "Apply only to matching files",
|
||||
alwaysApply: false,
|
||||
globs: "src/utils/**/*.ts",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
},
|
||||
};
|
||||
|
|
@ -127,7 +127,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
rule: "Follow nested module standards",
|
||||
// Fix: Specify the exact path prefix to restrict to this directory structure
|
||||
globs: "src/features/auth/utils/**/*.ts",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/features/auth/utils/rules.md",
|
||||
};
|
||||
|
||||
|
|
@ -157,7 +157,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
// Note: Negative globs may not be supported by the current implementation
|
||||
// Testing with standard pattern instead
|
||||
globs: "src/**/[!.]*.ts",
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/rules.md",
|
||||
};
|
||||
|
||||
|
|
@ -174,7 +174,7 @@ describe("Rule colocation - glob pattern matching", () => {
|
|||
// Use a pattern that doesn't match test files
|
||||
globs: ["src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"],
|
||||
alwaysApply: false,
|
||||
source: "rules-block",
|
||||
source: "colocated-markdown",
|
||||
ruleFile: "src/rules.md",
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -24,7 +24,12 @@ export async function* llmStreamChat(
|
|||
void TTS.kill();
|
||||
}
|
||||
|
||||
const { legacySlashCommandData, completionOptions, messages } = msg.data;
|
||||
const {
|
||||
legacySlashCommandData,
|
||||
completionOptions,
|
||||
messages,
|
||||
messageOptions,
|
||||
} = msg.data;
|
||||
|
||||
const model = config.selectedModelByRole.chat;
|
||||
|
||||
|
|
@ -117,6 +122,7 @@ export async function* llmStreamChat(
|
|||
messages,
|
||||
abortController.signal,
|
||||
completionOptions,
|
||||
messageOptions,
|
||||
);
|
||||
let next = await gen.next();
|
||||
while (!next.done) {
|
||||
|
|
|
|||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { getSecureID } from "../getSecureID";
|
||||
import { getSecureID } from "./getSecureID";
|
||||
|
||||
// Mock the crypto.randomUUID function
|
||||
const mockRandomUUID = jest.fn();
|
||||
481
core/llm/utils/retry.test.ts
Normal file
481
core/llm/utils/retry.test.ts
Normal file
|
|
@ -0,0 +1,481 @@
|
|||
import { retryAsync, withLLMRetry, withRetry } from "./retry";
|
||||
|
||||
// Mock console.warn to avoid noise in tests
|
||||
const consoleSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
|
||||
|
||||
describe("Retry Functionality", () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("retryAsync", () => {
|
||||
it("should succeed on first attempt", async () => {
|
||||
const mockFn = jest.fn().mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn);
|
||||
|
||||
expect(result).toBe("success");
|
||||
expect(mockFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should retry on retryable errors", async () => {
|
||||
const error = new Error("ECONNRESET");
|
||||
(error as any).code = "ECONNRESET";
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 10, // Very short delay for testing
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
expect(mockFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should not retry on non-retryable errors", async () => {
|
||||
const error = new Error("Bad Request");
|
||||
(error as any).status = 400;
|
||||
const mockFn = jest.fn().mockRejectedValue(error);
|
||||
|
||||
await expect(retryAsync(mockFn)).rejects.toThrow("Bad Request");
|
||||
expect(mockFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should respect max attempts", async () => {
|
||||
const error = new Error("ECONNRESET");
|
||||
(error as any).code = "ECONNRESET";
|
||||
const mockFn = jest.fn().mockRejectedValue(error);
|
||||
|
||||
await expect(
|
||||
retryAsync(mockFn, {
|
||||
maxAttempts: 3,
|
||||
baseDelay: 10,
|
||||
}),
|
||||
).rejects.toThrow("ECONNRESET");
|
||||
expect(mockFn).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("should throw the last error when all retries are exhausted", async () => {
|
||||
const firstError = new Error("First error");
|
||||
(firstError as any).code = "ECONNRESET";
|
||||
const secondError = new Error("Second error");
|
||||
(secondError as any).code = "ECONNRESET";
|
||||
const lastError = new Error("Last error");
|
||||
(lastError as any).code = "ECONNRESET";
|
||||
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(firstError)
|
||||
.mockRejectedValueOnce(secondError)
|
||||
.mockRejectedValueOnce(lastError);
|
||||
|
||||
await expect(
|
||||
retryAsync(mockFn, {
|
||||
maxAttempts: 3,
|
||||
baseDelay: 10,
|
||||
}),
|
||||
).rejects.toThrow("Last error");
|
||||
expect(mockFn).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("should handle HTTP 429 errors", async () => {
|
||||
const error = new Error("Too Many Requests");
|
||||
(error as any).status = 429;
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 10,
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
expect(mockFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should handle HTTP 5xx errors", async () => {
|
||||
const error = new Error("Internal Server Error");
|
||||
(error as any).status = 500;
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 10,
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
expect(mockFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should handle AWS SDK errors", async () => {
|
||||
const error = new Error("Throttling");
|
||||
error.name = "ThrottlingException";
|
||||
(error as any).$fault = "client";
|
||||
(error as any).$metadata = {
|
||||
httpStatusCode: 429,
|
||||
requestId: "test-request-id",
|
||||
};
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 10,
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
expect(mockFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("should not retry AbortError", async () => {
|
||||
const error = new Error("Aborted");
|
||||
error.name = "AbortError";
|
||||
const mockFn = jest.fn().mockRejectedValue(error);
|
||||
|
||||
await expect(retryAsync(mockFn)).rejects.toThrow("Aborted");
|
||||
expect(mockFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should use custom shouldRetry function", async () => {
|
||||
const mockFn = jest.fn().mockRejectedValue(new Error("Custom Error"));
|
||||
const customShouldRetry = jest.fn().mockReturnValue(true);
|
||||
|
||||
await expect(
|
||||
retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
shouldRetry: customShouldRetry,
|
||||
baseDelay: 10,
|
||||
}),
|
||||
).rejects.toThrow("Custom Error");
|
||||
|
||||
expect(customShouldRetry).toHaveBeenCalledWith(expect.any(Error), 1);
|
||||
expect(mockFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("withRetry decorator functional usage", () => {
|
||||
it("should work when applied manually to methods", async () => {
|
||||
const testClass = {
|
||||
attempts: 0,
|
||||
|
||||
async testMethod(): Promise<string> {
|
||||
this.attempts++;
|
||||
if (this.attempts < 3) {
|
||||
const error = new Error("ECONNRESET");
|
||||
(error as any).code = "ECONNRESET";
|
||||
throw error;
|
||||
}
|
||||
return "success";
|
||||
},
|
||||
};
|
||||
|
||||
// Apply decorator manually
|
||||
const decorator = withRetry({
|
||||
maxAttempts: 3,
|
||||
baseDelay: 10,
|
||||
});
|
||||
const descriptor = decorator(testClass, "testMethod", {
|
||||
value: testClass.testMethod,
|
||||
writable: true,
|
||||
enumerable: false,
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
if (descriptor?.value) {
|
||||
testClass.testMethod = descriptor.value;
|
||||
}
|
||||
|
||||
const result = await testClass.testMethod();
|
||||
|
||||
expect(result).toBe("success");
|
||||
expect(testClass.attempts).toBe(3);
|
||||
});
|
||||
|
||||
it("should throw the last error when all retries are exhausted", async () => {
|
||||
const testClass = {
|
||||
attempts: 0,
|
||||
|
||||
async testMethod(): Promise<string> {
|
||||
this.attempts++;
|
||||
if (this.attempts === 1) {
|
||||
const error = new Error("First decorator error");
|
||||
(error as any).code = "ECONNRESET";
|
||||
throw error;
|
||||
} else if (this.attempts === 2) {
|
||||
const error = new Error("Second decorator error");
|
||||
(error as any).code = "ECONNRESET";
|
||||
throw error;
|
||||
} else {
|
||||
const error = new Error("Last decorator error");
|
||||
(error as any).code = "ECONNRESET";
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// Apply decorator manually
|
||||
const decorator = withRetry({
|
||||
maxAttempts: 3,
|
||||
baseDelay: 10,
|
||||
});
|
||||
const descriptor = decorator(testClass, "testMethod", {
|
||||
value: testClass.testMethod,
|
||||
writable: true,
|
||||
enumerable: false,
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
if (descriptor?.value) {
|
||||
testClass.testMethod = descriptor.value;
|
||||
}
|
||||
|
||||
await expect(testClass.testMethod()).rejects.toThrow(
|
||||
"Last decorator error",
|
||||
);
|
||||
expect(testClass.attempts).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("withLLMRetry decorator functional usage", () => {
|
||||
it("should use LLM-specific defaults", async () => {
|
||||
const testLLM = {
|
||||
attempts: 0,
|
||||
|
||||
async streamChat(): Promise<string> {
|
||||
this.attempts++;
|
||||
if (this.attempts < 2) {
|
||||
const error = new Error("Too Many Requests");
|
||||
(error as any).status = 429;
|
||||
throw error;
|
||||
}
|
||||
return "success";
|
||||
},
|
||||
};
|
||||
|
||||
// Apply decorator manually
|
||||
const decorator = withLLMRetry({ baseDelay: 10 });
|
||||
const descriptor = decorator(testLLM, "streamChat", {
|
||||
value: testLLM.streamChat,
|
||||
writable: true,
|
||||
enumerable: false,
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
if (descriptor?.value) {
|
||||
testLLM.streamChat = descriptor.value;
|
||||
}
|
||||
|
||||
const result = await testLLM.streamChat();
|
||||
|
||||
expect(result).toBe("success");
|
||||
expect(testLLM.attempts).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("exponential backoff with jitter", () => {
|
||||
it("should increase delay exponentially", async () => {
|
||||
const delays: number[] = [];
|
||||
const error = new Error("ECONNRESET");
|
||||
(error as any).code = "ECONNRESET";
|
||||
const mockFn = jest.fn().mockRejectedValue(error);
|
||||
|
||||
await expect(
|
||||
retryAsync(mockFn, {
|
||||
maxAttempts: 3,
|
||||
baseDelay: 1000,
|
||||
jitterFactor: 0, // No jitter for predictable testing
|
||||
onRetry: (error, attempt, delay) => {
|
||||
delays.push(delay);
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
|
||||
// First retry should be ~1000ms, second should be ~2000ms
|
||||
expect(delays).toHaveLength(2);
|
||||
expect(delays[0]).toBe(1000);
|
||||
expect(delays[1]).toBe(2000);
|
||||
});
|
||||
|
||||
it("should respect maxDelay", async () => {
|
||||
const delays: number[] = [];
|
||||
const error = new Error("ECONNRESET");
|
||||
(error as any).code = "ECONNRESET";
|
||||
const mockFn = jest.fn().mockRejectedValue(error);
|
||||
|
||||
await expect(
|
||||
retryAsync(mockFn, {
|
||||
maxAttempts: 4,
|
||||
baseDelay: 1000,
|
||||
maxDelay: 2500,
|
||||
jitterFactor: 0,
|
||||
onRetry: (error, attempt, delay) => {
|
||||
delays.push(delay);
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow();
|
||||
|
||||
// Delays should be: 1000, 2000, 2500 (capped)
|
||||
expect(delays).toEqual([1000, 2000, 2500]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rate limiting headers", () => {
|
||||
it("should respect retry-after header in seconds", async () => {
|
||||
const delays: number[] = [];
|
||||
const error = new Error("Too Many Requests");
|
||||
(error as any).status = 429;
|
||||
(error as any).headers = { "retry-after": "1" }; // 1 second for fast testing
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 100, // 100ms fallback
|
||||
onRetry: (error, attempt, delay) => {
|
||||
delays.push(delay);
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
expect(mockFn).toHaveBeenCalledTimes(2);
|
||||
// Should use header value (1000ms) not exponential backoff (100ms)
|
||||
expect(delays[0]).toBeGreaterThan(940); // 1000ms with wider tolerance for jitter and system performance
|
||||
expect(delays[0]).toBeLessThan(1080);
|
||||
});
|
||||
|
||||
it("should respect x-ratelimit-reset header", async () => {
|
||||
const delays: number[] = [];
|
||||
const error = new Error("Rate limited");
|
||||
(error as any).status = 429;
|
||||
(error as any).headers = { "x-ratelimit-reset": "0.5" }; // 500ms for fast testing
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 100,
|
||||
onRetry: (error, attempt, delay) => {
|
||||
delays.push(delay);
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
// Should use header value (500ms) not exponential backoff (100ms)
|
||||
expect(delays[0]).toBeGreaterThan(470); // 500ms with wider tolerance for jitter and system performance
|
||||
expect(delays[0]).toBeLessThan(540);
|
||||
});
|
||||
|
||||
it("should handle HTTP date format in retry-after header", async () => {
|
||||
const delays: number[] = [];
|
||||
const futureDate = new Date(Date.now() + 2000); // 2 seconds from now to avoid timing issues
|
||||
const error = new Error("Rate limited");
|
||||
(error as any).status = 429;
|
||||
(error as any).headers = { "retry-after": futureDate.toUTCString() };
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 100,
|
||||
maxDelay: 300, // Cap at 300ms for fast testing
|
||||
onRetry: (error, attempt, delay) => {
|
||||
delays.push(delay);
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
// Should be capped at maxDelay (300ms) since original would be ~2000ms
|
||||
expect(delays[0]).toBeGreaterThan(280);
|
||||
expect(delays[0]).toBeLessThan(320);
|
||||
});
|
||||
|
||||
it("should fallback to exponential backoff when no headers present", async () => {
|
||||
const delays: number[] = [];
|
||||
const error = new Error("Server Error");
|
||||
(error as any).status = 500;
|
||||
// No headers property
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 50, // Fast for testing
|
||||
jitterFactor: 0,
|
||||
onRetry: (error, attempt, delay) => {
|
||||
delays.push(delay);
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
// Should use exponential backoff (50ms) since no headers
|
||||
expect(delays[0]).toBe(50);
|
||||
});
|
||||
|
||||
it("should respect maxDelay even with rate limit headers", async () => {
|
||||
const delays: number[] = [];
|
||||
const error = new Error("Rate limited");
|
||||
(error as any).status = 429;
|
||||
(error as any).headers = { "retry-after": "10" }; // 10 seconds requested
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 100,
|
||||
maxDelay: 200, // Cap at 200ms for fast testing
|
||||
onRetry: (error, attempt, delay) => {
|
||||
delays.push(delay);
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
// Should be capped at maxDelay (200ms) not header value (10000ms)
|
||||
expect(delays[0]).toBeGreaterThan(190);
|
||||
expect(delays[0]).toBeLessThan(210);
|
||||
});
|
||||
|
||||
it("should handle case-insensitive header names", async () => {
|
||||
const delays: number[] = [];
|
||||
const error = new Error("Rate limited");
|
||||
(error as any).status = 429;
|
||||
(error as any).headers = { "Retry-After": "0.3" }; // 300ms for fast testing
|
||||
const mockFn = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(error)
|
||||
.mockResolvedValue("success");
|
||||
|
||||
const result = await retryAsync(mockFn, {
|
||||
maxAttempts: 2,
|
||||
baseDelay: 100,
|
||||
onRetry: (error, attempt, delay) => {
|
||||
delays.push(delay);
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toBe("success");
|
||||
// Should use header value (300ms)
|
||||
expect(delays[0]).toBeGreaterThan(284);
|
||||
expect(delays[0]).toBeLessThan(316);
|
||||
});
|
||||
});
|
||||
});
|
||||
459
core/llm/utils/retry.ts
Normal file
459
core/llm/utils/retry.ts
Normal file
|
|
@ -0,0 +1,459 @@
|
|||
/**
|
||||
* Configuration options for the retry decorator
|
||||
*/
|
||||
export interface RetryOptions {
|
||||
/** Maximum number of retry attempts (default: 3) */
|
||||
maxAttempts?: number;
|
||||
/** Base delay in milliseconds (default: 1000) */
|
||||
baseDelay?: number;
|
||||
/** Maximum delay in milliseconds (default: 30000) */
|
||||
maxDelay?: number;
|
||||
/** Jitter factor between 0 and 1 (default: 0.3) */
|
||||
jitterFactor?: number;
|
||||
/** Custom function to determine if an error should be retried */
|
||||
shouldRetry?: (error: any, attempt: number) => boolean;
|
||||
/** Custom function called on each retry attempt */
|
||||
onRetry?: (error: any, attempt: number, delay: number) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default configuration for retry behavior
|
||||
*/
|
||||
const DEFAULT_RETRY_OPTIONS: Required<RetryOptions> = {
|
||||
maxAttempts: 3,
|
||||
baseDelay: 1000,
|
||||
maxDelay: 30000,
|
||||
jitterFactor: 0.3,
|
||||
shouldRetry: defaultShouldRetry,
|
||||
onRetry: defaultOnRetry,
|
||||
};
|
||||
|
||||
/**
|
||||
* Default function to determine if an error should be retried
|
||||
* Retries on:
|
||||
* - Network errors
|
||||
* - HTTP 429 (Too Many Requests)
|
||||
* - HTTP 5xx (Server errors)
|
||||
* - Specific AWS errors
|
||||
* - Timeout errors
|
||||
*/
|
||||
function defaultShouldRetry(error: any, attempt: number): boolean {
|
||||
// Note: maxAttempts check is handled by the retry logic itself
|
||||
// This function only determines if the error type is retryable
|
||||
|
||||
// Network/connection errors
|
||||
if (
|
||||
error.code === "ENOTFOUND" ||
|
||||
error.code === "ECONNRESET" ||
|
||||
error.code === "ECONNREFUSED" ||
|
||||
error.code === "ETIMEDOUT"
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// AWS SDK specific errors (v3 - check for AWS error structure and retryable types)
|
||||
const isAwsError =
|
||||
error.$fault || error.$metadata || (error.name && error.__type);
|
||||
const awsRetryableErrors = [
|
||||
"ThrottlingException",
|
||||
"ServiceUnavailableException",
|
||||
"InternalServerError",
|
||||
"RequestTimeout",
|
||||
"ModelNotReadyException",
|
||||
"ModelTimeoutException",
|
||||
"ResourceNotFoundException",
|
||||
];
|
||||
|
||||
if (isAwsError && error.name && awsRetryableErrors.includes(error.name)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// HTTP status codes
|
||||
if (error.status || error.statusCode) {
|
||||
const status = error.status || error.statusCode;
|
||||
|
||||
// Rate limiting
|
||||
if (status === 429) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Server errors (5xx)
|
||||
if (status >= 500 && status < 600) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Don't retry client errors (4xx except 429)
|
||||
if (status >= 400 && status < 500) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Timeout errors
|
||||
if (
|
||||
error.name === "TimeoutError" ||
|
||||
error.message?.includes("timeout") ||
|
||||
error.message?.includes("TIMEOUT")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Abort signal errors should not be retried
|
||||
if (error.name === "AbortError" || error.code === "ABORT_ERR") {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Default to not retrying unknown errors
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Default function called on each retry attempt
|
||||
*/
|
||||
function defaultOnRetry(error: any, attempt: number, delay: number): void {
|
||||
console.warn(
|
||||
`Retry attempt ${attempt} after ${delay}ms delay. Error: ${error.message || error}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate delay with rate limit header awareness and exponential backoff fallback
|
||||
*/
|
||||
function calculateDelay(
|
||||
attempt: number,
|
||||
baseDelay: number,
|
||||
maxDelay: number,
|
||||
jitterFactor: number,
|
||||
error?: any,
|
||||
): number {
|
||||
// Check for rate limiting headers first (more accurate than exponential backoff)
|
||||
if (error?.headers) {
|
||||
const retryAfter =
|
||||
error.headers["retry-after"] ||
|
||||
error.headers["x-ratelimit-reset"] ||
|
||||
error.headers["ratelimit-reset"] ||
|
||||
error.headers["Retry-After"] ||
|
||||
error.headers["X-RateLimit-Reset"] ||
|
||||
error.headers["RateLimit-Reset"];
|
||||
|
||||
if (retryAfter) {
|
||||
let delayMs: number;
|
||||
|
||||
// Parse retry-after header (can be seconds or HTTP date)
|
||||
if (typeof retryAfter === "string" && isNaN(Number(retryAfter))) {
|
||||
// HTTP date format
|
||||
const resetTime = new Date(retryAfter).getTime();
|
||||
const now = Date.now();
|
||||
delayMs = Math.max(0, resetTime - now);
|
||||
} else {
|
||||
// Seconds format
|
||||
delayMs = Number(retryAfter) * 1000;
|
||||
}
|
||||
|
||||
// Respect maxDelay and add small jitter to spread requests
|
||||
const cappedDelay = Math.min(delayMs, maxDelay);
|
||||
const jitterMultiplier = 1 + (Math.random() * 0.1 - 0.05); // Small jitter ±5%
|
||||
return Math.max(0, Math.floor(cappedDelay * jitterMultiplier));
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to exponential backoff if no rate limit headers
|
||||
const exponentialDelay = baseDelay * Math.pow(2, attempt - 1);
|
||||
const cappedDelay = Math.min(exponentialDelay, maxDelay);
|
||||
|
||||
// Add jitter: random value between (1 - jitterFactor) and (1 + jitterFactor)
|
||||
const jitterMultiplier = 1 + (Math.random() * 2 - 1) * jitterFactor;
|
||||
const jitteredDelay = cappedDelay * jitterMultiplier;
|
||||
|
||||
return Math.max(0, Math.floor(jitteredDelay));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleep for the specified number of milliseconds
|
||||
*/
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry decorator for async functions with exponential backoff and jitter
|
||||
*
|
||||
* @param options Retry configuration options
|
||||
* @returns Decorator function
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* class MyLLM {
|
||||
* @withRetry({ maxAttempts: 5, baseDelay: 2000 })
|
||||
* async streamChat(messages: ChatMessage[]): Promise<AsyncGenerator<ChatMessage>> {
|
||||
* // Implementation that might fail
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function withRetry(options: RetryOptions = {}) {
|
||||
const config = { ...DEFAULT_RETRY_OPTIONS, ...options };
|
||||
|
||||
return function (...args: any[]): any {
|
||||
// Handle different decorator calling patterns
|
||||
const [target, propertyName, descriptor] = args;
|
||||
|
||||
// Get the original method
|
||||
let originalMethod: Function;
|
||||
if (descriptor && descriptor.value) {
|
||||
originalMethod = descriptor.value;
|
||||
} else {
|
||||
// Get method from prototype
|
||||
originalMethod = target[propertyName];
|
||||
}
|
||||
|
||||
if (!originalMethod || typeof originalMethod !== "function") {
|
||||
throw new Error(`@withRetry can only be applied to methods`);
|
||||
}
|
||||
|
||||
// Check if the original method is an async generator function
|
||||
const isAsyncGenerator =
|
||||
originalMethod.constructor.name === "AsyncGeneratorFunction";
|
||||
|
||||
const wrappedMethod = isAsyncGenerator
|
||||
? async function* (this: any, ...methodArgs: any[]) {
|
||||
let lastError: any;
|
||||
|
||||
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
|
||||
try {
|
||||
const generator = originalMethod.apply(this, methodArgs);
|
||||
yield* createRetryableAsyncGenerator(
|
||||
generator,
|
||||
config,
|
||||
originalMethod,
|
||||
this,
|
||||
methodArgs,
|
||||
attempt,
|
||||
);
|
||||
return; // Successfully completed
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
|
||||
// Check if we should retry this error
|
||||
if (!config.shouldRetry(error, attempt)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Don't delay on the last attempt
|
||||
if (attempt === config.maxAttempts) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Calculate delay and wait
|
||||
const delay = calculateDelay(
|
||||
attempt,
|
||||
config.baseDelay,
|
||||
config.maxDelay,
|
||||
config.jitterFactor,
|
||||
error,
|
||||
);
|
||||
|
||||
config.onRetry(error, attempt, delay);
|
||||
await sleep(delay);
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here, all attempts failed
|
||||
throw lastError;
|
||||
}
|
||||
: async function (this: any, ...methodArgs: any[]) {
|
||||
let lastError: any;
|
||||
|
||||
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
|
||||
try {
|
||||
const result = originalMethod.apply(this, methodArgs);
|
||||
return await result;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
|
||||
// Check if we should retry this error
|
||||
if (!config.shouldRetry(error, attempt)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Don't delay on the last attempt
|
||||
if (attempt === config.maxAttempts) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Calculate delay and wait
|
||||
const delay = calculateDelay(
|
||||
attempt,
|
||||
config.baseDelay,
|
||||
config.maxDelay,
|
||||
config.jitterFactor,
|
||||
error,
|
||||
);
|
||||
|
||||
config.onRetry(error, attempt, delay);
|
||||
|
||||
await sleep(delay);
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here, all attempts failed
|
||||
throw lastError;
|
||||
};
|
||||
|
||||
// Apply the wrapped method based on how the decorator was called
|
||||
if (descriptor) {
|
||||
descriptor.value = wrappedMethod;
|
||||
return descriptor;
|
||||
} else {
|
||||
// Handle case where descriptor is not provided
|
||||
target[propertyName] = wrappedMethod;
|
||||
return wrappedMethod;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a retryable async generator that handles errors during iteration
|
||||
*/
|
||||
async function* createRetryableAsyncGenerator<T>(
|
||||
generator: AsyncGenerator<T>,
|
||||
config: Required<RetryOptions>,
|
||||
originalMethod: Function,
|
||||
context: any,
|
||||
args: any[],
|
||||
initialAttempt: number,
|
||||
): AsyncGenerator<T> {
|
||||
let currentGenerator = generator;
|
||||
let attempt = initialAttempt;
|
||||
|
||||
try {
|
||||
for await (const value of currentGenerator) {
|
||||
yield value;
|
||||
}
|
||||
} catch (error) {
|
||||
// If we encounter an error during iteration, we can retry by creating a new generator
|
||||
let lastError = error;
|
||||
|
||||
for (
|
||||
let retryAttempt = attempt + 1;
|
||||
retryAttempt <= config.maxAttempts;
|
||||
retryAttempt++
|
||||
) {
|
||||
// Check if we should retry this error
|
||||
if (!config.shouldRetry(error, retryAttempt)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Don't delay on the last attempt
|
||||
if (retryAttempt === config.maxAttempts) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Calculate delay and wait
|
||||
const delay = calculateDelay(
|
||||
retryAttempt,
|
||||
config.baseDelay,
|
||||
config.maxDelay,
|
||||
config.jitterFactor,
|
||||
error,
|
||||
);
|
||||
|
||||
config.onRetry(error, retryAttempt, delay);
|
||||
await sleep(delay);
|
||||
|
||||
try {
|
||||
// Create a new generator and continue iteration
|
||||
const newGenerator = await originalMethod.apply(context, args);
|
||||
|
||||
if (
|
||||
newGenerator &&
|
||||
typeof newGenerator[Symbol.asyncIterator] === "function"
|
||||
) {
|
||||
for await (const value of newGenerator) {
|
||||
yield value;
|
||||
}
|
||||
return; // Successfully completed
|
||||
} else {
|
||||
throw new Error("Method did not return an async generator on retry");
|
||||
}
|
||||
} catch (retryError) {
|
||||
lastError = retryError;
|
||||
error = retryError;
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here, all retry attempts failed
|
||||
throw lastError;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Functional version of retry for use without decorators
|
||||
*
|
||||
* @param fn Function to retry
|
||||
* @param options Retry configuration options
|
||||
* @returns Promise that resolves with the function result or rejects with the last error
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const result = await retryAsync(
|
||||
* () => someApiCall(),
|
||||
* { maxAttempts: 3, baseDelay: 1000 }
|
||||
* );
|
||||
* ```
|
||||
*/
|
||||
export async function retryAsync<T>(
|
||||
fn: () => Promise<T>,
|
||||
options: RetryOptions = {},
|
||||
): Promise<T> {
|
||||
const config = { ...DEFAULT_RETRY_OPTIONS, ...options };
|
||||
let lastError: any;
|
||||
|
||||
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
|
||||
// Check if we should retry this error
|
||||
if (!config.shouldRetry(error, attempt)) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Don't delay on the last attempt
|
||||
if (attempt === config.maxAttempts) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Calculate delay and wait
|
||||
const delay = calculateDelay(
|
||||
attempt,
|
||||
config.baseDelay,
|
||||
config.maxDelay,
|
||||
config.jitterFactor,
|
||||
error,
|
||||
);
|
||||
|
||||
config.onRetry(error, attempt, delay);
|
||||
|
||||
await sleep(delay);
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here, all attempts failed
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry decorator specifically configured for LLM providers
|
||||
* Uses sensible defaults for LLM API calls, including longer delays
|
||||
* for capacity provisioning (e.g., AWS Bedrock can require up to 59+ seconds)
|
||||
*/
|
||||
export function withLLMRetry(options: Partial<RetryOptions> = {}) {
|
||||
return withRetry({
|
||||
maxAttempts: 5, // More attempts for capacity issues
|
||||
baseDelay: 2000, // Start with 2 seconds
|
||||
maxDelay: 90000, // Allow up to 90 seconds for capacity provisioning
|
||||
jitterFactor: 0.4, // Slightly more jitter to spread load
|
||||
...options,
|
||||
});
|
||||
}
|
||||
|
|
@ -158,19 +158,19 @@ export class NextEditProvider {
|
|||
this.loggingService.cancel();
|
||||
}
|
||||
|
||||
// public accept(completionId: string) {
|
||||
// const outcome = this.loggingService.accept(completionId);
|
||||
// if (!outcome) {
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
public accept(completionId: string) {
|
||||
const outcome = this.loggingService.accept(completionId);
|
||||
if (!outcome) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// public reject(completionId: string) {
|
||||
// const outcome = this.loggingService.reject(completionId);
|
||||
// if (!outcome) {
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
public reject(completionId: string) {
|
||||
const outcome = this.loggingService.reject(completionId);
|
||||
if (!outcome) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public markDisplayed(completionId: string, outcome: NextEditOutcome) {
|
||||
this.loggingService.markDisplayed(completionId, outcome);
|
||||
|
|
@ -237,7 +237,6 @@ export class NextEditProvider {
|
|||
|
||||
// TODO: Toggle between the default endpoint and the finetuned endpoint.
|
||||
const prompts: Prompt[] = [];
|
||||
|
||||
if (this.endpointType === "default") {
|
||||
prompts.push(renderDefaultSystemPrompt());
|
||||
prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
|
||||
|
|
@ -272,17 +271,30 @@ export class NextEditProvider {
|
|||
cursorPosition: helper.pos,
|
||||
...helper.options,
|
||||
};
|
||||
|
||||
// When using the JetBrains extension, mark as displayed.
|
||||
// This helps us not need to make additional network calls just to mark as displayed.
|
||||
const ideType = (await this.ide.getIdeInfo()).ideType;
|
||||
if (ideType === "jetbrains") {
|
||||
this.markDisplayed(input.completionId, outcomeNext);
|
||||
}
|
||||
|
||||
return outcomeNext;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
} else {
|
||||
const msg: ChatMessage = await llm.chat(prompts, token);
|
||||
|
||||
if (typeof msg.content === "string") {
|
||||
// TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
|
||||
const nextCompletion = replaceEscapedCharacters(
|
||||
msg.content.split("<|editable_region_start|>\n")[1],
|
||||
).replace(/\n$/, "");
|
||||
// NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
|
||||
const nextCompletion = msg.content.split(
|
||||
"<|editable_region_start|>\n",
|
||||
)[1]
|
||||
? replaceEscapedCharacters(
|
||||
msg.content.split("<|editable_region_start|>\n")[1],
|
||||
).replace(/\n$/, "")
|
||||
: "";
|
||||
|
||||
const currCursorPos = helper.pos;
|
||||
const editableRegionStartLine = Math.max(
|
||||
|
|
@ -319,6 +331,14 @@ export class NextEditProvider {
|
|||
cursorPosition: helper.pos,
|
||||
...helper.options,
|
||||
};
|
||||
|
||||
// When using the JetBrains extension, mark as displayed.
|
||||
// This helps us not need to make additional network calls just to mark as displayed.
|
||||
const ideType = (await this.ide.getIdeInfo()).ideType;
|
||||
if (ideType === "jetbrains") {
|
||||
this.markDisplayed(input.completionId, outcomeNext);
|
||||
}
|
||||
|
||||
return outcomeNext;
|
||||
} else {
|
||||
return undefined;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
export const IS_NEXT_EDIT_ACTIVE = false;
|
||||
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 5;
|
||||
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0;
|
||||
export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
|
||||
export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
|
||||
export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
|
||||
|
|
|
|||
17
core/package-lock.json
generated
17
core/package-lock.json
generated
|
|
@ -51,7 +51,7 @@
|
|||
"node-html-markdown": "^1.3.0",
|
||||
"ollama": "^0.4.6",
|
||||
"onnxruntime-node": "1.14.0",
|
||||
"openai": "^4.76.0",
|
||||
"openai": "^4.104.0",
|
||||
"p-limit": "^6.1.0",
|
||||
"partial-json": "^0.1.7",
|
||||
"pg": "^8.11.3",
|
||||
|
|
@ -180,7 +180,7 @@
|
|||
"dotenv": "^16.5.0",
|
||||
"json-schema": "^0.4.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
"openai": "^4.76.0",
|
||||
"openai": "^4.104.0",
|
||||
"uuid": "^11.1.0",
|
||||
"zod": "^3.24.2"
|
||||
},
|
||||
|
|
@ -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": {
|
||||
|
|
@ -14329,9 +14330,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/openai": {
|
||||
"version": "4.76.0",
|
||||
"resolved": "https://registry.npmjs.org/openai/-/openai-4.76.0.tgz",
|
||||
"integrity": "sha512-QBGIetjX1C9xDp5XGa/3mPnfKI9BgAe2xHQX6PmO98wuW9qQaurBaumcYptQWc9LHZZq7cH/Y1Rjnsr6uUDdVw==",
|
||||
"version": "4.104.0",
|
||||
"resolved": "https://registry.npmjs.org/openai/-/openai-4.104.0.tgz",
|
||||
"integrity": "sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==",
|
||||
"dependencies": {
|
||||
"@types/node": "^18.11.18",
|
||||
"@types/node-fetch": "^2.6.4",
|
||||
|
|
@ -14345,9 +14346,13 @@
|
|||
"openai": "bin/cli"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"ws": "^8.18.0",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"ws": {
|
||||
"optional": true
|
||||
},
|
||||
"zod": {
|
||||
"optional": true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -78,6 +78,7 @@
|
|||
"handlebars": "^4.7.8",
|
||||
"http-proxy-agent": "^7.0.1",
|
||||
"https-proxy-agent": "^7.0.3",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"ignore": "^5.3.1",
|
||||
"is-localhost-ip": "^2.0.0",
|
||||
"jinja-js": "0.1.8",
|
||||
|
|
@ -91,7 +92,7 @@
|
|||
"node-html-markdown": "^1.3.0",
|
||||
"ollama": "^0.4.6",
|
||||
"onnxruntime-node": "1.14.0",
|
||||
"openai": "^4.76.0",
|
||||
"openai": "^4.104.0",
|
||||
"p-limit": "^6.1.0",
|
||||
"partial-json": "^0.1.7",
|
||||
"pg": "^8.11.3",
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { GlobalContextModelSelections } from "../util/GlobalContext";
|
|||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ChatMessage,
|
||||
CompiledMessagesResult,
|
||||
CompleteOnboardingPayload,
|
||||
ContextItem,
|
||||
ContextItemWithId,
|
||||
|
|
@ -25,6 +26,7 @@ import {
|
|||
FileSymbolMap,
|
||||
IdeSettings,
|
||||
LLMFullCompletionOptions,
|
||||
MessageOption,
|
||||
ModelDescription,
|
||||
PromptLog,
|
||||
RangeInFile,
|
||||
|
|
@ -89,7 +91,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
},
|
||||
];
|
||||
"config/deleteModel": [{ title: string }, void];
|
||||
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
|
||||
"config/reload": [undefined, void];
|
||||
"config/refreshProfiles": [
|
||||
(
|
||||
| undefined
|
||||
|
|
@ -145,6 +147,9 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"context/indexDocs": [{ reIndex: boolean }, void];
|
||||
"autocomplete/cancel": [undefined, void];
|
||||
"autocomplete/accept": [{ completionId: string }, void];
|
||||
"nextEdit/predict": [AutocompleteInput, string[]];
|
||||
"nextEdit/reject": [{ completionId: string }, void];
|
||||
"nextEdit/accept": [{ completionId: string }, void];
|
||||
"llm/complete": [
|
||||
{
|
||||
prompt: string;
|
||||
|
|
@ -159,6 +164,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
messages: ChatMessage[];
|
||||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
messageOptions?: MessageOption;
|
||||
legacySlashCommandData?: {
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
|
|
@ -170,12 +176,23 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
AsyncGenerator<ChatMessage, PromptLog>,
|
||||
];
|
||||
streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator<DiffLine>];
|
||||
"llm/compileChat": [
|
||||
{ messages: ChatMessage[]; options: LLMFullCompletionOptions },
|
||||
CompiledMessagesResult,
|
||||
];
|
||||
"chatDescriber/describe": [
|
||||
{
|
||||
text: string;
|
||||
},
|
||||
string | undefined,
|
||||
];
|
||||
"conversation/compact": [
|
||||
{
|
||||
index: number;
|
||||
sessionId: string;
|
||||
},
|
||||
string | undefined,
|
||||
];
|
||||
"stats/getTokensPerDay": [
|
||||
undefined,
|
||||
{ day: string; promptTokens: number; generatedTokens: number }[],
|
||||
|
|
|
|||
|
|
@ -37,12 +37,17 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"autocomplete/complete",
|
||||
"autocomplete/cancel",
|
||||
"autocomplete/accept",
|
||||
"nextEdit/predict",
|
||||
"nextEdit/reject",
|
||||
"nextEdit/accept",
|
||||
"tts/kill",
|
||||
"llm/complete",
|
||||
"llm/streamChat",
|
||||
"llm/listModels",
|
||||
"llm/compileChat",
|
||||
"streamDiffLines",
|
||||
"chatDescriber/describe",
|
||||
"conversation/compact",
|
||||
"stats/getTokensPerDay",
|
||||
"stats/getTokensPerModel",
|
||||
// Codebase
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ export const ideSettingsPromise = testIde.getIdeSettings();
|
|||
export const testControlPlaneClient = new ControlPlaneClient(
|
||||
Promise.resolve(undefined),
|
||||
ideSettingsPromise,
|
||||
testIde.getIdeInfo(),
|
||||
);
|
||||
|
||||
export const testConfigHandler = new ConfigHandler(
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Tool } from "../..";
|
||||
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile";
|
||||
|
||||
export interface EditToolArgs {
|
||||
filepath: string;
|
||||
|
|
@ -18,7 +19,7 @@ export const editFileTool: Tool = {
|
|||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.EditExistingFile,
|
||||
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}`,
|
||||
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "changes"],
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
|||
|
||||
export const lsTool: Tool = {
|
||||
type: "function",
|
||||
displayTitle: "LS Tool",
|
||||
displayTitle: "ls",
|
||||
wouldLikeTo: "list files and folders in {{{ dirPath }}}",
|
||||
isCurrently: "listing files and folders in {{{ dirPath }}}",
|
||||
hasAlready: "listed files and folders in {{{ dirPath }}}",
|
||||
|
|
@ -3,9 +3,13 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
|||
|
||||
export interface SearchAndReplaceInFileArgs {
|
||||
filepath: string;
|
||||
diff: string;
|
||||
diffs: string[];
|
||||
}
|
||||
|
||||
// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts`
|
||||
export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
|
||||
"Note this tool CANNOT be called in parallel.";
|
||||
|
||||
/**
|
||||
* This tool is in an experimental state.
|
||||
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
|
||||
|
|
@ -21,20 +25,22 @@ export const searchAndReplaceInFileTool: Tool = {
|
|||
isInstant: false,
|
||||
function: {
|
||||
name: BuiltInToolNames.SearchAndReplaceInFile,
|
||||
description:
|
||||
"Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
|
||||
description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "diff"],
|
||||
required: ["filepath", "diffs"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to modify, relative to the root of the workspace.",
|
||||
},
|
||||
diff: {
|
||||
type: "string",
|
||||
description: `One or more SEARCH/REPLACE blocks following this exact format:
|
||||
diffs: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
},
|
||||
description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
|
||||
\`\`\`
|
||||
------- SEARCH
|
||||
[exact content to find]
|
||||
|
|
@ -51,16 +57,17 @@ Critical rules:
|
|||
* Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
|
||||
* Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
|
||||
* When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
|
||||
3. Keep SEARCH/REPLACE blocks concise:
|
||||
3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application.
|
||||
4. Keep SEARCH/REPLACE blocks concise:
|
||||
* Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
|
||||
* Include just the changing lines, and a few surrounding lines if needed for uniqueness.
|
||||
* Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
|
||||
* Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
|
||||
4. Splitting up tool calls:
|
||||
5. Splitting up tool calls:
|
||||
* When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
|
||||
* If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
|
||||
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
|
||||
5. Special operations:
|
||||
6. Special operations:
|
||||
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
|
||||
* To delete code: Use empty REPLACE section
|
||||
|
||||
|
|
@ -78,7 +85,8 @@ Usage:
|
|||
[new content to replace with]
|
||||
+++++++ REPLACE
|
||||
\`\`\`
|
||||
`,
|
||||
|
||||
Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,5 +1,22 @@
|
|||
import iconv from "iconv-lite";
|
||||
import childProcess from "node:child_process";
|
||||
import util from "node:util";
|
||||
// Automatically decode the buffer according to the platform to avoid garbled Chinese
|
||||
function getDecodedOutput(data: Buffer): string {
|
||||
if (process.platform === "win32") {
|
||||
try {
|
||||
let out = iconv.decode(data, "utf-8");
|
||||
if (/<2F>/.test(out)) {
|
||||
out = iconv.decode(data, "gbk");
|
||||
}
|
||||
return out;
|
||||
} catch {
|
||||
return iconv.decode(data, "gbk");
|
||||
}
|
||||
} else {
|
||||
return data.toString();
|
||||
}
|
||||
}
|
||||
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ToolImpl } from ".";
|
||||
|
|
@ -77,7 +94,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
// Skip if this process has been backgrounded
|
||||
if (isProcessBackgrounded(toolCallId)) return;
|
||||
|
||||
const newOutput = data.toString();
|
||||
const newOutput = getDecodedOutput(data);
|
||||
terminalOutput += newOutput;
|
||||
|
||||
// Send partial output to UI
|
||||
|
|
@ -103,7 +120,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
// Skip if this process has been backgrounded
|
||||
if (isProcessBackgrounded(toolCallId)) return;
|
||||
|
||||
const newOutput = data.toString();
|
||||
const newOutput = getDecodedOutput(data);
|
||||
terminalOutput += newOutput;
|
||||
|
||||
// Send partial output to UI, status is not required
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { editFileTool } from "./definitions/editFile";
|
|||
import { fetchUrlContentTool } from "./definitions/fetchUrlContent";
|
||||
import { globSearchTool } from "./definitions/globSearch";
|
||||
import { grepSearchTool } from "./definitions/grepSearch";
|
||||
import { lsTool } from "./definitions/lsTool";
|
||||
import { lsTool } from "./definitions/ls";
|
||||
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
|
||||
import { readFileTool } from "./definitions/readFile";
|
||||
import { requestRuleTool } from "./definitions/requestRule";
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@
|
|||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"noEmitOnError": false,
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": ["./**/*.ts", "./**/*.js", "./**/*.d.ts"],
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
// core/util/GlobalContext.test.ts
|
||||
import { GlobalContext, GlobalContextType } from "./GlobalContext";
|
||||
import fs from "node:fs";
|
||||
import path from "path";
|
||||
import { GlobalContext } from "./GlobalContext";
|
||||
import { getGlobalContextFilePath } from "./paths";
|
||||
|
||||
describe("GlobalContext", () => {
|
||||
|
|
@ -69,13 +68,40 @@ describe("GlobalContext", () => {
|
|||
const value = globalContext.get("indexingPaused");
|
||||
expect(value).toBeUndefined();
|
||||
expect(consoleWarnMock).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Error parsing global context"),
|
||||
expect.stringContaining(
|
||||
"Error parsing global context, deleting corrupted file",
|
||||
),
|
||||
);
|
||||
|
||||
// Clean up
|
||||
consoleWarnMock.mockRestore();
|
||||
});
|
||||
|
||||
it("should delete corrupted file on get and allow fresh start", () => {
|
||||
// Write invalid JSON to the file
|
||||
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
|
||||
expect(fs.existsSync(globalContextFilePath)).toBe(true);
|
||||
|
||||
const consoleWarnMock = jest
|
||||
.spyOn(console, "warn")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
// Try to get a value - this should delete the corrupted file
|
||||
const value = globalContext.get("indexingPaused");
|
||||
expect(value).toBeUndefined();
|
||||
|
||||
// File should be deleted after corruption is detected
|
||||
expect(fs.existsSync(globalContextFilePath)).toBe(false);
|
||||
|
||||
// Now we should be able to update and get values normally
|
||||
globalContext.update("indexingPaused", true);
|
||||
const newValue = globalContext.get("indexingPaused");
|
||||
expect(newValue).toBe(true);
|
||||
|
||||
// Clean up
|
||||
consoleWarnMock.mockRestore();
|
||||
});
|
||||
|
||||
it("should handle JSON parsing errors gracefully on update", () => {
|
||||
// Write invalid JSON to the file
|
||||
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
|
||||
|
|
@ -87,15 +113,45 @@ describe("GlobalContext", () => {
|
|||
// Attempt to update
|
||||
globalContext.update("indexingPaused", true);
|
||||
|
||||
// The update should have been skipped due to JSON parsing error
|
||||
// So attempting to get the value should return undefined
|
||||
const value = globalContext.get("indexingPaused");
|
||||
expect(value).toBeUndefined();
|
||||
|
||||
expect(consoleWarnMock).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Error updating global context"),
|
||||
expect.stringContaining(
|
||||
"Error updating global context, deleting corrupted file",
|
||||
),
|
||||
);
|
||||
|
||||
// The update should have recreated the file with just the new value
|
||||
const value = globalContext.get("indexingPaused");
|
||||
expect(value).toBe(true);
|
||||
|
||||
// Clean up
|
||||
consoleWarnMock.mockRestore();
|
||||
});
|
||||
|
||||
it("should delete and recreate corrupted file on update", () => {
|
||||
// Write invalid JSON to the file
|
||||
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
|
||||
expect(fs.existsSync(globalContextFilePath)).toBe(true);
|
||||
|
||||
const consoleWarnMock = jest
|
||||
.spyOn(console, "warn")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
// Try to update - this should delete the corrupted file and recreate it
|
||||
globalContext.update("indexingPaused", true);
|
||||
|
||||
// File should still exist but with valid JSON now
|
||||
expect(fs.existsSync(globalContextFilePath)).toBe(true);
|
||||
|
||||
// Should be able to read the value
|
||||
const value = globalContext.get("indexingPaused");
|
||||
expect(value).toBe(true);
|
||||
|
||||
// Should be able to add more values
|
||||
globalContext.update("hasAlreadyCreatedAPromptFile", false);
|
||||
expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(false);
|
||||
// Original value should still be there
|
||||
expect(globalContext.get("indexingPaused")).toBe(true);
|
||||
|
||||
// Clean up
|
||||
consoleWarnMock.mockRestore();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -68,7 +68,28 @@ export class GlobalContext {
|
|||
try {
|
||||
parsed = JSON.parse(data);
|
||||
} catch (e: any) {
|
||||
console.warn(`Error updating global context: ${e}`);
|
||||
console.warn(
|
||||
`Error updating global context, deleting corrupted file: ${e}`,
|
||||
);
|
||||
// Delete the corrupted file and recreate it fresh
|
||||
try {
|
||||
fs.unlinkSync(filepath);
|
||||
} catch (deleteError) {
|
||||
console.warn(
|
||||
`Error deleting corrupted global context file: ${deleteError}`,
|
||||
);
|
||||
}
|
||||
// Recreate the file with just the new value
|
||||
fs.writeFileSync(
|
||||
filepath,
|
||||
JSON.stringify(
|
||||
{
|
||||
[key]: value,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -90,7 +111,17 @@ export class GlobalContext {
|
|||
const parsed = JSON.parse(data);
|
||||
return parsed[key];
|
||||
} catch (e: any) {
|
||||
console.warn(`Error parsing global context: ${e}`);
|
||||
console.warn(
|
||||
`Error parsing global context, deleting corrupted file: ${e}`,
|
||||
);
|
||||
// Delete the corrupted file so it can be recreated fresh
|
||||
try {
|
||||
fs.unlinkSync(filepath);
|
||||
} catch (deleteError) {
|
||||
console.warn(
|
||||
`Error deleting corrupted global context file: ${deleteError}`,
|
||||
);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
89
core/util/conversationCompaction.ts
Normal file
89
core/util/conversationCompaction.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import { ILLM } from "..";
|
||||
import { HistoryManager } from "./history";
|
||||
import { stripImages } from "./messageContent";
|
||||
|
||||
export interface CompactionParams {
|
||||
sessionId: string;
|
||||
index: number;
|
||||
historyManager: HistoryManager;
|
||||
currentModel: ILLM;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compacts conversation history up to a specified index by generating a summary.
|
||||
* This helper function extracts the compaction logic from the main core handler.
|
||||
*
|
||||
* @param params - Object containing sessionId, index, historyManager, and currentModel
|
||||
* @returns Promise<void> - Updates the session with the conversation summary
|
||||
*/
|
||||
export async function compactConversation({
|
||||
sessionId,
|
||||
index,
|
||||
historyManager,
|
||||
currentModel,
|
||||
}: CompactionParams): Promise<void> {
|
||||
// Get the current session
|
||||
const session = historyManager.load(sessionId);
|
||||
const historyUpToIndex = session.history.slice(0, index + 1);
|
||||
|
||||
// Apply the same filtering logic as in constructMessages, but exclude the target message
|
||||
// if it already has a summary (we're re-compacting)
|
||||
let summaryContent = "";
|
||||
let filteredHistory = historyUpToIndex;
|
||||
|
||||
// First, check if the target message already has a summary and ignore it
|
||||
const targetMessageHasSummary = historyUpToIndex[index].conversationSummary;
|
||||
const searchHistory = targetMessageHasSummary
|
||||
? historyUpToIndex.slice(0, index)
|
||||
: historyUpToIndex;
|
||||
|
||||
// Find the most recent conversation summary (excluding target if it has one)
|
||||
for (let i = searchHistory.length - 1; i >= 0; i--) {
|
||||
const summary = searchHistory[i].conversationSummary;
|
||||
if (summary) {
|
||||
summaryContent = summary;
|
||||
// Only include messages that come AFTER the message with the summary
|
||||
filteredHistory = historyUpToIndex.slice(i + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Create messages from filtered history
|
||||
const messages = filteredHistory.map((item: any) => item.message);
|
||||
|
||||
// If there's a previous summary, include it as a user message at the beginning
|
||||
if (summaryContent) {
|
||||
messages.unshift({
|
||||
role: "user",
|
||||
content: `Previous conversation summary:\n\n${summaryContent}`,
|
||||
});
|
||||
}
|
||||
|
||||
const compactionPrompt = {
|
||||
role: "user" as const,
|
||||
content:
|
||||
"Create a comprehensive summary of this conversation that captures all essential information needed to continue the work seamlessly. Structure your response to preserve technical accuracy and context continuity.\n\nYour summary should include:\n\n1. **Conversation Overview**: Describe the main topic and progression of the discussion, including any shifts in focus or direction.\n\n2. **Active Development**: Detail what was being implemented, modified, or debugged most recently. Include specific technical approaches and methodologies used.\n\n3. **Technical Stack**: List all relevant technologies, frameworks, libraries, coding patterns, and architectural decisions discussed.\n\n4. **File Operations**: Document all files that were created, modified, or referenced, including their purposes and key changes. Include important code snippets and their locations.\n\n5. **Solutions & Troubleshooting**: Summarize problems encountered and how they were resolved, including any debugging steps or workarounds applied.\n\n6. **Outstanding Work**: Clearly identify any incomplete tasks, pending implementations, or next steps that were discussed. Include direct references to user requests and current progress.\n\nIf there's a previous summary in the conversation, integrate its relevant information while removing outdated details. Focus on technical precision and include specific identifiers (file paths, function names, class names, etc.) that would be essential for continuation. Write in third person and maintain an objective, technical tone.",
|
||||
};
|
||||
|
||||
// Generate the summary using the current model
|
||||
const response = await currentModel.chat(
|
||||
[...messages, compactionPrompt],
|
||||
new AbortController().signal,
|
||||
{},
|
||||
);
|
||||
|
||||
// Update the target message with the conversation summary
|
||||
const updatedHistory = [...session.history];
|
||||
updatedHistory[index] = {
|
||||
...updatedHistory[index],
|
||||
conversationSummary: stripImages(response.content),
|
||||
};
|
||||
|
||||
// Update the session with the new history
|
||||
const updatedSession = {
|
||||
...session,
|
||||
history: updatedHistory,
|
||||
};
|
||||
|
||||
historyManager.save(updatedSession);
|
||||
}
|
||||
|
|
@ -120,6 +120,7 @@ class FileSystemIde implements IDE {
|
|||
version: "0.1",
|
||||
remoteName: "na",
|
||||
extensionVersion: "na",
|
||||
isPrerelease: false,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ function safeParseArray<T>(
|
|||
}
|
||||
}
|
||||
|
||||
class HistoryManager {
|
||||
export class HistoryManager {
|
||||
list(options: ListHistoryOptions): SessionMetadata[] {
|
||||
const filepath = getSessionsListPath();
|
||||
if (!fs.existsSync(filepath)) {
|
||||
|
|
|
|||
|
|
@ -11,6 +11,6 @@ description: "Model Context Protocol servers provide specialized functionality:"
|
|||
|
||||

|
||||
|
||||
## Learn More[](#learn-more "Direct link to Learn More")
|
||||
## Learn More
|
||||
|
||||
Learn more in the [MCP deep dive](/customization/mcp-tools), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ description: "These blocks form the foundation of the entire assistant experienc
|
|||
|
||||

|
||||
|
||||
## Learn More[](#learn-more "Direct link to Learn More")
|
||||
## Learn More
|
||||
|
||||
Continue supports [many model providers](/customization/models#openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
|
||||
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ description: "Continue can be deeply customized. For example you might:"
|
|||
|
||||
Whatever you choose, you'll probably start by editing your Assistant.
|
||||
|
||||
## Editing your assistant[](#editing-your-assistant "Direct link to Editing your assistant")
|
||||
## Editing your assistant
|
||||
|
||||
You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon.
|
||||
|
||||
|
|
|
|||
|
|
@ -11,6 +11,6 @@ description: "These are the specialized instructions that shape how models respo
|
|||
|
||||

|
||||
|
||||
## Learn More[](#learn-more "Direct link to Learn More")
|
||||
## Learn More
|
||||
|
||||
Prompt blocks have the same syntax as [prompt files](/customization/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).
|
||||
|
|
|
|||
|
|
@ -11,10 +11,10 @@ Think of these as the guardrails for your AI coding assistants:
|
|||
|
||||
By implementing rules, you transform the AI from a generic coding assistant into a knowledgeable team member that understands your project's unique requirements and constraints.
|
||||
|
||||
### How Rules Work[](#how-rules-work "Direct link to How Rules Work")
|
||||
### How Rules Work
|
||||
|
||||
Your assistant detects rule blocks and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes.
|
||||
|
||||
## Learn More[](#learn-more "Direct link to Learn More")
|
||||
## Learn More
|
||||
|
||||
Learn more in the [rules deep dive](/customization/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.
|
||||
|
|
|
|||
|
|
@ -4,8 +4,6 @@ description: Talk to your codebase
|
|||
keywords: [talk, embeddings, reranker, codebase, experimental]
|
||||
---
|
||||
|
||||
# @Codebase
|
||||
|
||||
Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally using `transformers.js` and stored locally in `~/.continue/index`.
|
||||
|
||||
<Info>
|
||||
|
|
|
|||
|
|
@ -15,8 +15,6 @@ keywords:
|
|||
toc_max_heading_level: 5
|
||||
---
|
||||
|
||||
# @Docs
|
||||
|
||||
The [`@Docs` context provider](../custom-providers#docs) allows you to efficiently reference documentation directly within Continue.
|
||||
|
||||
## Enabling the `@Docs` context provider
|
||||
|
|
|
|||
|
|
@ -7,15 +7,15 @@ As an example, say you are working on solving a new GitHub Issue. You type '@Iss
|
|||
|
||||

|
||||
|
||||
## Context blocks[](#context-blocks "Direct link to Context blocks")
|
||||
## Context blocks
|
||||
|
||||
You can add context providers to assistants using [`context` blocks](/hub/blocks/block-types#context). Explore available context blocks in [the hub](https://hub.continue.dev/explore/context).
|
||||
|
||||
## Built-in Context Providers[](#built-in-context-providers "Direct link to Built-in Context Providers")
|
||||
## Built-in Context Providers
|
||||
|
||||
You can add any built-in context-providers in your config file as shown below:
|
||||
|
||||
### `@File`[](#file "Direct link to file")
|
||||
### `@File`
|
||||
|
||||
Reference any file in your current workspace.
|
||||
|
||||
|
|
@ -34,7 +34,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "file" }] }
|
||||
```
|
||||
|
||||
### `@Code`[](#code "Direct link to code")
|
||||
### `@Code`
|
||||
|
||||
Reference specific functions or classes from throughout your project.
|
||||
|
||||
|
|
@ -53,7 +53,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "code" }] }
|
||||
```
|
||||
|
||||
### `@Git Diff`[](#git-diff "Direct link to git-diff")
|
||||
### `@Git Diff`
|
||||
|
||||
Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
|
||||
|
||||
|
|
@ -72,7 +72,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "diff" }] }
|
||||
```
|
||||
|
||||
### `@Current File`[](#current-file "Direct link to current-file")
|
||||
### `@Current File`
|
||||
|
||||
Reference the currently open file.
|
||||
|
||||
|
|
@ -91,7 +91,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "currentFile" }] }
|
||||
```
|
||||
|
||||
### `@Terminal`[](#terminal "Direct link to terminal")
|
||||
### `@Terminal`
|
||||
|
||||
Reference the last command you ran in your IDE's terminal and its output.
|
||||
|
||||
|
|
@ -110,7 +110,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "terminal" }] }
|
||||
```
|
||||
|
||||
### `@Docs`[](#docs "Direct link to docs")
|
||||
### `@Docs`
|
||||
|
||||
Reference the contents from any documentation site.
|
||||
|
||||
|
|
@ -133,7 +133,7 @@ Note that this will only enable the `@Docs` context provider.
|
|||
|
||||
To use it, you need to add a documentation site to your config file. See the [docs](/customization/overview#documentation-context) page for more information.
|
||||
|
||||
### `@Open`[](#open "Direct link to open")
|
||||
### `@Open`
|
||||
|
||||
Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
|
||||
|
||||
|
|
@ -152,7 +152,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "open", "params": { "onlyPinned": true } }] }
|
||||
```
|
||||
|
||||
### `@Web`[](#web "Direct link to web")
|
||||
### `@Web`
|
||||
|
||||
Reference relevant pages from across the web, automatically determined from your input.
|
||||
|
||||
|
|
@ -173,7 +173,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "web", "params": { "n": 5 } }] }
|
||||
```
|
||||
|
||||
### `@Codebase`[](#codebase "Direct link to codebase")
|
||||
### `@Codebase`
|
||||
|
||||
Reference the most relevant snippets from your codebase.
|
||||
|
||||
|
|
@ -194,7 +194,7 @@ config.json
|
|||
|
||||
Read more about indexing and retrieval [here](/customization/overview#codebase-context).
|
||||
|
||||
### `@Folder`[](#folder "Direct link to folder")
|
||||
### `@Folder`
|
||||
|
||||
Uses the same retrieval mechanism as `@Codebase`, but only on a single folder.
|
||||
|
||||
|
|
@ -213,7 +213,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "folder" }] }
|
||||
```
|
||||
|
||||
### `@Search`[](#search "Direct link to search")
|
||||
### `@Search`
|
||||
|
||||
Reference the results of codebase search, just like the results you would get from VS Code search.
|
||||
|
||||
|
|
@ -234,7 +234,7 @@ config.json
|
|||
|
||||
This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep).
|
||||
|
||||
### `@Url`[](#url "Direct link to url")
|
||||
### `@Url`
|
||||
|
||||
Reference the markdown converted contents of a given URL.
|
||||
|
||||
|
|
@ -253,7 +253,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "url" }] }
|
||||
```
|
||||
|
||||
### `@Clipboard`[](#clipboard "Direct link to clipboard")
|
||||
### `@Clipboard`
|
||||
|
||||
Reference recent clipboard items
|
||||
|
||||
|
|
@ -272,7 +272,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "clipboard" }] }
|
||||
```
|
||||
|
||||
### `@Tree`[](#tree "Direct link to tree")
|
||||
### `@Tree`
|
||||
|
||||
Reference the structure of your current workspace.
|
||||
|
||||
|
|
@ -291,7 +291,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "tree" }] }
|
||||
```
|
||||
|
||||
### `@Problems`[](#problems "Direct link to problems")
|
||||
### `@Problems`
|
||||
|
||||
Get Problems from the current file.
|
||||
|
||||
|
|
@ -310,7 +310,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "problems" }] }
|
||||
```
|
||||
|
||||
### `@Debugger`[](#debugger "Direct link to debugger")
|
||||
### `@Debugger`
|
||||
|
||||
Reference the contents of the local variables in the debugger. Currently only available in VS Code.
|
||||
|
||||
|
|
@ -331,7 +331,7 @@ config.json
|
|||
|
||||
Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
|
||||
|
||||
### `@Repository Map`[](#repository-map "Direct link to repository-map")
|
||||
### `@Repository Map`
|
||||
|
||||
Reference the outline of your codebase. By default, signatures are included along with file in the repo map.
|
||||
|
||||
|
|
@ -358,7 +358,7 @@ In the submenu that appears, you can select either `Entire codebase`, or specify
|
|||
|
||||
This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html).
|
||||
|
||||
### `@Operating System`[](#operating-system "Direct link to operating-system")
|
||||
### `@Operating System`
|
||||
|
||||
Reference the architecture and platform of your current operating system.
|
||||
|
||||
|
|
@ -377,7 +377,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "os" }] }
|
||||
```
|
||||
|
||||
### Model Context Protocol[](#model-context-protocol "Direct link to Model Context Protocol")
|
||||
### Model Context Protocol
|
||||
|
||||
The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then set up your configuration like this:
|
||||
|
||||
|
|
@ -410,7 +410,7 @@ config.json
|
|||
|
||||
You'll then be able to type "@" and see "MCP" in the context providers dropdown.
|
||||
|
||||
### `@Issue`[](#issue "Direct link to issue")
|
||||
### `@Issue`
|
||||
|
||||
Reference the conversation in a GitHub issue.
|
||||
|
||||
|
|
@ -441,7 +441,7 @@ config.json
|
|||
|
||||
Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited.
|
||||
|
||||
### `@Database`[](#database "Direct link to database")
|
||||
### `@Database`
|
||||
|
||||
Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
|
||||
|
||||
|
|
@ -504,7 +504,7 @@ Available connection types:
|
|||
- `mysql`
|
||||
- `sqlite`
|
||||
|
||||
### `@Postgres`[](#postgres "Direct link to postgres")
|
||||
### `@Postgres`
|
||||
|
||||
Reference the schema of a table, and some sample rows
|
||||
|
||||
|
|
@ -544,7 +544,7 @@ By default, the `schema` filter is set to `public`, and the `sampleRows` is set
|
|||
|
||||
[Here is a short demo.](https://github.com/continuedev/continue/pull/859)
|
||||
|
||||
### `@Google`[](#google "Direct link to google")
|
||||
### `@Google`
|
||||
|
||||
Reference the results of a Google search.
|
||||
|
||||
|
|
@ -574,7 +574,7 @@ For example, type "@Google python tutorial" if you want to search and discuss wa
|
|||
|
||||
Note: You can get an API key for free at [serper.dev](https://serper.dev).
|
||||
|
||||
### `@Gitlab Merge Request`[](#gitlab-merge-request "Direct link to gitlab-merge-request")
|
||||
### `@Gitlab Merge Request`
|
||||
|
||||
Reference an open MR for this branch on GitLab.
|
||||
|
||||
|
|
@ -595,7 +595,7 @@ config.json
|
|||
|
||||
You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope.
|
||||
|
||||
#### Using Self-Hosted GitLab[](#using-self-hosted-gitlab "Direct link to Using Self-Hosted GitLab")
|
||||
#### Using Self-Hosted GitLab
|
||||
|
||||
You can specify the domain to communicate with by setting the `domain` parameter in your configurtion. By default this is set to `gitlab.com`.
|
||||
|
||||
|
|
@ -621,11 +621,11 @@ config.json
|
|||
}
|
||||
```
|
||||
|
||||
#### Filtering Comments[](#filtering-comments "Direct link to Filtering Comments")
|
||||
#### Filtering Comments
|
||||
|
||||
If you select some code to be edited, you can have the context provider filter out comments for other files. To enable this feature, set `filterComments` to `true`.
|
||||
|
||||
### `@Jira`[](#jira "Direct link to jira")
|
||||
### `@Jira`
|
||||
|
||||
Reference the conversation in a Jira issue.
|
||||
|
||||
|
|
@ -653,7 +653,7 @@ config.json
|
|||
|
||||
Make sure to include your own [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens), or use your `email` and `token`, with token set to your password for basic authentication. If you use your own Atlassian API Token, don't configure your email.
|
||||
|
||||
#### Jira Datacenter Support[](#jira-datacenter-support "Direct link to Jira Datacenter Support")
|
||||
#### Jira Datacenter Support
|
||||
|
||||
This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property.
|
||||
|
||||
|
|
@ -672,7 +672,7 @@ config.json
|
|||
{ "contextProviders": [{ "name": "jira", "params": { "apiVersion": "2" } }] }
|
||||
```
|
||||
|
||||
#### Issue Query[](#issue-query "Direct link to Issue Query")
|
||||
#### Issue Query
|
||||
|
||||
By default, the following query will be used to find issues:
|
||||
|
||||
|
|
@ -682,11 +682,11 @@ assignee = currentUser() AND resolution = Unresolved order by updated DESC
|
|||
|
||||
You can override this query by setting the `issueQuery` parameter.
|
||||
|
||||
#### Max results[](#max-results "Direct link to Max results")
|
||||
#### Max results
|
||||
|
||||
You can set the `maxResults` parameter to limit the number of results returned. The default is `50`.
|
||||
|
||||
### `@Discord`[](#discord "Direct link to discord")
|
||||
### `@Discord`
|
||||
|
||||
Reference the messages in a Discord channel.
|
||||
|
||||
|
|
@ -721,7 +721,7 @@ config.json
|
|||
|
||||
Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels.
|
||||
|
||||
### `@HTTP`[](#http "Direct link to http")
|
||||
### `@HTTP`
|
||||
|
||||
The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
|
||||
|
||||
|
|
@ -760,7 +760,7 @@ Response
|
|||
[ { "name": "", "description": "", "content": "" }]// OR{ "name": "", "description": "", "content": ""}
|
||||
```
|
||||
|
||||
### `@Commits`[](#commits "Direct link to commits")
|
||||
### `@Commits`
|
||||
|
||||
Reference specific git commit metadata and diff or all of the recent commits.
|
||||
|
||||
|
|
@ -785,7 +785,7 @@ config.json
|
|||
|
||||
The depth is how many commits will be loaded into the submenu, defaults to 50. The LastXCommitsDepth is how many recent commits will be included, defaults to 10.
|
||||
|
||||
### `@Greptile`[](#greptile "Direct link to greptile")
|
||||
### `@Greptile`
|
||||
|
||||
Query a [Greptile](https://www.greptile.com/) index of the current repo/branch.
|
||||
|
||||
|
|
@ -811,6 +811,6 @@ config.json
|
|||
}
|
||||
```
|
||||
|
||||
### Requesting Context Providers[](#requesting-context-providers "Direct link to Requesting Context Providers")
|
||||
### Requesting Context Providers
|
||||
|
||||
Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new Context Provider.
|
||||
|
|
|
|||
|
|
@ -6,8 +6,6 @@ toc_max_heading_level: 5
|
|||
|
||||
{/* This is a work in progress and excluded by prefixing the file name with an underscore */}
|
||||
|
||||
# Apply
|
||||
|
||||
## Instant Diff Apply
|
||||
|
||||
If you have large files (exeeding the output token of your model) the edit apply will delete all lines that exceed the model window. To mitigate you can instead of applying the changes directly, ask the chat LLM to "generate a unified diff".
|
||||
|
|
|
|||
|
|
@ -4,8 +4,6 @@ description: MCP use and customization
|
|||
keywords: [tool, use, function calling, claude, automatic]
|
||||
---
|
||||
|
||||
# MCP
|
||||
|
||||
As AI systems get better, they're still held back by their training data and
|
||||
can't access real-time information or specialized tools. The [Model Context
|
||||
Protocol](https://modelcontextprotocol.io/introduction) (MCP) fixes this by
|
||||
|
|
@ -59,41 +57,7 @@ The result will be a generated file called `hn.txt` in the current working direc
|
|||
|
||||
You can set up an MCP server to search the Continue documentation directly from your agent. This is particularly useful for getting help with Continue configuration and features.
|
||||
|
||||
1. Create a folder called `.continue/mcpServers` at the top level of your workspace
|
||||
2. Add a file called `continue-docs-mcp.yaml` to this folder
|
||||
3. Write the following contents and save:
|
||||
|
||||
```yaml title=".continue/mcpServers/continue-docs-mcp.yaml"
|
||||
name: Continue Documentation MCP
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
mcpServers:
|
||||
- name: Continue Docs Search
|
||||
type: stdio
|
||||
command: npx
|
||||
args:
|
||||
- mint-mcp
|
||||
- add
|
||||
- continue-docs
|
||||
```
|
||||
|
||||
Now you can search the Continue documentation by asking questions like:
|
||||
|
||||
```
|
||||
Search for model setup instructions in the Continue docs
|
||||
```
|
||||
|
||||
```
|
||||
Find documentation about context providers
|
||||
```
|
||||
|
||||
```
|
||||
How do I configure autocomplete in Continue?
|
||||
```
|
||||
|
||||
The MCP server will search the Continue documentation and provide relevant information to help with your questions.
|
||||
|
||||
For detailed setup instructions and troubleshooting, see the [Continue MCP Reference](/reference/continue-mcp).
|
||||
For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp).
|
||||
|
||||
## Using MCP Servers
|
||||
|
||||
|
|
|
|||
|
|
@ -6,8 +6,6 @@ keywords: [slash command, custom commands, step]
|
|||
|
||||

|
||||
|
||||
## Slash commands
|
||||
|
||||
Slash commands are shortcuts that can be activated by typing '/' in a chat session (press <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains)), and selecting from the dropdown.
|
||||

|
||||
|
||||
|
|
|
|||
|
|
@ -4,8 +4,6 @@ description: "Configure Llama Stack with Continue"
|
|||
keywords: [llama, stack, local, api, inference]
|
||||
---
|
||||
|
||||
# Llama Stack
|
||||
|
||||
[Llama Stack](https://llama-stack.readthedocs.io/en/latest/index.html) is an open-source library that standardizes the core building blocks that simplify AI application development. It codifies best practices across the Llama ecosystem. More specifically, it provides
|
||||
|
||||
- **Unified API layer** for Inference, RAG, Agents, Tools, Safety, Evals, and Telemetry.
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -9,18 +9,18 @@ slug: ../xai
|
|||
|
||||
## Chat model
|
||||
|
||||
We recommend configuring **grok-2-latest** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models).
|
||||
We recommend configuring **grok-4** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models).
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Config">
|
||||
Add the [xAI Grok 2 model block](https://hub.continue.dev/xai/grok-2) on the hub.
|
||||
Add the [xAI Grok 4 model block](https://hub.continue.dev/xai/grok-4) on the hub.
|
||||
</Tab>
|
||||
<Tab title="YAML">
|
||||
```yaml title="config.yaml"
|
||||
models:
|
||||
- name: Grok 2
|
||||
- name: Grok 4
|
||||
provider: xAI
|
||||
model: grok-2-latest
|
||||
model: grok-4
|
||||
apiKey: <YOUR_XAI_API_KEY>
|
||||
```
|
||||
</Tab>
|
||||
|
|
@ -29,9 +29,9 @@ We recommend configuring **grok-2-latest** as your chat model. For information o
|
|||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Grok 2",
|
||||
"title": "Grok 4",
|
||||
"provider": "xAI",
|
||||
"model": "grok-2-latest",
|
||||
"model": "grok-4",
|
||||
"apiKey": "<YOUR_XAI_API_KEY>"
|
||||
}
|
||||
]
|
||||
|
|
|
|||
|
|
@ -3,43 +3,43 @@ title: "Overview"
|
|||
description: "Explore Continue's advanced capabilities for power users and complex development scenarios."
|
||||
---
|
||||
|
||||
## Context Providers[](#context-providers "Direct link to Context Providers")
|
||||
## Context Providers
|
||||
|
||||
Master how Continue understands your codebase with powerful context providers for code, documentation, and more.
|
||||
|
||||
[Explore Context Providers →](/customize/custom-providers)
|
||||
|
||||
## Context Integration[](#context-integration "Direct link to Context Integration")
|
||||
## Context Integration
|
||||
|
||||
Specialized context features for codebase understanding and documentation integration.
|
||||
|
||||
[Browse Context Features →](/customization/overview#codebase-context)
|
||||
|
||||
## Deep Dives[](#deep-dives "Direct link to Deep Dives")
|
||||
## Deep Dives
|
||||
|
||||
Detailed technical explanations of Continue's internal workings and advanced configuration options.
|
||||
|
||||
[Read Deep Dives →](/customization/overview#configuration)
|
||||
|
||||
## Model Providers[](#model-providers "Direct link to Model Providers")
|
||||
## Model Providers
|
||||
|
||||
Configure and optimize different AI model providers for your specific needs and infrastructure.
|
||||
|
||||
[Configure Providers →](/customization/models#openai)
|
||||
|
||||
## Model Roles[](#model-roles "Direct link to Model Roles")
|
||||
## Model Roles
|
||||
|
||||
Understand how different models can be assigned specific roles in your development workflow.
|
||||
|
||||
[Learn Model Roles →](/customize/model-roles)
|
||||
|
||||
## Reference[](#reference "Direct link to Reference")
|
||||
## Reference
|
||||
|
||||
Complete configuration reference and API documentation.
|
||||
|
||||
[View Reference →](/reference)
|
||||
|
||||
## Troubleshooting[](#troubleshooting "Direct link to Troubleshooting")
|
||||
## Troubleshooting
|
||||
|
||||
Solutions to common issues and debugging techniques.
|
||||
|
||||
|
|
|
|||
|
|
@ -2,17 +2,17 @@
|
|||
title: "Telemetry"
|
||||
---
|
||||
|
||||
## Overview[](#overview "Direct link to Overview")
|
||||
## Overview
|
||||
|
||||
The open-source Continue Extensions collect and report **anonymous** usage information to help us improve our product. This data enables us to understand user interactions and optimize the user experience effectively. You can opt out of telemetry collection at any time if you prefer not to share your usage information.
|
||||
|
||||
We utilize [Posthog](https://posthog.com/), an open-source platform for product analytics, to gather and store this data. For transparency, you can review the implementation code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx) or read our [official privacy policy](https://continue.dev/privacy).
|
||||
|
||||
## Tracking Policy[](#tracking-policy "Direct link to Tracking Policy")
|
||||
## Tracking Policy
|
||||
|
||||
All data collected by the open-source Continue extensions is anonymized and stripped of personally identifiable information (PII) before being sent to PostHog. We are committed to maintaining the privacy and security of your data.
|
||||
|
||||
## What We Track[](#what-we-track "Direct link to What We Track")
|
||||
## What We Track
|
||||
|
||||
The following usage information is collected and reported:
|
||||
|
||||
|
|
@ -22,7 +22,7 @@ The following usage information is collected and reported:
|
|||
- **System Information:** The name of your operating system (OS) and integrated development environment (IDE).
|
||||
- **Pageviews:** General pageview statistics.
|
||||
|
||||
## How to Opt Out[](#how-to-opt-out "Direct link to How to Opt Out")
|
||||
## How to Opt Out
|
||||
|
||||
You can disable anonymous telemetry by visiting the [User Settings Page](/customize/settings) and toggling "Allow Anonymous Telemetry" off.
|
||||
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
@ -258,7 +259,8 @@
|
|||
"pages": [
|
||||
"reference",
|
||||
"reference/json-reference",
|
||||
"reference/yaml-migration"
|
||||
"reference/yaml-migration",
|
||||
"reference/continue-mcp"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,19 +0,0 @@
|
|||
# Context Selection
|
||||
|
||||
Autocomplete will automatically determine context based on the current cursor position. We use the following techniques to determine what to include in the prompt:
|
||||
|
||||
## File prefix/suffix
|
||||
|
||||
We will always include the code from your file prior to and after the cursor position.
|
||||
|
||||
## Definitions from the Language Server Protocol
|
||||
|
||||
Similar to how you can use cmd/ctrl + click in your editor, we use the same tool (the LSP) to power "go to definition". For example, if you are typing out a function call, we will include the function definition. Or, if you are writing code inside of a method, we will include the type definitions for any parameters or the return type.
|
||||
|
||||
## Imported files
|
||||
|
||||
Because there are often many imports, we can't include all of them. Instead, we look for symbols around your cursor that have matching imports and use that as context.
|
||||
|
||||
## Recent files
|
||||
|
||||
We automatically consider recently opened or edited files and include snippets that are relevant to the current completion.
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue