Merge branch 'main' into nate/watsonx-v

This commit is contained in:
Nate 2025-06-03 07:50:50 -07:00
commit e6e607fd24
242 changed files with 51918 additions and 48825 deletions

View file

@ -13,4 +13,4 @@ description: Standards for writing and maintaining Continue Docs
- Include cross-references to related documentation
- Reference other docs with relative paths
- Keep paragraphs concise and scannable
- Use code blocks with appropriate language tags
- Use code blocks with appropriate language tags

View file

@ -30,6 +30,24 @@ jobs:
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci
prettier-check:
needs: install-root
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') }}
- name: Check code formatting with Prettier
run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}" --ignore-path .gitignore --ignore-path .prettierignore
install-config-yaml:
needs: install-root
runs-on: ubuntu-latest
@ -860,6 +878,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- install-root
- prettier-check
- install-core
- core-checks
- install-gui

View file

@ -15,4 +15,11 @@ gui/dist
CHANGELOG.md
**/continue_tutorial.py
**/node_modules
**/CODEOWNERS
**/CODEOWNERS
core/vendor
coverage
e2e
extensions/vscode/gui
extensions/vscode/models
extensions/intellij/src/main/resources
packages/continue-sdk

View file

@ -14,21 +14,21 @@ religion, or sexual identity and orientation.
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
- The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities

View file

@ -58,7 +58,6 @@ file
![edit](docs/static/img/edit.gif)
</div>
## Getting Started

View file

@ -1,6 +1,10 @@
const path = require('path');
const path = require("path");
process.env.CONTINUE_DEVELOPMENT = true;
process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug');
process.env.CONTINUE_GLOBAL_DIR = path.join(
process.env.PROJECT_DIR,
"extensions",
".continue-debug",
);
require('./out/index.js');
require("./out/index.js");

View file

@ -1,7 +1,13 @@
const fs = require('fs');
const path = require('path');
const fs = require("fs");
const path = require("path");
const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
const logDirPath = path.join(
__dirname,
"..",
"extensions",
".continue-debug",
"logs",
);
const logFilePath = path.join(logDirPath, "prompt.log");
// Ensure the log directory exists
@ -12,7 +18,7 @@ if (!fs.existsSync(logDirPath)) {
// Create the log file if it doesn't exist
if (!fs.existsSync(logFilePath)) {
fs.writeFileSync(logFilePath, ''); // Create an empty file synchronously
fs.writeFileSync(logFilePath, ""); // Create an empty file synchronously
console.log("Created empty log file at " + logFilePath);
}
@ -25,14 +31,16 @@ try {
// console.clear();
const stream = fs.createReadStream(logFilePath);
stream.pipe(process.stdout);
stream.on('error', (err) => {
console.error('Error reading log file:', err.message);
stream.on("error", (err) => {
console.error("Error reading log file:", err.message);
});
} catch (err) {
console.error('Error while handling file change:', err.message);
console.error("Error while handling file change:", err.message);
}
});
} catch (err) {
console.error('Error setting up file watcher:', err.message);
console.log('You may need to restart the script after the extension generates the first log entry.');
}
console.error("Error setting up file watcher:", err.message);
console.log(
"You may need to restart the script after the extension generates the first log entry.",
);
}

View file

@ -39,4 +39,4 @@ module.exports = {
TARGET_TO_RIPGREP_RELEASE,
TARGET_TO_LANCEDB,
RIPGREP_VERSION,
};
};

View file

@ -74,7 +74,6 @@ export class StreamTransformPipeline {
const timeoutValue = helper.options.modelTimeout;
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
const finalGenerator = streamWithNewLines(lineGenerator);

View file

@ -215,21 +215,47 @@ describe("lineStream", () => {
});
it("should handle unfenced code with a code block", async () => {
const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```"]);
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
});
it("should handle unfenced code with two code blocks", async () => {
const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```bash",
"ls -al",
"```",
"```bash",
"ls -al",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
"```bash",
"ls -al",
"```",
]);
});
it("should remove lines before the first valid line", async () => {
@ -242,7 +268,11 @@ describe("lineStream", () => {
});
it("should remove outer blocks", async () => {
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;","```"]);
const linesGenerator = await getLineGenerator([
"```ts",
"const x = 5;",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
@ -251,48 +281,119 @@ describe("lineStream", () => {
});
it("should leave inner blocks intact", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```"]);
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
});
it("should handle included inner ticks", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","echo ```test```","```","```"]);
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"echo ```test```",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","echo ```test```","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"echo ```test```",
"```",
]);
});
it("should leave single inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```","trailing text"]);
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"```",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
});
it("should leave double inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```","```","trailing text"]);
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"const y = 10;",
"```sh",
"echo `hello world`",
"```",
"```",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
"const y = 10;",
"```sh",
"echo `hello world`",
"```",
]);
});
it("should leave inner blocks intact but not return trailing or leading text", async () => {
const linesGenerator = await getLineGenerator(["[CODE]", "const x = 5;", "```bash","ls -al","```","[/CODE]","trailing text"]);
const linesGenerator = await getLineGenerator([
"[CODE]",
"const x = 5;",
"```bash",
"ls -al",
"```",
"[/CODE]",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
});
});

View file

@ -350,12 +350,10 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
let nestCount = 0;
for await (const line of rawLines) {
if (!seenFirstFence) {
if (shouldRemoveLineBeforeStart(line)) {
// Filter out starting ``` or START block
continue
continue;
}
// Regardless of a fence or START block start tracking the nesting level
seenFirstFence = true;

View file

@ -14,7 +14,11 @@ export class GeneratorReuseManager {
) {
this.currentGenerator?.cancel();
const listenableGen = new ListenableGenerator(gen, this.onError, abortController);
const listenableGen = new ListenableGenerator(
gen,
this.onError,
abortController,
);
listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? ""));
this.pendingGeneratorPrefix = prefix;
@ -43,7 +47,11 @@ export class GeneratorReuseManager {
if (!this.shouldReuseExistingGenerator(prefix)) {
// Create a wrapper over the current generator to fix the prompt
const abortController = new AbortController();
this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix);
this._createListenableGenerator(
abortController,
newGenerator(abortController.signal),
prefix,
);
}
// Already typed characters are those that are new in the prefix from the old generator

View file

@ -72,7 +72,8 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
};
const seedCoderFimTemplate: AutocompleteTemplate = {
template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
template:
"<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
completionOptions: {
stop: [
"<[end▁of▁sentence]>",

View file

@ -42,17 +42,18 @@ export const getSnippets = (
helper: HelperVars,
payload: SnippetPayload,
): AutocompleteSnippet[] => {
const snippets = {
"clipboard": payload.clipboardSnippets,
"recentlyVisitedRanges": payload.recentlyVisitedRangesSnippets,
"recentlyEditedRanges": payload.recentlyEditedRangeSnippets,
"diff": payload.diffSnippets,
"base": shuffleArray(filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
)),
}
clipboard: payload.clipboardSnippets,
recentlyVisitedRanges: payload.recentlyVisitedRangesSnippets,
recentlyEditedRanges: payload.recentlyEditedRangeSnippets,
diff: payload.diffSnippets,
base: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
),
),
};
// Define snippets with their priorities
const snippetConfigs: {
@ -61,53 +62,60 @@ export const getSnippets = (
defaultPriority: number;
snippets: AutocompleteSnippet[];
}[] = [
{
key: "clipboard",
enabledOrPriority: helper.options.experimental_includeClipboard,
defaultPriority: 1,
snippets: payload.clipboardSnippets,
},
{
key: "recentlyVisitedRanges",
enabledOrPriority: helper.options.experimental_includeRecentlyVisitedRanges,
defaultPriority: 2,
snippets: payload.recentlyVisitedRangesSnippets,
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
{
key: "clipboard",
enabledOrPriority: helper.options.experimental_includeClipboard,
defaultPriority: 1,
snippets: payload.clipboardSnippets,
},
{
key: "recentlyVisitedRanges",
enabledOrPriority:
helper.options.experimental_includeRecentlyVisitedRanges,
defaultPriority: 2,
snippets: payload.recentlyVisitedRangesSnippets,
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
if they are visible. We should handle them separately so that we can control their priority
and whether they should be included or not. */
},
{
key: "recentlyEditedRanges",
enabledOrPriority: helper.options.experimental_includeRecentlyEditedRanges,
defaultPriority: 3,
snippets: payload.recentlyEditedRangeSnippets,
},
{
key: "diff",
enabledOrPriority: helper.options.experimental_includeDiff,
defaultPriority: 4,
snippets: payload.diffSnippets,
// TODO: diff is commonly too large, thus anything lower in priority is not included.
},
{
key: "base",
enabledOrPriority: true,
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
snippets: shuffleArray(filterSnippetsAlreadyInCaretWindow(
},
{
key: "recentlyEditedRanges",
enabledOrPriority:
helper.options.experimental_includeRecentlyEditedRanges,
defaultPriority: 3,
snippets: payload.recentlyEditedRangeSnippets,
},
{
key: "diff",
enabledOrPriority: helper.options.experimental_includeDiff,
defaultPriority: 4,
snippets: payload.diffSnippets,
// TODO: diff is commonly too large, thus anything lower in priority is not included.
},
{
key: "base",
enabledOrPriority: true,
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
snippets: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
helper.prunedCaretWindow,
)),
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
// always not inlucded due to diff being commonly large
},
];
),
),
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
// always not inlucded due to diff being commonly large
},
];
// Create a readable order of enabled snippets
const snippetOrder = snippetConfigs
.filter(({ enabledOrPriority }) => enabledOrPriority)
.map(({ key, enabledOrPriority, defaultPriority }) => ({
key,
priority: typeof enabledOrPriority === 'number' ? enabledOrPriority : defaultPriority,
priority:
typeof enabledOrPriority === "number"
? enabledOrPriority
: defaultPriority,
}))
.sort((a, b) => a.priority - b.priority);
@ -121,15 +129,19 @@ export const getSnippets = (
// Convert configs to prioritized snippets
let prioritizedSnippets = snippetOrder
.flatMap(({ key, priority }) =>
snippets[key].map(snippet => ({ snippet, priority }))
snippets[key].map((snippet) => ({ snippet, priority })),
)
.sort((a, b) => a.priority - b.priority)
.map(({ snippet }) => snippet);
// Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
// while looking at the prompts in the Continue's output
prioritizedSnippets = prioritizedSnippets.filter((snippet) =>
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith("output:extension-output-Continue.continue"));
prioritizedSnippets = prioritizedSnippets.filter(
(snippet) =>
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith(
"output:extension-output-Continue.continue",
),
);
const finalSnippets = [];
let remainingTokenCount = getRemainingTokenCount(helper);

View file

@ -8,23 +8,23 @@ export class AutocompleteDebouncer {
// Generate a unique ID for this request
const requestId = uuidv4();
this.currentRequestId = requestId;
// Clear any existing timeout
if (this.debounceTimeout) {
clearTimeout(this.debounceTimeout);
}
// Create a new promise that resolves after the debounce delay
return new Promise<boolean>((resolve) => {
this.debounceTimeout = setTimeout(() => {
// When the timeout completes, check if this is still the most recent request
const shouldDebounce = this.currentRequestId !== requestId;
// If this is the most recent request, it shouldn't be debounced
if (!shouldDebounce) {
this.currentRequestId = undefined;
}
resolve(shouldDebounce);
}, debounceDelay);
});

View file

@ -1,65 +1,65 @@
import {
processTestCase,
type CompletionTestCase,
processTestCase,
type CompletionTestCase,
} from "./completionTestUtils";
describe("processTestCase utility", () => {
it("processes simple console.log completion", () => {
const testCase: CompletionTestCase = {
original: "console.log(|cur||till|)",
completion: "\"foo,\", bar",
};
it("processes simple console.log completion", () => {
const testCase: CompletionTestCase = {
original: "console.log(|cur||till|)",
completion: '"foo,", bar',
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: "\"foo,\", bar",
currentText: ")",
cursorPosition: "console.log(".length,
},
expectedResult: {
completionText: "\"foo,\", bar",
},
});
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: '"foo,", bar',
currentText: ")",
cursorPosition: "console.log(".length,
},
expectedResult: {
completionText: '"foo,", bar',
},
});
});
it("processes simple console.log completion with overwriting", () => {
const testCase: CompletionTestCase = {
original: "console.log(|cur|)|till|",
completion: "\"foo,\", bar);",
};
it("processes simple console.log completion with overwriting", () => {
const testCase: CompletionTestCase = {
original: "console.log(|cur|)|till|",
completion: '"foo,", bar);',
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: "\"foo,\", bar);",
currentText: ")",
cursorPosition: "console.log(".length,
},
expectedResult: {
completionText: "\"foo,\", bar);",
range: {
start: "console.log(".length,
end: "console.log()".length,
},
},
});
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: '"foo,", bar);',
currentText: ")",
cursorPosition: "console.log(".length,
},
expectedResult: {
completionText: '"foo,", bar);',
range: {
start: "console.log(".length,
end: "console.log()".length,
},
},
});
});
it("partially applying completion", () => {
const testCase: CompletionTestCase = {
original: "|cur||till|fetch(\"https://example.com\");",
completion: "await fetch(\"https://example.com\");",
appliedCompletion: "await ",
};
it("partially applying completion", () => {
const testCase: CompletionTestCase = {
original: '|cur||till|fetch("https://example.com");',
completion: 'await fetch("https://example.com");',
appliedCompletion: "await ",
};
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: "await fetch(\"https://example.com\");",
currentText: "fetch(\"https://example.com\");",
cursorPosition: 0,
},
expectedResult: {
completionText: "await ",
},
});
expect(processTestCase(testCase)).toEqual({
input: {
lastLineOfCompletionText: 'await fetch("https://example.com");',
currentText: 'fetch("https://example.com");',
cursorPosition: 0,
},
expectedResult: {
completionText: "await ",
},
});
});
});

View file

@ -1,91 +1,94 @@
export interface CompletionTestCase {
original: string; // Text with |cur| and |till| markers
completion: string; // Text to insert/overwrite
appliedCompletion?: string | null;
cursorMarker?: string;
tillMarker?: string;
original: string; // Text with |cur| and |till| markers
completion: string; // Text to insert/overwrite
appliedCompletion?: string | null;
cursorMarker?: string;
tillMarker?: string;
}
export interface ProcessedTestCase {
input: {
lastLineOfCompletionText: string;
currentText: string;
cursorPosition: number;
};
expectedResult: {
completionText: string;
range?: {
start: number;
end: number;
};
input: {
lastLineOfCompletionText: string;
currentText: string;
cursorPosition: number;
};
expectedResult: {
completionText: string;
range?: {
start: number;
end: number;
};
};
}
/**
* Transforms human-readable test case into input and expected results.
*
*
* - `original`: Your original text with |cur| marking where the cursor is before completion,
* and |till| marking where the cursor should be after accepting completion (and this is
* the end of the actual applied completion)
* - `completion`: LLM completion output
* - `appliedCompletion` (optional): part of the LLM completion output that is actually applied
* (written between |cur| and |till| in the original)
*
*
* For example, you have this line:
*
*
* console.log("<cursor here>");
*
*
* and expect it to be completed this way:
*
*
* console.log("foo: ", bar<cursor here>);
*
*
* with your completion coming from LLM being: `'foo: ", bar<cursor here>);'`
*
*
* Your input to this function should be:
* - original: `'console.log("|cur|"|till|);'`
* - completion: `'foo: ", bar);'`
* - appliedCompletion: `'foo: ", bar'`
*
*
* Output: input and expected output of {@link core/autocomplete/util/processSingleLineCompletion/processSingleLineCompletion|processSingleLineCompletion()}
*
*
*/
export function processTestCase({
original,
completion,
appliedCompletion = null,
cursorMarker = "|cur|",
tillMarker = "|till|",
original,
completion,
appliedCompletion = null,
cursorMarker = "|cur|",
tillMarker = "|till|",
}: CompletionTestCase): ProcessedTestCase {
// Validate cursor marker
if (!original.includes(cursorMarker)) {
throw new Error("Cursor marker not found in original text");
}
// Validate cursor marker
if (!original.includes(cursorMarker)) {
throw new Error("Cursor marker not found in original text");
}
const cursorPos = original.indexOf(cursorMarker);
original = original.replace(cursorMarker, "");
const cursorPos = original.indexOf(cursorMarker);
original = original.replace(cursorMarker, "");
let tillPos = original.indexOf(tillMarker);
if (tillPos < 0) {
tillPos = cursorPos;
} else {
original = original.replace(tillMarker, "")
}
let tillPos = original.indexOf(tillMarker);
if (tillPos < 0) {
tillPos = cursorPos;
} else {
original = original.replace(tillMarker, "");
}
// Calculate currentText based on what's between cursor and till marker
const currentText = original.substring(cursorPos);
// Calculate currentText based on what's between cursor and till marker
const currentText = original.substring(cursorPos);
return {
input: {
lastLineOfCompletionText: completion,
currentText,
cursorPosition: cursorPos,
},
expectedResult: {
completionText: appliedCompletion || completion,
range: cursorPos === tillPos ? undefined : {
start: cursorPos,
end: tillPos,
return {
input: {
lastLineOfCompletionText: completion,
currentText,
cursorPosition: cursorPos,
},
expectedResult: {
completionText: appliedCompletion || completion,
range:
cursorPos === tillPos
? undefined
: {
start: cursorPos,
end: tillPos,
},
},
};
}
},
};
}

View file

@ -2,96 +2,94 @@ import { processTestCase } from "./completionTestUtils";
import { processSingleLineCompletion } from "./processSingleLineCompletion";
describe("processSingleLineCompletion", () => {
it("should handle simple end of line completion", () => {
const testCase = processTestCase({
original: "console.log(|cur|",
completion: "\"Hello, world!\")",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
it("should handle simple end of line completion", () => {
const testCase = processTestCase({
original: "console.log(|cur|",
completion: '"Hello, world!")',
});
it("should handle midline insert repeating the end of line", () => {
const testCase = processTestCase({
original: "console.log(|cur|);|till|",
completion: "\"Hello, world!\");",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
expect(result).toEqual(testCase.expectedResult);
it("should handle midline insert repeating the end of line", () => {
const testCase = processTestCase({
original: "console.log(|cur|);|till|",
completion: '"Hello, world!");',
});
it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
const testCase = processTestCase({
original: "console.log(|cur|)|till|",
completion: "\"Hello, world!\");",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
expect(result).toEqual(testCase.expectedResult);
it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
const testCase = processTestCase({
original: "console.log(|cur|)|till|",
completion: '"Hello, world!");',
});
it("should handle simple midline insert", () => {
const testCase = processTestCase({
original: "console.log(|cur|)",
completion: "\"Hello, world!\"",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
expect(result).toEqual(testCase.expectedResult);
it("should handle simple midline insert", () => {
const testCase = processTestCase({
original: "console.log(|cur|)",
completion: '"Hello, world!"',
});
it("should handle complex dif with addition in the beginning", () => {
const testCase = processTestCase({
original: "console.log(|cur||till|, \"param1\", )", // TODO
completion: "\"Hello world!\", \"param1\", param1);",
appliedCompletion: "\"Hello world!\""
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
expect(result).toEqual(testCase.expectedResult);
it("should handle complex dif with addition in the beginning", () => {
const testCase = processTestCase({
original: 'console.log(|cur||till|, "param1", )', // TODO
completion: '"Hello world!", "param1", param1);',
appliedCompletion: '"Hello world!"',
});
it("should handle simple insertion even with random equality", () => {
const testCase = processTestCase({
original: "print(f\"Foobar length: |cur||till|\")",
completion: "{len(foobar)}",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition
);
expect(result).toEqual(testCase.expectedResult);
});
expect(result).toEqual(testCase.expectedResult);
it("should handle simple insertion even with random equality", () => {
const testCase = processTestCase({
original: 'print(f"Foobar length: |cur||till|")',
completion: "{len(foobar)}",
});
const result = processSingleLineCompletion(
testCase.input.lastLineOfCompletionText,
testCase.input.currentText,
testCase.input.cursorPosition,
);
expect(result).toEqual(testCase.expectedResult);
});
});

View file

@ -1,92 +1,93 @@
import * as Diff from "diff";
interface SingleLineCompletionResult {
completionText: string;
range?: {
start: number;
end: number;
};
completionText: string;
range?: {
start: number;
end: number;
};
}
interface DiffType {
count?: number;
added?: boolean;
removed?: boolean;
value: string;
count?: number;
added?: boolean;
removed?: boolean;
value: string;
}
function diffPatternMatches(
diffs: DiffType[],
pattern: DiffPartType[],
diffs: DiffType[],
pattern: DiffPartType[],
): boolean {
if (diffs.length !== pattern.length) {
return false;
if (diffs.length !== pattern.length) {
return false;
}
for (let i = 0; i < diffs.length; i++) {
const diff = diffs[i];
const diffPartType: DiffPartType =
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
if (diffPartType !== pattern[i]) {
return false;
}
}
for (let i = 0; i < diffs.length; i++) {
const diff = diffs[i];
const diffPartType: DiffPartType =
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
if (diffPartType !== pattern[i]) {
return false;
}
}
return true;
return true;
}
type DiffPartType = "+" | "-" | "=";
export function processSingleLineCompletion(
lastLineOfCompletionText: string,
currentText: string,
cursorPosition: number
lastLineOfCompletionText: string,
currentText: string,
cursorPosition: number,
): SingleLineCompletionResult | undefined {
const diffs: DiffType[] = Diff.diffWords(currentText, lastLineOfCompletionText);
const diffs: DiffType[] = Diff.diffWords(
currentText,
lastLineOfCompletionText,
);
if (diffPatternMatches(diffs, ["+"])) {
// Just insert, we're already at the end of the line
return {
completionText: lastLineOfCompletionText,
};
}
if (
diffPatternMatches(diffs, ["+", "="]) ||
diffPatternMatches(diffs, ["+", "=", "+"])
) {
// The model repeated the text after the cursor to the end of the line
return {
completionText: lastLineOfCompletionText,
range: {
start: cursorPosition,
end: currentText.length + cursorPosition,
},
};
}
if (
diffPatternMatches(diffs, ["+", "-"]) ||
diffPatternMatches(diffs, ["-", "+"])
) {
// We are midline and the model just inserted without repeating to the end of the line
return {
completionText: lastLineOfCompletionText,
};
}
// For any other diff pattern, just use the first added part if available
if (diffs[0]?.added) {
return {
completionText: diffs[0].value,
};
}
// Default case: treat as simple insertion
if (diffPatternMatches(diffs, ["+"])) {
// Just insert, we're already at the end of the line
return {
completionText: lastLineOfCompletionText,
completionText: lastLineOfCompletionText,
};
}
if (
diffPatternMatches(diffs, ["+", "="]) ||
diffPatternMatches(diffs, ["+", "=", "+"])
) {
// The model repeated the text after the cursor to the end of the line
return {
completionText: lastLineOfCompletionText,
range: {
start: cursorPosition,
end: currentText.length + cursorPosition,
},
};
}
if (
diffPatternMatches(diffs, ["+", "-"]) ||
diffPatternMatches(diffs, ["-", "+"])
) {
// We are midline and the model just inserted without repeating to the end of the line
return {
completionText: lastLineOfCompletionText,
};
}
// For any other diff pattern, just use the first added part if available
if (diffs[0]?.added) {
return {
completionText: diffs[0].value,
};
}
// Default case: treat as simple insertion
return {
completionText: lastLineOfCompletionText,
};
}

View file

@ -19,14 +19,14 @@ const GenerateTerminalCommand: SlashCommand = {
return;
}
const gen =
llm.streamComplete(`The user has made a request to run a shell command. Their description of what it should do is:
const gen = llm.streamComplete(
`The user has made a request to run a shell command. Their description of what it should do is:
"${input}"
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
new AbortController().signal
);
new AbortController().signal,
);
const lines = streamLines(gen);
let cmd = "";

View file

@ -24,7 +24,7 @@ class ContinueProxyContextProvider extends BaseContextProvider {
this.options.title || ContinueProxyContextProvider.description.title,
displayTitle:
this.options.displayTitle ||
this.options.name ||
this.options.name ||
ContinueProxyContextProvider.description.displayTitle,
description:
this.options.description ||

View file

@ -124,10 +124,10 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
let urlMatches: RegExpExecArray | null;
if (/https?.*/.test(remoteUrl)) {
const pathname = new URL(remoteUrl).pathname;
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname)
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname);
} else {
// ssh
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl)
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl);
}
const project = urlMatches?.groups?.projectPath ?? null;

View file

@ -20,10 +20,11 @@ class HttpContextProvider extends BaseContextProvider {
try {
const currentFile = await ide.getCurrentFile();
// `isLocalhost` actually also returns true for other local addresses, not just localhost
return await isLocalhost(url.hostname) ?
(await ide.getWorkspaceDirs()).find(workspaceDirectory => {
return currentFile?.path.startsWith(workspaceDirectory)
}) : undefined
return (await isLocalhost(url.hostname))
? (await ide.getWorkspaceDirs()).find((workspaceDirectory) => {
return currentFile?.path.startsWith(workspaceDirectory);
})
: undefined;
} catch (e) {
return undefined;
}
@ -44,12 +45,12 @@ class HttpContextProvider extends BaseContextProvider {
HttpContextProvider.description.renderInlineAs,
};
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const parsedUrl = new URL(this.options.url)
const parsedUrl = new URL(this.options.url);
const response = await extras.fetch(parsedUrl, {
method: "POST",
headers: {

View file

@ -25,7 +25,7 @@ class JiraIssuesContextProvider extends BaseContextProvider {
issueQuery: this.options.issueQuery,
apiVersion: this.options.apiVersion,
requestOptions: this.options.requestOptions,
maxResults: this.options.maxResults
maxResults: this.options.maxResults,
});
}

View file

@ -85,7 +85,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
}
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
return await this.ftsIndex.retrieve({
n,
text: tokens,

View file

@ -23,6 +23,14 @@ export interface ControlPlaneWorkspace {
export interface ControlPlaneModelDescription extends ModelDescription {}
export interface FreeTrialStatus {
optedInToFreeTrial: boolean;
chatCount?: number;
autocompleteCount?: number;
chatLimit: number;
autocompleteLimit: number;
}
export const TRIAL_PROXY_URL =
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
@ -159,4 +167,19 @@ export class ControlPlaneClient {
return null;
}
}
public async getFreeTrialStatus(): Promise<FreeTrialStatus | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.request("ide/free-trial-status", {
method: "GET",
});
return (await resp.json()) as FreeTrialStatus;
} catch (e) {
return null;
}
}
}

View file

@ -363,6 +363,10 @@ export class Core {
await this.messenger.request("openUrl", url);
});
on("controlPlane/getFreeTrialStatus", async (msg) => {
return this.configHandler.controlPlaneClient.getFreeTrialStatus();
});
on("mcp/reloadServer", async (msg) => {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});

View file

@ -83,10 +83,13 @@ export async function* getReplacementWithLlm(
\`\`\`
`;
const completion = await llm.streamChat([
{ role: "user", content: userPrompt },
{ role: "assistant", content: assistantPrompt },
], new AbortController().signal);
const completion = await llm.streamChat(
[
{ role: "user", content: userPrompt },
{ role: "assistant", content: assistantPrompt },
],
new AbortController().signal,
);
let lines = streamLines(completion);
lines = filterLeadingNewline(lines);

View file

@ -43,7 +43,7 @@ describe("isUnifiedDiffFormat", () => {
expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
});
it("should return true in case of empty lines", () => {
it("should return true in case of empty lines", () => {
const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
line1
@ -83,16 +83,25 @@ describe("applyUnifiedDiff", () => {
const expected = [
{ type: "same", line: "func main() {" },
{ type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" },
{ type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" },
{ type: "same", line: " fmt.Println(\" + : Addition\")" },
{ type: "same", line: " fmt.Println(\" - : Subtraction\")" },
{ type: "same", line: " fmt.Println(\" * : Multiplication\")" },
{ type: "same", line: " fmt.Println(\" / : Division\")" },
{ type: "same", line: " fmt.Println(\" ^ : Power\")" },
{ type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" },
{ type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" },
{
type: "same",
line: ' fmt.Println("Calculator started! Available operations:")',
},
{ type: "same", line: ' fmt.Println(" + : Addition")' },
{ type: "same", line: ' fmt.Println(" - : Subtraction")' },
{ type: "same", line: ' fmt.Println(" * : Multiplication")' },
{ type: "same", line: ' fmt.Println(" / : Division")' },
{ type: "same", line: ' fmt.Println(" ^ : Power")' },
{
type: "same",
line: ' fmt.Println(" √ : Square root (use only one number)")',
},
{
type: "new",
line: " fmt.Println(\" log: Logarithm (use 'log base number')\")",
},
{ type: "same", line: "}" },
{ type: "same", line: "// End of file" }
{ type: "same", line: "// End of file" },
];
expect(result).toEqual(expected);
@ -130,18 +139,18 @@ func main() {
const expected = [
{ type: "same", line: "package main" },
{ type: "same", line: "" },
{ type: "old", line: "import \"fmt\"" },
{ type: "old", line: 'import "fmt"' },
{ type: "new", line: "import (" },
{ type: "new", line: " \"fmt\"" },
{ type: "new", line: " \"time\"" },
{ type: "new", line: ' "fmt"' },
{ type: "new", line: ' "time"' },
{ type: "new", line: ")" },
{ type: "same", line: "" },
{ type: "same", line: "func main() {" },
{ type: "old", line: " fmt.Println(\"Hello\")" },
{ type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" },
{ type: "old", line: " fmt.Println(\"World\")" },
{ type: "new", line: " fmt.Println(\"Goodbye!\")" },
{ type: "same", line: "}" }
{ type: "old", line: ' fmt.Println("Hello")' },
{ type: "new", line: ' fmt.Printf("The time is: %v\\n", time.Now())' },
{ type: "old", line: ' fmt.Println("World")' },
{ type: "new", line: ' fmt.Println("Goodbye!")' },
{ type: "same", line: "}" },
];
expect(result).toEqual(expected);
@ -379,29 +388,47 @@ func TestLargeNumbers(t *testing.T) {
expect(result[0].line).toEqual("package main");
// 1st block
expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")");
expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")");
expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")");
// 2nd block
expect(result[56]).toEqual({type: "same", line: "\t}"});
expect(result[57]).toEqual({type: "new", line: "\t"});
expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"});
expect(result[73]).toEqual({type: "new", line: ""});
expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"});
// 3rd block
expect(result[140]).toEqual({type: "same", line: "}"});
expect(result[141]).toEqual({type: "new", line: ""});
expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"});
expect(result[153]).toEqual({type: "new", line: "\t}"});
expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"});
});
expect(result[18].line).toEqual(
'\tfmt.Println(" √ : Square root (use only one number)")',
);
expect(result[19].line).toEqual(
" fmt.Println(\" log: Logarithm (use 'log base number')\")",
);
expect(result[20].line).toEqual(
' fmt.Println(" Base must be > 0 and != 1, number must be > 0")',
);
// 2nd block
expect(result[56]).toEqual({ type: "same", line: "\t}" });
expect(result[57]).toEqual({ type: "new", line: "\t" });
expect(result[58]).toEqual({
type: "new",
line: "\t// Handle logarithmic operations",
});
expect(result[73]).toEqual({ type: "new", line: "" });
expect(result[74]).toEqual({
type: "same",
line: "\tif len(parts) != 3 {",
});
// 3rd block
expect(result[140]).toEqual({ type: "same", line: "}" });
expect(result[141]).toEqual({ type: "new", line: "" });
expect(result[142]).toEqual({
type: "new",
line: "func TestLogarithmicCases(t *testing.T) {",
});
expect(result[153]).toEqual({ type: "new", line: "\t}" });
expect(result[154]).toEqual({
type: "same",
line: "func TestSpecialCases(t *testing.T) {",
});
});
it("should throw error when hunk cannot be matched to source", () => {
const sourceCode = `line1
it("should throw error when hunk cannot be matched to source", () => {
const sourceCode = `line1
line2
line3`;
const diffText = `--- a.txt
const diffText = `--- a.txt
+++ b.txt
@@ -1,3 +1,4 @@
missing1
@ -409,7 +436,8 @@ missing1
+newline2
missing3`;
expect(() => applyUnifiedDiff(sourceCode, diffText))
.toThrow("Hunk could not be applied cleanly to source code.");
});
expect(() => applyUnifiedDiff(sourceCode, diffText)).toThrow(
"Hunk could not be applied cleanly to source code.",
);
});
});

View file

@ -8,7 +8,9 @@ import { DiffLine } from "../../index";
export function isUnifiedDiffFormat(diff: string): boolean {
const lines = diff.trim().split("\n");
if (lines.length < 3) {return false;}
if (lines.length < 3) {
return false;
}
let hasHunkHeader = false;
let hasValidContent = false;
@ -35,10 +37,13 @@ function extractBeforeLines(hunkLines: string[]): string[] {
/**
* Applies a unified diff to source code and returns an array of DiffLine objects.
* Each DiffLine contains a type ("same", "new", or "old") and the line content.
*
*
* @throws Error if the diff cannot be cleanly applied to the source
*/
export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] {
export function applyUnifiedDiff(
sourceCode: string,
unifiedDiffText: string,
): DiffLine[] {
const sourceLines = sourceCode.split(/\r?\n/);
const hunks = parseUnifiedDiff(unifiedDiffText);
const diffResult: DiffLine[] = [];
@ -46,7 +51,11 @@ export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): D
for (const hunk of hunks) {
const hunkBeforeLines = extractBeforeLines(hunk.lines);
const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos);
const hunkStart = findHunkInSource(
sourceLines,
hunkBeforeLines,
currentPos,
);
if (hunkStart === -1) {
// All hunks must be found in the source code. If not, throw an error.
throw new Error("Hunk could not be applied cleanly to source code.");
@ -124,8 +133,16 @@ function parseUnifiedDiff(diffText: string): Hunk[] {
*
* Returns the index in sourceLines where the block begins, or -1 if no match is found.
*/
function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number {
for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) {
function findHunkInSource(
sourceLines: string[],
hunkBeforeLines: string[],
startIndex: number,
): number {
for (
let i = startIndex;
i <= sourceLines.length - hunkBeforeLines.length;
i++
) {
let match = true;
for (let j = 0; j < hunkBeforeLines.length; j++) {
const sl = sourceLines[i + j];

View file

@ -14,12 +14,14 @@ export async function* basicChunker(
let startLine = 0;
let currLine = 0;
const lineTokens = await Promise.all(contents.split("\n").map(async l => {
return {
line: l,
tokenCount: await countTokensAsync(l),
};
}));
const lineTokens = await Promise.all(
contents.split("\n").map(async (l) => {
return {
line: l,
tokenCount: await countTokensAsync(l),
};
}),
);
for (const lt of lineTokens) {
if (chunkTokens + lt.tokenCount > maxChunkSize - 5) {

View file

@ -30,7 +30,7 @@ describe.skip("codeChunker", () => {
test("should capture small class and function from large python file", async () => {
const extraLine = "# This is a comment";
const myClass = "class MyClass:\n def __init__(self):\n pass";
const myFunction = "def my_function():\n return \"Hello, World!\"";
const myFunction = 'def my_function():\n return "Hello, World!"';
const file =
Array(100).fill(extraLine).join("\n") +
@ -67,7 +67,7 @@ describe.skip("codeChunker", () => {
chunks[0].startsWith("class MyClass:\n def method1():\n ..."),
).toBe(true);
// The extra spaces seem to be a bug with tree-sitter-python
expect(chunks).toContain("def method1():\n return \"Hello, 1!\"");
expect(chunks).toContain("def method20():\n return \"Hello, 20!\"");
expect(chunks).toContain('def method1():\n return "Hello, 1!"');
expect(chunks).toContain('def method20():\n return "Hello, 20!"');
});
});

View file

@ -480,5 +480,5 @@ export {
pruneLinesFromTop,
pruneRawPromptFromTop,
pruneStringFromBottom,
pruneStringFromTop
pruneStringFromTop,
};

View file

@ -1,11 +1,20 @@
export declare class LlamaTokenizer {
vocabById: string[];
vocabByString: Map<string, number>;
merges: Map<string, number>;
constructor(vocab_base64?: string, merges_binary?: string);
encode(prompt: string, add_bos_token?: boolean, add_preceding_space?: boolean, log_performance?: boolean): number[];
decode(tokenIds: number[], add_bos_token?: boolean, add_preceding_space?: boolean): string;
runTests(tests?: (tokenizer: LlamaTokenizer) => boolean): void
vocabById: string[];
vocabByString: Map<string, number>;
merges: Map<string, number>;
constructor(vocab_base64?: string, merges_binary?: string);
encode(
prompt: string,
add_bos_token?: boolean,
add_preceding_space?: boolean,
log_performance?: boolean,
): number[];
decode(
tokenIds: number[],
add_bos_token?: boolean,
add_preceding_space?: boolean,
): string;
runTests(tests?: (tokenizer: LlamaTokenizer) => boolean): void;
}
declare const llamaTokenizer: LlamaTokenizer;
export default llamaTokenizer;
export default llamaTokenizer;

File diff suppressed because one or more lines are too long

View file

@ -1,7 +1,12 @@
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
import Bedrock from "./Bedrock.js";
import { ChatMessage, Chunk, CompletionOptions, UserChatMessage } from "../../index.js";
import {
ChatMessage,
Chunk,
CompletionOptions,
UserChatMessage,
} from "../../index.js";
// Mock AWS SDK
jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
@ -34,7 +39,7 @@ class TestBedrock extends Bedrock {
public async *streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: TestCompletionOptions
options: TestCompletionOptions,
): AsyncGenerator<ChatMessage> {
if (options.mockError) {
throw new Error(options.mockError);
@ -44,14 +49,16 @@ class TestBedrock extends Bedrock {
yield {
role: "assistant",
content: "",
toolCalls: [{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg1":"value1"}'
}
}],
toolCalls: [
{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg1":"value1"}',
},
},
],
};
return;
}
@ -97,7 +104,9 @@ describe("Bedrock", () => {
expect(bedrock.region).toBe("us-east-1");
expect(bedrock.profile).toBe("bedrock");
expect(bedrock.apiBase).toBe("https://bedrock-runtime.us-east-1.amazonaws.com");
expect(bedrock.apiBase).toBe(
"https://bedrock-runtime.us-east-1.amazonaws.com",
);
});
it("should use custom options when provided", () => {
@ -131,14 +140,20 @@ describe("Bedrock", () => {
});
it("should handle text streaming correctly", async () => {
const messages: ChatMessage[] = [{
role: "user",
content: "Hi"
} as UserChatMessage];
const messages: ChatMessage[] = [
{
role: "user",
content: "Hi",
} as UserChatMessage,
];
const results = [];
for await (const message of bedrock.streamChat(messages, mockAbortSignal, defaultOptions)) {
for await (const message of bedrock.streamChat(
messages,
mockAbortSignal,
defaultOptions,
)) {
results.push(message);
}
@ -149,18 +164,24 @@ describe("Bedrock", () => {
});
it("should handle tool use streaming correctly", async () => {
const messages: ChatMessage[] = [{
role: "user",
content: "Use a tool"
} as UserChatMessage];
const messages: ChatMessage[] = [
{
role: "user",
content: "Use a tool",
} as UserChatMessage,
];
const results = [];
const options: TestCompletionOptions = {
...defaultOptions,
mockToolUse: true
mockToolUse: true,
};
for await (const message of bedrock.streamChat(messages, mockAbortSignal, options)) {
for await (const message of bedrock.streamChat(
messages,
mockAbortSignal,
options,
)) {
results.push(message);
}
@ -168,31 +189,39 @@ describe("Bedrock", () => {
{
role: "assistant",
content: "",
toolCalls: [{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg1":"value1"}'
}
}],
toolCalls: [
{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg1":"value1"}',
},
},
],
},
]);
});
it("should handle API errors", async () => {
const messages: ChatMessage[] = [{
role: "user",
content: "Hi"
} as UserChatMessage];
const messages: ChatMessage[] = [
{
role: "user",
content: "Hi",
} as UserChatMessage,
];
const options: TestCompletionOptions = {
...defaultOptions,
mockError: "API Error"
mockError: "API Error",
};
await expect(async () => {
for await (const _ of bedrock.streamChat(messages, mockAbortSignal, options)) {
for await (const _ of bedrock.streamChat(
messages,
mockAbortSignal,
options,
)) {
// consume generator
}
}).rejects.toThrow("API Error");
@ -239,7 +268,7 @@ describe("Bedrock", () => {
filepath: "file1",
index: 0,
startLine: 1,
endLine: 1
endLine: 1,
},
{
content: "doc2",
@ -247,8 +276,8 @@ describe("Bedrock", () => {
filepath: "file2",
index: 1,
startLine: 1,
endLine: 1
}
endLine: 1,
},
];
const result = await bedrock.rerank("query", chunks);
@ -262,16 +291,18 @@ describe("Bedrock", () => {
filepath: "file1",
index: 0,
startLine: 1,
endLine: 1
endLine: 1,
};
await expect(
bedrock.rerank("error", [chunk])
).rejects.toThrow("Reranking Error");
await expect(bedrock.rerank("error", [chunk])).rejects.toThrow(
"Reranking Error",
);
});
it("should throw error for empty input", async () => {
await expect(bedrock.rerank("", [])).rejects.toThrow("Query and chunks must not be empty");
await expect(bedrock.rerank("", [])).rejects.toThrow(
"Query and chunks must not be empty",
);
});
});
@ -289,7 +320,7 @@ describe("Bedrock", () => {
it("should convert text messages correctly", () => {
const message: ChatMessage = {
role: "user",
content: "Hello"
content: "Hello",
} as UserChatMessage;
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
@ -307,12 +338,14 @@ describe("Bedrock", () => {
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [{
toolResult: {
toolUseId: "tool-1",
content: [{ text: "Tool result" }],
content: [
{
toolResult: {
toolUseId: "tool-1",
content: [{ text: "Tool result" }],
},
},
}],
],
});
});
@ -320,25 +353,29 @@ describe("Bedrock", () => {
const message: ChatMessage = {
role: "assistant",
content: "",
toolCalls: [{
id: "tool-1",
type: "function" as const,
function: {
name: "test_tool",
arguments: '{"arg":"value"}',
toolCalls: [
{
id: "tool-1",
type: "function" as const,
function: {
name: "test_tool",
arguments: '{"arg":"value"}',
},
},
}],
],
};
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "assistant",
content: [{
toolUse: {
toolUseId: "tool-1",
name: "test_tool",
input: { arg: "value" },
content: [
{
toolUse: {
toolUseId: "tool-1",
name: "test_tool",
input: { arg: "value" },
},
},
}],
],
});
});

View file

@ -292,9 +292,12 @@ class Bedrock extends BaseLLM {
const convertedMessages = this._convertMessages(messages);
const shouldCacheSystemMessage =
!!systemMessage && this.cacheBehavior?.cacheSystemMessage || this.completionOptions.promptCaching;
(!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
this.completionOptions.promptCaching;
const enablePromptCaching =
shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation || this.completionOptions.promptCaching;
shouldCacheSystemMessage ||
this.cacheBehavior?.cacheConversation ||
this.completionOptions.promptCaching;
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
// Add header for prompt caching
@ -306,21 +309,24 @@ class Bedrock extends BaseLLM {
}
const supportsTools =
(this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
(this.capabilities?.tools ||
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
false;
let toolConfig = supportsTools && options.tools
? {
tools: options.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
} as ToolConfiguration
: undefined;
let toolConfig =
supportsTools && options.tools
? ({
tools: options.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
} as ToolConfiguration)
: undefined;
if (toolConfig?.tools && shouldCacheToolsConfig) {
toolConfig.tools.push({ cachePoint: { type: "default" } });

View file

@ -1,6 +1,6 @@
import {
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";

View file

@ -12,7 +12,7 @@ class Cerebras extends OpenAI {
private static modelConversion: { [key: string]: string } = {
"llama3.1-8b": "llama3.1-8b",
"llama3.1-70b": "llama3.1-70b",
"llama-4-scout-17b-16e-instruct": "llama-4-scout-17b-16e-instruct"
"llama-4-scout-17b-16e-instruct": "llama-4-scout-17b-16e-instruct",
};
protected _convertModelName(model: string): string {
return Cerebras.modelConversion[model] ?? model;

View file

@ -38,11 +38,11 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (this.apiKey) {
headers["Authorization"] = `Bearer ${this.apiKey}`;
}
const resp = await this.fetch(new URL("embed", this.apiBase), {
method: "POST",
body: JSON.stringify({

View file

@ -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",
@ -30,7 +30,12 @@ class NCompass extends OpenAI {
}
protected _getHeaders() {
const headers = super._getHeaders() as { "Content-Type": string; Authorization: string; "api-key": string; Accept?: string };
const headers = super._getHeaders() as {
"Content-Type": string;
Authorization: string;
"api-key": string;
Accept?: string;
};
headers["Accept"] = "text/event-stream";
return headers;
}
@ -56,7 +61,6 @@ class NCompass extends OpenAI {
const data = (await resp.json()) as any;
return data.data.map((result: { embedding: number[] }) => result.embedding);
}
}
export default NCompass;

View file

@ -10,7 +10,7 @@ class Novita extends OpenAI {
private static MODEL_IDS: { [name: string]: string } = {
"deepseek-r1": "deepseek/deepseek-r1",
"deepseek_v3": "deepseek/deepseek_v3",
deepseek_v3: "deepseek/deepseek_v3",
"llama3-8b": "meta-llama/llama-3-8b-instruct",
"llama3-70b": "meta-llama/llama-3-70b-instruct",
"llama3.1-8b": "meta-llama/llama-3.1-8b-instruct",

View file

@ -20,20 +20,23 @@ export class OVHcloud extends OpenAI {
"mistral-7b": "Mistral-7B-Instruct-v0.3",
"mistral-8x7b": "Mixtral-8x7B-Instruct-v0.1",
"mistral-nemo": "Mistral-Nemo-Instruct-2407",
"DeepSeek-R1-Distill-Llama-70B": "DeepSeek-R1-Distill-Llama-70B"
"DeepSeek-R1-Distill-Llama-70B": "DeepSeek-R1-Distill-Llama-70B",
};
protected _convertModelName(model: string) {
return OVHcloud.MODEL_IDS[model] || this.model;
}
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
protected _convertArgs(
options: CompletionOptions,
messages: ChatMessage[],
): ChatCompletionCreateParams {
const modifiedOptions = {
...options,
model: this._convertModelName(options.model)
model: this._convertModelName(options.model),
};
return super._convertArgs(modifiedOptions, messages);
}
}
export default OVHcloud;
export default OVHcloud;

View file

@ -1,7 +1,7 @@
import {
InvokeEndpointCommand,
InvokeEndpointWithResponseStreamCommand,
SageMakerRuntimeClient,
InvokeEndpointCommand,
InvokeEndpointWithResponseStreamCommand,
SageMakerRuntimeClient,
} from "@aws-sdk/client-sagemaker-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";

View file

@ -3,7 +3,6 @@ import OpenAI from "./OpenAI";
import { LLMOptions, CompletionOptions, ChatMessage } from "../../index.js";
import { ChatCompletionCreateParams } from "openai/resources/index";
class Scaleway extends OpenAI {
static providerName = "scaleway";
static defaultOptions: Partial<LLMOptions> = {
@ -17,17 +16,20 @@ class Scaleway extends OpenAI {
"llama3.1-70b": "llama-3.1-70b-instruct",
"mistral-nemo": "mistral-nemo-instruct-2407",
"qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct",
"pixtral": "pixtral-12b-2409",
pixtral: "pixtral-12b-2409",
};
protected _convertModelName(model: string) {
return Scaleway.MODEL_IDS[model] || this.model;
}
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
protected _convertArgs(
options: CompletionOptions,
messages: ChatMessage[],
): ChatCompletionCreateParams {
// Convert model name in the options before passing to parent
const modifiedOptions = {
...options,
model: this._convertModelName(options.model)
model: this._convertModelName(options.model),
};
return super._convertArgs(modifiedOptions, messages);
}

View file

@ -9,14 +9,22 @@ class Venice extends OpenAI {
apiBase: "https://api.venice.ai/api/v1",
};
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
const finalOptions = super._convertArgs(options, messages) as ChatCompletionCreateParams & { venice_parameters?: any };
if ("venice_parameters" in options && typeof options.venice_parameters === "object") {
protected _convertArgs(
options: CompletionOptions,
messages: ChatMessage[],
): ChatCompletionCreateParams {
const finalOptions = super._convertArgs(
options,
messages,
) as ChatCompletionCreateParams & { venice_parameters?: any };
if (
"venice_parameters" in options &&
typeof options.venice_parameters === "object"
) {
finalOptions.venice_parameters = { ...options.venice_parameters };
}
return finalOptions;
}
}
export default Venice;
export default Venice;

View file

@ -1,6 +1,9 @@
/* eslint-disable max-lines-per-function */
import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
import { getSystemMessageWithRules, shouldApplyRule } from "./getSystemMessageWithRules";
import {
getSystemMessageWithRules,
shouldApplyRule,
} from "./getSystemMessageWithRules";
describe("getSystemMessageWithRules", () => {
const baseSystemMessage = "Base system message";
@ -450,7 +453,8 @@ describe("getSystemMessageWithRules", () => {
it("should include rules with alwaysApply: false when globs match", () => {
const userMessage: UserChatMessage = {
role: "user",
content: "```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
content:
"```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
};
const result = getSystemMessageWithRules({
@ -701,14 +705,18 @@ describe("shouldApplyRule", () => {
it("should return true when alwaysApply is true, regardless of file paths", () => {
expect(shouldApplyRule(ruleAlwaysApplyTrue, [])).toBe(true);
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["src/main.js"])).toBe(true);
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(true);
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(
true,
);
});
it("should use glob matching when alwaysApply is false", () => {
// Should apply when globs match
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["src/main.ts"])).toBe(true);
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(true);
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(
true,
);
// Should not apply when globs don't match
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["script.py"])).toBe(false);
expect(shouldApplyRule(ruleAlwaysApplyFalse, [])).toBe(false);
@ -716,7 +724,9 @@ describe("shouldApplyRule", () => {
it("should return false when alwaysApply is false and no globs specified", () => {
expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, [])).toBe(false);
expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"])).toBe(false);
expect(
shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"]),
).toBe(false);
});
});
@ -724,7 +734,9 @@ describe("shouldApplyRule", () => {
it("should return true for rules without globs regardless of file paths", () => {
expect(shouldApplyRule(ruleWithoutGlobs, [])).toBe(true);
expect(shouldApplyRule(ruleWithoutGlobs, ["src/main.js"])).toBe(true);
expect(shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"])).toBe(true);
expect(
shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"]),
).toBe(true);
});
it("should return false for rules with globs when no file paths are provided", () => {
@ -734,12 +746,16 @@ describe("shouldApplyRule", () => {
it("should return true for rules with globs when matching file paths are provided", () => {
expect(shouldApplyRule(ruleWithGlobs, ["Component.tsx"])).toBe(true);
expect(shouldApplyRule(ruleWithGlobs, ["src/main.ts"])).toBe(true);
expect(shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"])).toBe(true);
expect(
shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"]),
).toBe(true);
});
it("should return false for rules with globs when no matching file paths are provided", () => {
expect(shouldApplyRule(ruleWithGlobs, ["utils.py"])).toBe(false);
expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(false);
expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(
false,
);
});
});
@ -760,19 +776,39 @@ describe("shouldApplyRule", () => {
it("should handle array of glob patterns", () => {
expect(shouldApplyRule(ruleWithArrayGlobs, ["src/main.ts"])).toBe(true);
expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(true);
expect(shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"])).toBe(false);
expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(
true,
);
expect(
shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"]),
).toBe(false);
});
it("should handle string glob patterns", () => {
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.py"])).toBe(true);
expect(shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"])).toBe(true);
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(false);
expect(
shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"]),
).toBe(true);
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(
false,
);
});
it("should return true if any file path matches when multiple paths provided", () => {
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js", "models.py", "config.json"])).toBe(true);
expect(shouldApplyRule(ruleWithGlobs, ["utils.py", "Component.tsx", "script.rb"])).toBe(true);
expect(
shouldApplyRule(ruleWithSpecificPattern, [
"utils.js",
"models.py",
"config.json",
]),
).toBe(true);
expect(
shouldApplyRule(ruleWithGlobs, [
"utils.py",
"Component.tsx",
"script.rb",
]),
).toBe(true);
});
});
@ -784,7 +820,7 @@ describe("shouldApplyRule", () => {
globs: [],
source: "rules-block",
};
// Empty array should be treated as "no globs" (truthy check fails)
expect(shouldApplyRule(ruleWithEmptyGlobs, ["any-file.js"])).toBe(false);
});
@ -796,7 +832,7 @@ describe("shouldApplyRule", () => {
globs: undefined,
source: "rules-block",
};
expect(shouldApplyRule(ruleUndefinedGlobs, ["any-file.js"])).toBe(true);
expect(shouldApplyRule(ruleUndefinedGlobs, [])).toBe(true);
});

View file

@ -95,11 +95,11 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string {
// Llama2 template with added \n to prevent Codestral from continuing user message
function codestralTemplateMessages(msgs: ChatMessage[]): string {
let template = llama2TemplateMessages(msgs);
if (template.length === 0) {
return template;
}
return template + "\n";
let template = llama2TemplateMessages(msgs);
if (template.length === 0) {
return template;
}
return template + "\n";
}
function anthropicTemplateMessages(messages: ChatMessage[]): string {

View file

@ -1,13 +1,13 @@
import { getSecureID } from '../getSecureID';
import { getSecureID } from "../getSecureID";
// Mock the crypto.randomUUID function
const mockRandomUUID = jest.fn();
global.crypto = {
...global.crypto,
randomUUID: mockRandomUUID
randomUUID: mockRandomUUID,
};
describe('getSecureID', () => {
describe("getSecureID", () => {
beforeEach(() => {
// Reset the static property before each test
(getSecureID as any).uuid = undefined;
@ -15,16 +15,16 @@ describe('getSecureID', () => {
// Reset the mock implementation
mockRandomUUID.mockReset();
// Setup a mock implementation that returns a fixed value for testing
mockRandomUUID.mockReturnValue('test-uuid-1234');
mockRandomUUID.mockReturnValue("test-uuid-1234");
});
test('should generate a UUID on first call', () => {
test("should generate a UUID on first call", () => {
const result = getSecureID();
expect(mockRandomUUID).toHaveBeenCalledTimes(1);
expect(result).toBe('<!-- SID: test-uuid-1234 -->');
expect(result).toBe("<!-- SID: test-uuid-1234 -->");
});
test('should reuse the same UUID on subsequent calls', () => {
test("should reuse the same UUID on subsequent calls", () => {
const firstResult = getSecureID();
const secondResult = getSecureID();
@ -33,17 +33,17 @@ describe('getSecureID', () => {
// Both results should be identical
expect(firstResult).toBe(secondResult);
expect(firstResult).toBe('<!-- SID: test-uuid-1234 -->');
expect(firstResult).toBe("<!-- SID: test-uuid-1234 -->");
});
test('should maintain the same UUID across different test cases if not reset', () => {
test("should maintain the same UUID across different test cases if not reset", () => {
// Don't reset the UUID here to test persistence
(getSecureID as any).uuid = 'persistent-uuid';
(getSecureID as any).uuid = "persistent-uuid";
const result = getSecureID();
// No new UUID should be generated
expect(mockRandomUUID).not.toHaveBeenCalled();
expect(result).toBe('<!-- SID: persistent-uuid -->');
expect(result).toBe("<!-- SID: persistent-uuid -->");
});
});
});

View file

@ -17,7 +17,7 @@ describe("extractPathsFromCodeBlocks", () => {
});
it("should handle multiple code blocks with different formats", () => {
const content =
const content =
"```typescript src/main.ts\nconst x = 1;\n```\n" +
"```test.js\nclass Calculator { }\n```\n" +
"```js utils.js (19-25)\nfunction test() {}\n```";
@ -32,4 +32,4 @@ describe("extractPathsFromCodeBlocks", () => {
const content = "```typescript\nconst x = 1;\n```";
expect(extractPathsFromCodeBlocks(content)).toEqual([]);
});
});
});

View file

@ -1,5 +1,4 @@
import { ConfigHandler } from "../config/ConfigHandler.js";
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
import { IDE, ILLM } from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
@ -18,7 +17,10 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce
import { AutocompleteLoggingService } from "../autocomplete/util/AutocompleteLoggingService.js";
import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
import { HelperVars } from "../autocomplete/util/HelperVars.js";
import { AutocompleteInput, AutocompleteOutcome } from "../autocomplete/util/types.js";
import {
AutocompleteInput,
AutocompleteOutcome,
} from "../autocomplete/util/types.js";
const autocompleteCache = AutocompleteLruCache.get();
@ -75,12 +77,14 @@ export class NextEditProvider {
if (llm instanceof OpenAI) {
llm.useLegacyCompletionsEndpoint = true;
} else if (
llm.providerName === "free-trial" &&
llm.model !== TRIAL_FIM_MODEL
) {
llm.model = TRIAL_FIM_MODEL;
}
// TODO: Resolve import error with TRIAL_FIM_MODEL
// else if (
// llm.providerName === "free-trial" &&
// llm.model !== TRIAL_FIM_MODEL
// ) {
// llm.model = TRIAL_FIM_MODEL;
// }
return llm;
}
@ -224,11 +228,11 @@ export class NextEditProvider {
const processedCompletion = helper.options.transform
? postprocessCompletion({
completion,
prefix: helper.prunedPrefix,
suffix: helper.prunedSuffix,
llm,
})
completion,
prefix: helper.prunedPrefix,
suffix: helper.prunedSuffix,
llm,
})
: completion;
completion = processedCompletion;

View file

@ -34,6 +34,7 @@ import {
} from "../";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
import { FreeTrialStatus } from "../control-plane/client";
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
@ -198,6 +199,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
"controlPlane/getFreeTrialStatus": [undefined, FreeTrialStatus | null];
isItemTooBig: [{ item: ContextItemWithId }, boolean];
didChangeControlPlaneSessionInfo: [
{ sessionInfo: ControlPlaneSessionInfo | undefined },

View file

@ -1,7 +1,7 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import os from 'os';
import os from "os";
/**
* Get the preferred shell for the current platform
@ -10,17 +10,17 @@ import os from 'os';
export function getPreferredShell(): string {
const platform = os.platform();
if (platform === 'win32') {
return process.env.COMSPEC || 'cmd.exe';
} else if (platform === 'darwin') {
return process.env.SHELL || '/bin/zsh';
if (platform === "win32") {
return process.env.COMSPEC || "cmd.exe";
} else if (platform === "darwin") {
return process.env.SHELL || "/bin/zsh";
} else {
// Linux and other Unix-like systems
return process.env.SHELL || '/bin/bash';
return process.env.SHELL || "/bin/bash";
}
}
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`;
export const runTerminalCommandTool: Tool = {
type: "function",
@ -32,28 +32,27 @@ export const runTerminalCommandTool: Tool = {
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.RunTerminalCommand,
description:
`Run a terminal command in the current directory.\
description: `Run a terminal command in the current directory.\
The shell is not stateful and will not remember any previous commands.\
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
Do NOT perform actions requiring special/admin privileges.\
${PLATFORM_INFO}`,
parameters: {
type: "object",
required: ["command"],
properties: {
command: {
type: "string",
description:
"The command to run. This will be passed directly into the IDE shell.",
},
waitForCompletion: {
type: "boolean",
description:
"Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.",
},
parameters: {
type: "object",
required: ["command"],
properties: {
command: {
type: "string",
description:
"The command to run. This will be passed directly into the IDE shell.",
},
waitForCompletion: {
type: "boolean",
description:
"Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.",
},
},
},
},
};

View file

@ -17,26 +17,31 @@ describe("runTerminalCommandImpl", () => {
const mockGetWorkspaceDirs = jest.fn();
const mockOnPartialOutput = jest.fn();
const mockRunCommand = jest.fn();
// Use a simple approach to ensure background processes are terminated
let testPid: number | null = null;
// Create a temp directory for our tests
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'terminal-command-test-'));
const tempDir = fs.mkdtempSync(
path.join(os.tmpdir(), "terminal-command-test-"),
);
beforeEach(() => {
jest.resetAllMocks();
// Setup backgrounded processes handling - don't mock, just make sure it's empty
// Get any processes that might be already tracked and clear them
const processMap = (processBackgroundStates as any).processTerminalBackgroundStates;
if (processMap && typeof processMap.clear === 'function') {
const processMap = (processBackgroundStates as any)
.processTerminalBackgroundStates;
if (processMap && typeof processMap.clear === "function") {
processMap.clear();
}
// Setup IDE mocks
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));
mockGetWorkspaceDirs.mockReturnValue(Promise.resolve([`file://${tempDir}`]));
mockGetWorkspaceDirs.mockReturnValue(
Promise.resolve([`file://${tempDir}`]),
);
});
afterEach(async () => {
@ -44,9 +49,11 @@ describe("runTerminalCommandImpl", () => {
if (testPid !== null) {
try {
// Platform-independent way to kill a process
if (process.platform === 'win32') {
await new Promise(resolve => {
childProcess.exec(`taskkill /F /PID ${testPid}`, () => resolve(null));
if (process.platform === "win32") {
await new Promise((resolve) => {
childProcess.exec(`taskkill /F /PID ${testPid}`, () =>
resolve(null),
);
});
} else {
process.kill(testPid);
@ -57,20 +64,24 @@ describe("runTerminalCommandImpl", () => {
testPid = null;
}
});
afterAll(() => {
// Clean up the temp directory after tests
fs.rmSync(tempDir, { recursive: true, force: true });
});
// Helper function to create a ToolExtras object
const createMockExtras = (overrides: Partial<{
onPartialOutput?: jest.Mock;
remoteName?: string;
}> = {}): ToolExtras => {
const createMockExtras = (
overrides: Partial<{
onPartialOutput?: jest.Mock;
remoteName?: string;
}> = {},
): ToolExtras => {
// Update IDE info if remoteName is provided
if (overrides.remoteName) {
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: overrides.remoteName }));
mockGetIdeInfo.mockReturnValue(
Promise.resolve({ remoteName: overrides.remoteName }),
);
}
// Create a minimally compliant IDE mock
@ -97,7 +108,7 @@ describe("runTerminalCommandImpl", () => {
llm: {} as any,
fetch: {} as any,
tool: {} as any,
toolCallId: "test-tool-call"
toolCallId: "test-tool-call",
} as ToolExtras;
// Apply overrides
@ -115,7 +126,7 @@ describe("runTerminalCommandImpl", () => {
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
// Verify real command output
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
@ -134,27 +145,27 @@ describe("runTerminalCommandImpl", () => {
console.error('error output');
}, 50);
"`;
const args = { command, waitForCompletion: true };
const mockOutputFn = jest.fn();
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
// Execute the command with streaming
const result = await runTerminalCommandImpl(args, extras);
// Verify onPartialOutput was called with increasing content
expect(mockOutputFn).toHaveBeenCalled();
// Verify final result has all output
expect(result[0].content).toContain('first output');
expect(result[0].content).toContain('second output');
expect(result[0].content).toContain('error output');
expect(result[0].content).toContain("first output");
expect(result[0].content).toContain("second output");
expect(result[0].content).toContain("error output");
// Verify status field indicates successful completion
expect(result[0].status).toBe("Command completed");
// Verify that initial streaming updates have empty status for regular commands
const firstCall = mockOutputFn.mock.calls[0][0];
if (firstCall && typeof firstCall === 'object') {
if (firstCall && typeof firstCall === "object") {
const contextItems = (firstCall as any).contextItems;
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
// For commands with waitForCompletion=true, status should be empty while streaming
@ -166,8 +177,8 @@ describe("runTerminalCommandImpl", () => {
it("should run commands in background when waitForCompletion is false", async () => {
// Create a self-identifying background process that writes its PID
// to a file we can access to kill it later
const pidFile = path.join(tempDir, 'test-pid.txt');
const pidFile = path.join(tempDir, "test-pid.txt");
// This script creates a long-running process and writes its PID to our file
// Using a fixed duration timeout so we can be sure to clean it up
const command = `node -e "
@ -178,59 +189,66 @@ describe("runTerminalCommandImpl", () => {
console.log('background process completed');
}, 500);
"`;
const args = { command, waitForCompletion: false };
const mockOutputFn = jest.fn();
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
const result = await runTerminalCommandImpl(args, extras);
// Result should indicate background running in either content or status
expect(result[0].content || result[0].status).toContain("running in the background");
expect(result[0].content || result[0].status).toContain(
"running in the background",
);
// Verify status field indicates background running
expect(result[0].status).toBe("Command is running in the background...");
// Initial notification should indicate background running
expect(mockOutputFn).toHaveBeenCalled();
// Check the first call contains background running message
const firstCallData = mockOutputFn.mock.calls[0][0];
if (firstCallData && typeof firstCallData === 'object') {
if (firstCallData && typeof firstCallData === "object") {
const contextItems = (firstCallData as any).contextItems;
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
expect(contextItems[0].content).toContain("");
expect(contextItems[0].status).toMatch(/Command is running in the background.../);
expect(contextItems[0].status).toMatch(
/Command is running in the background.../,
);
}
}
// Wait a bit to make sure the PID file is written
await new Promise(resolve => setTimeout(resolve, 100));
await new Promise((resolve) => setTimeout(resolve, 100));
// Read the PID file to get the process ID so we can kill it later
if (fs.existsSync(pidFile)) {
testPid = Number(fs.readFileSync(pidFile, 'utf-8'));
testPid = Number(fs.readFileSync(pidFile, "utf-8"));
}
// Wait a bit longer for the process to complete and onPartialOutput to be called again
await new Promise(resolve => setTimeout(resolve, 400));
await new Promise((resolve) => setTimeout(resolve, 400));
// Check for background process completion message in mockOutputFn calls
// Note: This is optional and depends on timing, so we don't want to strictly enforce it
let foundCompletionMessage = false;
for (let i = 0; i < mockOutputFn.mock.calls.length; i++) {
const call = mockOutputFn.mock.calls[i][0];
if (call && typeof call === 'object') {
if (call && typeof call === "object") {
const contextItems = (call as any).contextItems;
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
if (contextItems[0].status === "\nBackground command completed" ||
(contextItems[0].status && contextItems[0].status.includes("Background command"))) {
if (
contextItems[0].status === "\nBackground command completed" ||
(contextItems[0].status &&
contextItems[0].status.includes("Background command"))
) {
foundCompletionMessage = true;
break;
}
}
}
}
// If we found any completion message in the output, great!
// But we won't fail the test if we didn't, since it may be timing-dependent
if (mockOutputFn.mock.calls.length > 1) {
@ -244,7 +262,7 @@ describe("runTerminalCommandImpl", () => {
const extras = createMockExtras({ remoteName: "ssh" });
const result = await runTerminalCommandImpl(args, extras);
// In remote environments, it should use the IDE's runCommand
expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'");
// Match the actual output message
@ -256,23 +274,26 @@ describe("runTerminalCommandImpl", () => {
it("should handle errors when executing invalid commands", async () => {
// Use a command that should fail on any platform
const args = { command: "non-existent-command-xyz", waitForCompletion: true };
const args = {
command: "non-existent-command-xyz",
waitForCompletion: true,
};
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
expect(result[0].name).toBe("Terminal");
expect(result[0].description).toBe("Terminal command output");
// The exact error message varies by platform, but should contain error information
const errorContent = result[0].content;
expect(
errorContent.includes("Command failed") ||
errorContent.includes("not found") ||
errorContent.includes("recognized") ||
/error/i.test(errorContent)
errorContent.includes("Command failed") ||
errorContent.includes("not found") ||
errorContent.includes("recognized") ||
/error/i.test(errorContent),
).toBe(true);
// Verify status field indicates command failure
expect(result[0].status).toContain("Command failed with:");
});
@ -284,23 +305,23 @@ describe("runTerminalCommandImpl", () => {
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
// Verify we still get a result with a name and description
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
expect(result[0].description).toBe("Terminal command output");
// The command should have executed and returned content
expect(result[0].content).toBeDefined();
// We should see the error message we wrote to stderr
expect(result[0].content).toContain("This is an error message");
// Verify status field indicates command failure - the exact message format can vary
// between different node versions and platforms
expect(result[0].status).toContain("Command failed");
});
it("should set appropriate status when a command completes successfully", async () => {
// Use a simple command that will succeed
const command = `node -e "console.log('success test')"`;
@ -308,14 +329,14 @@ describe("runTerminalCommandImpl", () => {
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
expect(result[0].content).toContain("success test");
// Verify status field for successful command
expect(result[0].status).toBe("Command completed");
});
it("should include status info for background commands in non-streaming mode", async () => {
// Use a simple background command
const command = `node -e "setTimeout(() => console.log('done'), 300)"`;
@ -324,7 +345,7 @@ describe("runTerminalCommandImpl", () => {
const extras = createMockExtras();
const result = await runTerminalCommandImpl(args, extras);
expect(result).toHaveLength(1);
expect(result[0].name).toBe("Terminal");
// Verify both content and status fields for background commands

View file

@ -3,7 +3,10 @@ import util from "node:util";
import { fileURLToPath } from "node:url";
import { ToolImpl } from ".";
import { isProcessBackgrounded, removeBackgroundedProcess } from "../../util/processTerminalBackgroundStates";
import {
isProcessBackgrounded,
removeBackgroundedProcess,
} from "../../util/processTerminalBackgroundStates";
const asyncExec = util.promisify(childProcess.exec);
@ -56,7 +59,9 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Send partial output to UI
if (extras.onPartialOutput) {
const status = waitForCompletion ? "" : "Command is running in the background...";
const status = waitForCompletion
? ""
: "Command is running in the background...";
extras.onPartialOutput({
toolCallId,
contextItems: [
@ -116,9 +121,10 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
if (!waitForCompletion) {
// Already resolved, just update the UI with final output
if (extras.onPartialOutput) {
const status = (code === 0 || !code
? "\nBackground command completed"
: `\nBackground command failed with exit code ${code}`)
const status =
code === 0 || !code
? "\nBackground command completed"
: `\nBackground command failed with exit code ${code}`;
extras.onPartialOutput({
toolCallId,
contextItems: [
@ -140,7 +146,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
name: "Terminal",
description: "Terminal command output",
content: terminalOutput,
status: status
status: status,
},
]);
} else {
@ -149,9 +155,8 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
{
name: "Terminal",
description: "Terminal command output",
content:
terminalOutput,
status: status,
content: terminalOutput,
status: status,
},
]);
}
@ -191,7 +196,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Detach the process so it's not tied to the parent
detached: true,
// Redirect to /dev/null equivalent (works cross-platform)
stdio: 'ignore',
stdio: "ignore",
});
// Even for detached processes, add event handlers to clean up the background process map
@ -225,7 +230,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
name: "Terminal",
description: "Terminal command output",
content: status,
status: status
status: status,
},
];
}
@ -269,4 +274,4 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
status: "Command failed",
},
];
}
};

View file

@ -1,4 +1,3 @@
/**
* Recursively retrieves the root cause of an error by traversing through its `cause` property.
*
@ -6,8 +5,8 @@
* @returns The root cause of the error, or the original error if no further cause is found.
*/
export function getRootCause(err: any): any {
if (err.cause) {
return getRootCause(err.cause);
}
return err;
}
if (err.cause) {
return getRootCause(err.cause);
}
return err;
}

View file

@ -14,7 +14,7 @@ export async function findFaviconPath(url: URL): Promise<string | undefined> {
const document = dom.window.document;
// Look for favicon in <link> tags
const linkTags = document.querySelectorAll("link[rel*=\"icon\"]");
const linkTags = document.querySelectorAll('link[rel*="icon"]');
for (const link of linkTags) {
const href = link.getAttribute("href");

View file

@ -74,7 +74,7 @@ export function getMarkdownLanguageTagForFile(filepath: string): string {
tsx: "tsx",
ts: "typescript",
java: "java",
class:"java", //.class files decompile to Java
class: "java", //.class files decompile to Java
go: "go",
rb: "ruby",
rs: "rust",
@ -101,8 +101,7 @@ export function getMarkdownLanguageTagForFile(filepath: string): string {
return ext ? (extToLangMap[ext] ?? ext) : "";
}
function sanitizeExtension(ext?: string): string|undefined {
function sanitizeExtension(ext?: string): string | undefined {
if (ext) {
//ignore ranges in extension eg. "java (11-23)"
const match = ext.match(/^(\S+)\s*(\(.*\))?$/);
@ -208,6 +207,6 @@ export function removeCodeBlocksAndTrim(text: string): string {
export function splitCamelCaseAndNonAlphaNumeric(value: string) {
return value
.split(/(?<=[a-z0-9])(?=[A-Z])|[^a-zA-Z0-9]/)
.filter(t => t.length > 0)
.map(t => t.toLowerCase());
.filter((t) => t.length > 0)
.map((t) => t.toLowerCase());
}

View file

@ -10,7 +10,7 @@ describe("mergeJson", () => {
expect(result).toEqual({ a: 1, b: 3, c: 4 });
});
it("should overwrite values when mergeBehavior is \"overwrite\"", () => {
it('should overwrite values when mergeBehavior is "overwrite"', () => {
const first = { a: 1, b: 2 };
const second = { b: 3, c: 4 };
const result = mergeJson(first, second, "overwrite");

View file

@ -1,5 +1,15 @@
import { stripImages, renderChatMessage, renderContextItems, normalizeToMessageParts } from "./messageContent.js";
import { ChatMessage, ContextItem, MessageContent, MessagePart } from "../index.js";
import {
stripImages,
renderChatMessage,
renderContextItems,
normalizeToMessageParts,
} from "./messageContent.js";
import {
ChatMessage,
ContextItem,
MessageContent,
MessagePart,
} from "../index.js";
describe("messageContent utility functions", () => {
describe("stripImages", () => {
@ -11,7 +21,10 @@ describe("messageContent utility functions", () => {
it("should strip out image parts and join text parts of a message", () => {
const content: MessageContent = [
{ type: "text", text: "This is" },
{ type: "imageUrl", imageUrl: { url: "http://example.com/image1.png" } },
{
type: "imageUrl",
imageUrl: { url: "http://example.com/image1.png" },
},
{ type: "text", text: "a test message." },
];
expect(stripImages(content)).toBe("This is\na test message.");
@ -24,7 +37,10 @@ describe("messageContent utility functions", () => {
role: "assistant",
content: [
{ type: "text", text: "Hello," },
{ type: "imageUrl", imageUrl: { url: "http://example.com/image.png" } },
{
type: "imageUrl",
imageUrl: { url: "http://example.com/image.png" },
},
{ type: "text", text: "world!" },
],
};
@ -44,10 +60,20 @@ describe("messageContent utility functions", () => {
describe("renderContextItems", () => {
it("should concatenate the content of context items with two newlines", () => {
const items: ContextItem[] = [
{ content: "Context Item 1", name: "Item1", description: "Description1" },
{ content: "Context Item 2", name: "Item2", description: "Description2" },
{
content: "Context Item 1",
name: "Item1",
description: "Description1",
},
{
content: "Context Item 2",
name: "Item2",
description: "Description2",
},
];
expect(renderContextItems(items)).toBe("Context Item 1\n\nContext Item 2");
expect(renderContextItems(items)).toBe(
"Context Item 1\n\nContext Item 2",
);
});
});
@ -57,7 +83,9 @@ describe("messageContent utility functions", () => {
role: "user",
content: "This is a test message.",
};
const expected: MessagePart[] = [{ type: "text", text: "This is a test message." }];
const expected: MessagePart[] = [
{ type: "text", text: "This is a test message." },
];
expect(normalizeToMessageParts(message)).toEqual(expected);
});
@ -67,8 +95,10 @@ describe("messageContent utility functions", () => {
content: "Tool message content",
toolCallId: "1",
};
const expected: MessagePart[] = [{ type: "text", text: "Tool message content" }];
const expected: MessagePart[] = [
{ type: "text", text: "Tool message content" },
];
expect(normalizeToMessageParts(message)).toEqual(expected);
});
});
});
});

View file

@ -4,96 +4,100 @@ import path from "node:path";
import { IDE } from "..";
export interface ModelInfo {
id: string;
size: number;
digest: string;
id: string;
size: number;
digest: string;
}
export async function isOllamaInstalled(): Promise<boolean> {
return new Promise((resolve, _reject) => {
const command = process.platform === "win32" ? "where.exe ollama" : "which ollama";
exec(command, (error, _stdout, _stderr) => {
resolve(!error);
});
return new Promise((resolve, _reject) => {
const command =
process.platform === "win32" ? "where.exe ollama" : "which ollama";
exec(command, (error, _stdout, _stderr) => {
resolve(!error);
});
});
}
export async function startLocalOllama(ide: IDE): Promise<any> {
let startCommand: string | undefined;
let startCommand: string | undefined;
switch (process.platform) {
case "darwin"://MacOS
startCommand = "open -a Ollama.app\n";
break;
switch (process.platform) {
case "darwin": //MacOS
startCommand = "open -a Ollama.app\n";
break;
case "win32"://Windows
startCommand = "& \"ollama app.exe\"\n";
break;
case "win32": //Windows
startCommand = '& "ollama app.exe"\n';
break;
default: //Linux...
const start_script_path = path.resolve(__dirname, "./start_ollama.sh");
if (await ide.fileExists(`file:/${start_script_path}`)) {
startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`;
console.log(`Ollama Linux startup script at : ${start_script_path}`);
} else {
return ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`)
}
}
if (startCommand) {
return ide.runCommand(startCommand, {
reuseTerminal: true,
terminalName: "Start Ollama"
});
}
default: //Linux...
const start_script_path = path.resolve(__dirname, "./start_ollama.sh");
if (await ide.fileExists(`file:/${start_script_path}`)) {
startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`;
console.log(`Ollama Linux startup script at : ${start_script_path}`);
} else {
return ide.showToast(
"error",
`Cannot start Ollama: could not find ${start_script_path}!`,
);
}
}
if (startCommand) {
return ide.runCommand(startCommand, {
reuseTerminal: true,
terminalName: "Start Ollama",
});
}
}
export async function getRemoteModelInfo(
modelId: string,
signal?: AbortSignal,
): Promise<ModelInfo | undefined> {
const start = Date.now();
const [modelName, tag = "latest"] = modelId.split(":");
const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`;
try {
const sig = signal ? signal : AbortSignal.timeout(3000);
const response = await fetch(url, { signal: sig });
modelId: string,
signal?: AbortSignal,
): Promise<ModelInfo | undefined> {
const start = Date.now();
const [modelName, tag = "latest"] = modelId.split(":");
const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`;
try {
const sig = signal ? signal : AbortSignal.timeout(3000);
const response = await fetch(url, { signal: sig });
if (!response.ok) {
throw new Error(`Failed to fetch the model page: ${response.statusText}`);
}
// First, read the response body as an ArrayBuffer to compute the digest
const buffer = await response.arrayBuffer();
const digest = getDigest(buffer);
// Then, decode the ArrayBuffer into a string and parse it as JSON
const text = new TextDecoder().decode(buffer);
const manifest = JSON.parse(text) as {
config: { size: number };
layers: { size: number }[];
};
const modelSize =
manifest.config.size +
manifest.layers.reduce((sum, layer) => sum + layer.size, 0);
const data: ModelInfo = {
id: modelId,
size: modelSize,
digest,
};
// Cache the successful result
return data;
} catch (error) {
console.error(`Error fetching or parsing model info: ${error}`);
} finally {
const elapsed = Date.now() - start;
console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`);
if (!response.ok) {
throw new Error(`Failed to fetch the model page: ${response.statusText}`);
}
return undefined;
}
function getDigest(buffer: ArrayBuffer): string {
const hash = crypto.createHash("sha256");
hash.update(new Uint8Array(buffer));
return hash.digest("hex");
}
// First, read the response body as an ArrayBuffer to compute the digest
const buffer = await response.arrayBuffer();
const digest = getDigest(buffer);
// Then, decode the ArrayBuffer into a string and parse it as JSON
const text = new TextDecoder().decode(buffer);
const manifest = JSON.parse(text) as {
config: { size: number };
layers: { size: number }[];
};
const modelSize =
manifest.config.size +
manifest.layers.reduce((sum, layer) => sum + layer.size, 0);
const data: ModelInfo = {
id: modelId,
size: modelSize,
digest,
};
// Cache the successful result
return data;
} catch (error) {
console.error(`Error fetching or parsing model info: ${error}`);
} finally {
const elapsed = Date.now() - start;
console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`);
}
return undefined;
}
function getDigest(buffer: ArrayBuffer): string {
const hash = crypto.createHash("sha256");
hash.update(new Uint8Array(buffer));
return hash.digest("hex");
}

View file

@ -1,71 +1,73 @@
import {
markProcessAsBackgrounded,
isProcessBackgrounded,
removeBackgroundedProcess
} from './processTerminalBackgroundStates';
removeBackgroundedProcess,
} from "./processTerminalBackgroundStates";
describe('processTerminalBackgroundStates', () => {
describe("processTerminalBackgroundStates", () => {
beforeEach(() => {
// Clear any backgrounded processes before each test
const backgroundedProcesses = Array.from(
Object.getOwnPropertySymbols(global)
).find(symbol => String(symbol) === 'Symbol(processTerminalBackgroundStates)');
Object.getOwnPropertySymbols(global),
).find(
(symbol) => String(symbol) === "Symbol(processTerminalBackgroundStates)",
);
if (backgroundedProcesses) {
// Reset the map by reimporting the module
jest.resetModules();
}
});
test('should mark a process as backgrounded', () => {
const toolCallId = 'test-123';
test("should mark a process as backgrounded", () => {
const toolCallId = "test-123";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
});
test('should correctly identify non-backgrounded processes', () => {
const toolCallId = 'test-123';
const anotherToolCallId = 'test-456';
test("should correctly identify non-backgrounded processes", () => {
const toolCallId = "test-123";
const anotherToolCallId = "test-456";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
});
test('should remove a process from backgrounded state', () => {
const toolCallId = 'test-123';
test("should remove a process from backgrounded state", () => {
const toolCallId = "test-123";
markProcessAsBackgrounded(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(true);
removeBackgroundedProcess(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(false);
});
test('should handle removing non-existent processes', () => {
const toolCallId = 'test-123';
test("should handle removing non-existent processes", () => {
const toolCallId = "test-123";
// Should not throw an error
removeBackgroundedProcess(toolCallId);
expect(isProcessBackgrounded(toolCallId)).toBe(false);
});
test('should handle multiple processes', () => {
const toolCallId1 = 'test-123';
const toolCallId2 = 'test-456';
const toolCallId3 = 'test-789';
test("should handle multiple processes", () => {
const toolCallId1 = "test-123";
const toolCallId2 = "test-456";
const toolCallId3 = "test-789";
markProcessAsBackgrounded(toolCallId1);
markProcessAsBackgrounded(toolCallId2);
expect(isProcessBackgrounded(toolCallId1)).toBe(true);
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
expect(isProcessBackgrounded(toolCallId3)).toBe(false);
removeBackgroundedProcess(toolCallId1);
expect(isProcessBackgrounded(toolCallId1)).toBe(false);
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
});
});
});

View file

@ -14,4 +14,4 @@ export function isProcessBackgrounded(toolCallId: string): boolean {
// Function to remove a process from the backgrounded processes map
export function removeBackgroundedProcess(toolCallId: string): void {
processTerminalBackgroundStates.delete(toolCallId);
}
}

View file

@ -383,11 +383,7 @@
"resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.14.0.tgz",
"integrity": "sha512-5ba7TWomIV/9b6NH/1x/8QEeowsb+jBEvFzU6z0T4mNsFwdPqXeFUM7uxC6QeSRkEbWu3qEB0VMjrvzN/0S9+w==",
"optional": true,
"os": [
"win32",
"darwin",
"linux"
],
"os": ["win32", "darwin", "linux"],
"dependencies": {
"onnxruntime-common": "~1.14.0"
}

View file

@ -1,5 +1,3 @@
<p align="center">
<br/>
<picture>
@ -28,23 +26,21 @@
</a>
</p>
State-of-the-art Machine Learning for the web. Run 🤗 Transformers directly in your browser, with no need for a server!
Transformers.js is designed to be functionally equivalent to Hugging Face's [transformers](https://github.com/huggingface/transformers) python library, meaning you can run the same pretrained models using a very similar API. These models support common tasks in different modalities, such as:
- 📝 **Natural Language Processing**: text classification, named entity recognition, question answering, language modeling, summarization, translation, multiple choice, and text generation.
- 🖼️ **Computer Vision**: image classification, object detection, and segmentation.
- 🗣️ **Audio**: automatic speech recognition and audio classification.
- 🐙 **Multimodal**: zero-shot image classification.
Transformers.js uses [ONNX Runtime](https://onnxruntime.ai/) to run models in the browser. The best part about it, is that you can easily [convert](#convert-your-models-to-onnx) your pretrained PyTorch, TensorFlow, or JAX models to ONNX using [🤗 Optimum](https://github.com/huggingface/optimum#onnx--onnx-runtime).
- 📝 **Natural Language Processing**: text classification, named entity recognition, question answering, language modeling, summarization, translation, multiple choice, and text generation.
- 🖼️ **Computer Vision**: image classification, object detection, and segmentation.
- 🗣️ **Audio**: automatic speech recognition and audio classification.
- 🐙 **Multimodal**: zero-shot image classification.
Transformers.js uses [ONNX Runtime](https://onnxruntime.ai/) to run models in the browser. The best part about it, is that you can easily [convert](#convert-your-models-to-onnx) your pretrained PyTorch, TensorFlow, or JAX models to ONNX using [🤗 Optimum](https://github.com/huggingface/optimum#onnx--onnx-runtime).
For more information, check out the full [documentation](https://huggingface.co/docs/transformers.js).
## Quick tour
It's super simple to translate from existing code! Just like the python library, we support the `pipeline` API. Pipelines group together a pretrained model with preprocessing of inputs and postprocessing of outputs, making it the easiest way to run models with the library.
<table>
@ -69,12 +65,12 @@ out = pipe('I love transformers!')
<td>
```javascript
import { pipeline } from '@xenova/transformers';
import { pipeline } from "@xenova/transformers";
// Allocate a pipeline for sentiment-analysis
let pipe = await pipeline('sentiment-analysis');
let pipe = await pipeline("sentiment-analysis");
let out = await pipe('I love transformers!');
let out = await pipe("I love transformers!");
// [{'label': 'POSITIVE', 'score': 0.999817686}]
```
@ -82,74 +78,72 @@ let out = await pipe('I love transformers!');
</tr>
</table>
You can also use a different model by specifying the model id or path as the second argument to the `pipeline` function. For example:
```javascript
// Use a different model for sentiment-analysis
let pipe = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');
let pipe = await pipeline(
"sentiment-analysis",
"Xenova/bert-base-multilingual-uncased-sentiment",
);
```
## Installation
To install via [NPM](https://www.npmjs.com/package/@xenova/transformers), run:
```bash
npm i @xenova/transformers
```
Alternatively, you can use it in vanilla JS, without any bundler, by using a CDN or static hosting. For example, using [ES Modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), you can import the library with:
```html
<script type="module">
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0';
import { pipeline } from "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0";
</script>
```
## Examples
Want to jump straight in? Get started with one of our sample applications/templates:
| Name | Description | Links |
|-------------------|----------------------------------|-------------------------------|
| Whisper Web | Speech recognition w/ Whisper | [code](https://github.com/xenova/whisper-web), [demo](https://huggingface.co/spaces/Xenova/whisper-web) |
| Doodle Dash | Real-time sketch-recognition game | [blog](https://huggingface.co/blog/ml-web-games), [code](https://github.com/xenova/doodle-dash), [demo](https://huggingface.co/spaces/Xenova/doodle-dash) |
| Code Playground | In-browser code completion website | [code](./examples/code-completion/), [demo](https://huggingface.co/spaces/Xenova/ai-code-playground) |
| Semantic Image Search (client-side) | Search for images with text | [code](./examples/semantic-image-search-client/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search-client) |
| Semantic Image Search (server-side) | Search for images with text (Supabase) | [code](./examples/semantic-image-search/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search) |
| Vanilla JavaScript | In-browser object detection | [video](https://scrimba.com/scrim/cKm9bDAg), [code](./examples/vanilla-js/), [demo](https://huggingface.co/spaces/Scrimba/vanilla-js-object-detector) |
| React | Multilingual translation website | [code](./examples/react-translator/), [demo](https://huggingface.co/spaces/Xenova/react-translator) |
| Text to speech (client-side) | In-browser speech synthesis | [code](./examples/text-to-speech-client/), [demo](https://huggingface.co/spaces/Xenova/text-to-speech-client) |
| Browser extension | Text classification extension | [code](./examples/extension/) |
| Electron | Text classification application | [code](./examples/electron/) |
| Next.js (client-side) | Sentiment analysis (in-browser inference) | [code](./examples/next-client/), [demo](https://huggingface.co/spaces/Xenova/next-example-app) |
| Next.js (server-side) | Sentiment analysis (Node.js inference) | [code](./examples/next-server/), [demo](https://huggingface.co/spaces/Xenova/next-server-example-app) |
| Node.js | Sentiment analysis API | [code](./examples/node/) |
| Demo site | A collection of demos | [code](./examples/demo-site/), [demo](https://xenova.github.io/transformers.js/) |
| Name | Description | Links |
| ----------------------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Whisper Web | Speech recognition w/ Whisper | [code](https://github.com/xenova/whisper-web), [demo](https://huggingface.co/spaces/Xenova/whisper-web) |
| Doodle Dash | Real-time sketch-recognition game | [blog](https://huggingface.co/blog/ml-web-games), [code](https://github.com/xenova/doodle-dash), [demo](https://huggingface.co/spaces/Xenova/doodle-dash) |
| Code Playground | In-browser code completion website | [code](./examples/code-completion/), [demo](https://huggingface.co/spaces/Xenova/ai-code-playground) |
| Semantic Image Search (client-side) | Search for images with text | [code](./examples/semantic-image-search-client/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search-client) |
| Semantic Image Search (server-side) | Search for images with text (Supabase) | [code](./examples/semantic-image-search/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search) |
| Vanilla JavaScript | In-browser object detection | [video](https://scrimba.com/scrim/cKm9bDAg), [code](./examples/vanilla-js/), [demo](https://huggingface.co/spaces/Scrimba/vanilla-js-object-detector) |
| React | Multilingual translation website | [code](./examples/react-translator/), [demo](https://huggingface.co/spaces/Xenova/react-translator) |
| Text to speech (client-side) | In-browser speech synthesis | [code](./examples/text-to-speech-client/), [demo](https://huggingface.co/spaces/Xenova/text-to-speech-client) |
| Browser extension | Text classification extension | [code](./examples/extension/) |
| Electron | Text classification application | [code](./examples/electron/) |
| Next.js (client-side) | Sentiment analysis (in-browser inference) | [code](./examples/next-client/), [demo](https://huggingface.co/spaces/Xenova/next-example-app) |
| Next.js (server-side) | Sentiment analysis (Node.js inference) | [code](./examples/next-server/), [demo](https://huggingface.co/spaces/Xenova/next-server-example-app) |
| Node.js | Sentiment analysis API | [code](./examples/node/) |
| Demo site | A collection of demos | [code](./examples/demo-site/), [demo](https://xenova.github.io/transformers.js/) |
Check out the Transformers.js [template](https://huggingface.co/new-space?template=static-templates%2Ftransformers.js) on Hugging Face to get started in one click!
## Custom usage
By default, Transformers.js uses [hosted pretrained models](https://huggingface.co/models?library=transformers.js) and [precompiled WASM binaries](https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0/dist/), which should work out-of-the-box. You can customize this as follows:
### Settings
```javascript
import { env } from '@xenova/transformers';
import { env } from "@xenova/transformers";
// Specify a custom location for models (defaults to '/models/').
env.localModelPath = '/path/to/models/';
env.localModelPath = "/path/to/models/";
// Disable the loading of remote models from the Hugging Face Hub:
env.allowRemoteModels = false;
// Set location of .wasm files. Defaults to use a CDN.
env.backends.onnx.wasm.wasmPaths = '/path/to/files/';
env.backends.onnx.wasm.wasmPaths = "/path/to/files/";
```
For a full list of available settings, check out the [API Reference](https://huggingface.co/docs/transformers.js/api/env).
@ -163,6 +157,7 @@ python -m scripts.convert --quantize --model_id <model_name_or_path>
```
For example, convert and quantize [bert-base-uncased](https://huggingface.co/bert-base-uncased) using:
```bash
python -m scripts.convert --quantize --model_id bert-base-uncased
```
@ -181,7 +176,6 @@ bert-base-uncased/
For the full list of supported architectures, see the [Optimum documentation](https://huggingface.co/docs/optimum/main/en/exporters/onnx/overview).
## Supported tasks/models
Here is the list of all tasks and architectures currently supported by Transformers.js.
@ -191,78 +185,72 @@ to open up a feature request [here](https://github.com/xenova/transformers.js/is
To find compatible models on the Hub, select the "transformers.js" library tag in the filter menu (or visit [this link](https://huggingface.co/models?library=transformers.js)).
You can refine your search by selecting the task you're interested in (e.g., [text-classification](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js)).
### Tasks
#### Natural Language Processing
| Task | ID | Description | Supported? |
|--------------------------|----|-------------|------------|
| [Conversational](https://huggingface.co/tasks/conversational) | `conversational` | Generating conversational text that is relevant, coherent and knowledgable given a prompt. | ❌ |
| [Fill-Mask](https://huggingface.co/tasks/fill-mask) | `fill-mask` | Masking some of the words in a sentence and predicting which words should replace those masks. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FillMaskPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=fill-mask&library=transformers.js) |
| [Question Answering](https://huggingface.co/tasks/question-answering) | `question-answering` | Retrieve the answer to a question from a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.QuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js) |
| [Sentence Similarity](https://huggingface.co/tasks/sentence-similarity) | `sentence-similarity` | Determining how similar two texts are. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
| [Summarization](https://huggingface.co/tasks/summarization) | `summarization` | Producing a shorter version of a document while preserving its important information. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.SummarizationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js) |
| [Table Question Answering](https://huggingface.co/tasks/table-question-answering) | `table-question-answering` | Answering a question about information from a given table. | ❌ |
| [Text Classification](https://huggingface.co/tasks/text-classification) | `text-classification` or `sentiment-analysis` | Assigning a label or class to a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js) |
| [Text Generation](https://huggingface.co/tasks/text-generation#completion-generation-models) | `text-generation` | Producing new text by predicting the next word in a sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js) |
| [Text-to-text Generation](https://huggingface.co/tasks/text-generation#text-to-text-generation-models) | `text2text-generation` | Converting one text sequence into another text sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.Text2TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text2text-generation&library=transformers.js) |
| [Token Classification](https://huggingface.co/tasks/token-classification) | `token-classification` or `ner` | Assigning a label to each token in a text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TokenClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=token-classification&library=transformers.js) |
| [Translation](https://huggingface.co/tasks/translation) | `translation` | Converting text from one language to another. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TranslationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=translation&library=transformers.js) |
| [Zero-Shot Classification](https://huggingface.co/tasks/zero-shot-classification) | `zero-shot-classification` | Classifying text into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js) |
| Task | ID | Description | Supported? |
| ------------------------------------------------------------------------------------------------------ | --------------------------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Conversational](https://huggingface.co/tasks/conversational) | `conversational` | Generating conversational text that is relevant, coherent and knowledgable given a prompt. | ❌ |
| [Fill-Mask](https://huggingface.co/tasks/fill-mask) | `fill-mask` | Masking some of the words in a sentence and predicting which words should replace those masks. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FillMaskPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=fill-mask&library=transformers.js) |
| [Question Answering](https://huggingface.co/tasks/question-answering) | `question-answering` | Retrieve the answer to a question from a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.QuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js) |
| [Sentence Similarity](https://huggingface.co/tasks/sentence-similarity) | `sentence-similarity` | Determining how similar two texts are. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
| [Summarization](https://huggingface.co/tasks/summarization) | `summarization` | Producing a shorter version of a document while preserving its important information. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.SummarizationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js) |
| [Table Question Answering](https://huggingface.co/tasks/table-question-answering) | `table-question-answering` | Answering a question about information from a given table. | ❌ |
| [Text Classification](https://huggingface.co/tasks/text-classification) | `text-classification` or `sentiment-analysis` | Assigning a label or class to a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js) |
| [Text Generation](https://huggingface.co/tasks/text-generation#completion-generation-models) | `text-generation` | Producing new text by predicting the next word in a sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js) |
| [Text-to-text Generation](https://huggingface.co/tasks/text-generation#text-to-text-generation-models) | `text2text-generation` | Converting one text sequence into another text sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.Text2TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text2text-generation&library=transformers.js) |
| [Token Classification](https://huggingface.co/tasks/token-classification) | `token-classification` or `ner` | Assigning a label to each token in a text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TokenClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=token-classification&library=transformers.js) |
| [Translation](https://huggingface.co/tasks/translation) | `translation` | Converting text from one language to another. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TranslationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=translation&library=transformers.js) |
| [Zero-Shot Classification](https://huggingface.co/tasks/zero-shot-classification) | `zero-shot-classification` | Classifying text into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js) |
#### Vision
| Task | ID | Description | Supported? |
|--------------------------|----|-------------|------------|
| [Depth Estimation](https://huggingface.co/tasks/depth-estimation) | `depth-estimation` | Predicting the depth of objects present in an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DepthEstimationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=depth-estimation&library=transformers.js) |
| [Image Classification](https://huggingface.co/tasks/image-classification) | `image-classification` | Assigning a label or class to an entire image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js) |
| [Image Segmentation](https://huggingface.co/tasks/image-segmentation) | `image-segmentation` | Divides an image into segments where each pixel is mapped to an object. This task has multiple variants such as instance segmentation, panoptic segmentation and semantic segmentation. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageSegmentationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js) |
| [Image-to-Image](https://huggingface.co/tasks/image-to-image) | `image-to-image` | Transforming a source image to match the characteristics of a target image or a target image domain. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToImagePipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-image&library=transformers.js) |
| [Mask Generation](https://huggingface.co/tasks/mask-generation) | `mask-generation` | Generate masks for the objects in an image. | ❌ |
| [Object Detection](https://huggingface.co/tasks/object-detection) | `object-detection` | Identify objects of certain defined classes within an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js) |
| [Video Classification](https://huggingface.co/tasks/video-classification) | n/a | Assigning a label or class to an entire video. | ❌ |
| [Unconditional Image Generation](https://huggingface.co/tasks/unconditional-image-generation) | n/a | Generating images with no condition in any context (like a prompt text or another image). | ❌ |
| Task | ID | Description | Supported? |
| --------------------------------------------------------------------------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Depth Estimation](https://huggingface.co/tasks/depth-estimation) | `depth-estimation` | Predicting the depth of objects present in an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DepthEstimationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=depth-estimation&library=transformers.js) |
| [Image Classification](https://huggingface.co/tasks/image-classification) | `image-classification` | Assigning a label or class to an entire image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js) |
| [Image Segmentation](https://huggingface.co/tasks/image-segmentation) | `image-segmentation` | Divides an image into segments where each pixel is mapped to an object. This task has multiple variants such as instance segmentation, panoptic segmentation and semantic segmentation. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageSegmentationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js) |
| [Image-to-Image](https://huggingface.co/tasks/image-to-image) | `image-to-image` | Transforming a source image to match the characteristics of a target image or a target image domain. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToImagePipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-image&library=transformers.js) |
| [Mask Generation](https://huggingface.co/tasks/mask-generation) | `mask-generation` | Generate masks for the objects in an image. | ❌ |
| [Object Detection](https://huggingface.co/tasks/object-detection) | `object-detection` | Identify objects of certain defined classes within an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js) |
| [Video Classification](https://huggingface.co/tasks/video-classification) | n/a | Assigning a label or class to an entire video. | ❌ |
| [Unconditional Image Generation](https://huggingface.co/tasks/unconditional-image-generation) | n/a | Generating images with no condition in any context (like a prompt text or another image). | ❌ |
#### Audio
| Task | ID | Description | Supported? |
|--------------------------|----|-------------|------------|
| [Audio Classification](https://huggingface.co/tasks/audio-classification) | `audio-classification` | Assigning a label or class to a given audio. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js) |
| [Audio-to-Audio](https://huggingface.co/tasks/audio-to-audio) | n/a | Generating audio from an input audio source. | ❌ |
| [Automatic Speech Recognition](https://huggingface.co/tasks/automatic-speech-recognition) | `automatic-speech-recognition` | Transcribing a given audio into text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AutomaticSpeechRecognitionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js) |
| [Text-to-Speech](https://huggingface.co/tasks/text-to-speech) | `text-to-speech` or `text-to-audio` | Generating natural-sounding speech given text input. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextToAudioPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-to-audio&library=transformers.js) |
| Task | ID | Description | Supported? |
| ----------------------------------------------------------------------------------------- | ----------------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Audio Classification](https://huggingface.co/tasks/audio-classification) | `audio-classification` | Assigning a label or class to a given audio. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js) |
| [Audio-to-Audio](https://huggingface.co/tasks/audio-to-audio) | n/a | Generating audio from an input audio source. | ❌ |
| [Automatic Speech Recognition](https://huggingface.co/tasks/automatic-speech-recognition) | `automatic-speech-recognition` | Transcribing a given audio into text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AutomaticSpeechRecognitionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js) |
| [Text-to-Speech](https://huggingface.co/tasks/text-to-speech) | `text-to-speech` or `text-to-audio` | Generating natural-sounding speech given text input. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextToAudioPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-to-audio&library=transformers.js) |
#### Tabular
| Task | ID | Description | Supported? |
|--------------------------|----|-------------|------------|
| [Tabular Classification](https://huggingface.co/tasks/tabular-classification) | n/a | Classifying a target category (a group) based on set of attributes. | ❌ |
| [Tabular Regression](https://huggingface.co/tasks/tabular-regression) | n/a | Predicting a numerical value given a set of attributes. | ❌ |
| Task | ID | Description | Supported? |
| ----------------------------------------------------------------------------- | --- | ------------------------------------------------------------------- | ---------- |
| [Tabular Classification](https://huggingface.co/tasks/tabular-classification) | n/a | Classifying a target category (a group) based on set of attributes. | ❌ |
| [Tabular Regression](https://huggingface.co/tasks/tabular-regression) | n/a | Predicting a numerical value given a set of attributes. | ❌ |
#### Multimodal
| Task | ID | Description | Supported? |
|--------------------------|----|-------------|------------|
| [Document Question Answering](https://huggingface.co/tasks/document-question-answering) | `document-question-answering` | Answering questions on document images. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DocumentQuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=document-question-answering&library=transformers.js) |
| [Feature Extraction](https://huggingface.co/tasks/feature-extraction) | `feature-extraction` | Transforming raw data into numerical features that can be processed while preserving the information in the original dataset. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
| [Image-to-Text](https://huggingface.co/tasks/image-to-text) | `image-to-text` | Output text from a given image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToTextPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js) |
| [Text-to-Image](https://huggingface.co/tasks/text-to-image) | `text-to-image` | Generates images from input text. | ❌ |
| [Visual Question Answering](https://huggingface.co/tasks/visual-question-answering) | `visual-question-answering` | Answering open-ended questions based on an image. | ❌ |
| [Zero-Shot Audio Classification](https://huggingface.co/learn/audio-course/chapter4/classification_models#zero-shot-audio-classification) | `zero-shot-audio-classification` | Classifying audios into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotAudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-audio-classification&library=transformers.js) |
| [Zero-Shot Image Classification](https://huggingface.co/tasks/zero-shot-image-classification) | `zero-shot-image-classification` | Classifying images into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&library=transformers.js) |
| [Zero-Shot Object Detection](https://huggingface.co/tasks/zero-shot-object-detection) | `zero-shot-object-detection` | Identify objects of classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-object-detection&library=transformers.js) |
| Task | ID | Description | Supported? |
| ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Document Question Answering](https://huggingface.co/tasks/document-question-answering) | `document-question-answering` | Answering questions on document images. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DocumentQuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=document-question-answering&library=transformers.js) |
| [Feature Extraction](https://huggingface.co/tasks/feature-extraction) | `feature-extraction` | Transforming raw data into numerical features that can be processed while preserving the information in the original dataset. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
| [Image-to-Text](https://huggingface.co/tasks/image-to-text) | `image-to-text` | Output text from a given image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToTextPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js) |
| [Text-to-Image](https://huggingface.co/tasks/text-to-image) | `text-to-image` | Generates images from input text. | ❌ |
| [Visual Question Answering](https://huggingface.co/tasks/visual-question-answering) | `visual-question-answering` | Answering open-ended questions based on an image. | ❌ |
| [Zero-Shot Audio Classification](https://huggingface.co/learn/audio-course/chapter4/classification_models#zero-shot-audio-classification) | `zero-shot-audio-classification` | Classifying audios into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotAudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-audio-classification&library=transformers.js) |
| [Zero-Shot Image Classification](https://huggingface.co/tasks/zero-shot-image-classification) | `zero-shot-image-classification` | Classifying images into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&library=transformers.js) |
| [Zero-Shot Object Detection](https://huggingface.co/tasks/zero-shot-object-detection) | `zero-shot-object-detection` | Identify objects of classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-object-detection&library=transformers.js) |
#### Reinforcement Learning
| Task | ID | Description | Supported? |
|--------------------------|----|-------------|------------|
| [Reinforcement Learning](https://huggingface.co/tasks/reinforcement-learning) | n/a | Learning from actions by interacting with an environment through trial and error and receiving rewards (negative or positive) as feedback. | ❌ |
| Task | ID | Description | Supported? |
| ----------------------------------------------------------------------------- | --- | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------- |
| [Reinforcement Learning](https://huggingface.co/tasks/reinforcement-learning) | n/a | Learning from actions by interacting with an environment through trial and error and receiving rewards (negative or positive) as feedback. | ❌ |
### Models
@ -274,7 +262,7 @@ You can refine your search by selecting the task you're interested in (e.g., [te
1. **[Blenderbot](https://huggingface.co/docs/transformers/model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
1. **[BlenderbotSmall](https://huggingface.co/docs/transformers/model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
1. **[BLOOM](https://huggingface.co/docs/transformers/model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/).
1. **[CamemBERT](https://huggingface.co/docs/transformers/model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
1. **[CamemBERT](https://huggingface.co/docs/transformers/model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez\*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
1. **[Chinese-CLIP](https://huggingface.co/docs/transformers/model_doc/chinese_clip)** (from OFA-Sys) released with the paper [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://arxiv.org/abs/2211.01335) by An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou.
1. **[CLAP](https://huggingface.co/docs/transformers/model_doc/clap)** (from LAION-AI) released with the paper [Large-scale Contrastive Language-Audio Pretraining with Feature Fusion and Keyword-to-Caption Augmentation](https://arxiv.org/abs/2211.06687) by Yusong Wu, Ke Chen, Tianyu Zhang, Yuchen Hui, Taylor Berg-Kirkpatrick, Shlomo Dubnov.
1. **[CLIP](https://huggingface.co/docs/transformers/model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever.
@ -294,7 +282,7 @@ You can refine your search by selecting the task you're interested in (e.g., [te
1. **[Donut](https://huggingface.co/docs/transformers/model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park.
1. **[DPT](https://huggingface.co/docs/transformers/master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
1. **[ELECTRA](https://huggingface.co/docs/transformers/model_doc/electra)** (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
1. **[ESM](https://huggingface.co/docs/transformers/model_doc/esm)** (from Meta AI) are transformer protein language models. **ESM-1b** was released with the paper [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118) by Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus. **ESM-1v** was released with the paper [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648) by Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rives. **ESM-2 and ESMFold** were released with the paper [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902) by Zeming Lin, Halil Akin, Roshan Rao, Brian Hie, Zhongkai Zhu, Wenting Lu, Allan dos Santos Costa, Maryam Fazel-Zarandi, Tom Sercu, Sal Candido, Alexander Rives.
1. **[ESM](https://huggingface.co/docs/transformers/model_doc/esm)** (from Meta AI) are transformer protein language models. **ESM-1b** was released with the paper [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118) by Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus. **ESM-1v** was released with the paper [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648) by Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rives. **ESM-2 and ESMFold** were released with the paper [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902) by Zeming Lin, Halil Akin, Roshan Rao, Brian Hie, Zhongkai Zhu, Wenting Lu, Allan dos Santos Costa, Maryam Fazel-Zarandi, Tom Sercu, Sal Candido, Alexander Rives.
1. **[Falcon](https://huggingface.co/docs/transformers/model_doc/falcon)** (from Technology Innovation Institute) by Almazrouei, Ebtesam and Alobeidli, Hamza and Alshamsi, Abdulaziz and Cappelli, Alessandro and Cojocaru, Ruxandra and Debbah, Merouane and Goffinet, Etienne and Heslow, Daniel and Launay, Julien and Malartic, Quentin and Noune, Badreddine and Pannier, Baptiste and Penedo, Guilherme.
1. **[FLAN-T5](https://huggingface.co/docs/transformers/model_doc/flan-t5)** (from Google AI) released in the repository [google-research/t5x](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-t5-checkpoints) by Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, Albert Webson, Shixiang Shane Gu, Zhuyun Dai, Mirac Suzgun, Xinyun Chen, Aakanksha Chowdhery, Sharan Narang, Gaurav Mishra, Adams Yu, Vincent Zhao, Yanping Huang, Andrew Dai, Hongkun Yu, Slav Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam Roberts, Denny Zhou, Quoc V. Le, and Jason Wei
1. **[GLPN](https://huggingface.co/docs/transformers/model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
@ -347,5 +335,3 @@ You can refine your search by selecting the task you're interested in (e.g., [te
1. **[XLM](https://huggingface.co/docs/transformers/model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
1. **[XLM-RoBERTa](https://huggingface.co/docs/transformers/model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
1. **[YOLOS](https://huggingface.co/docs/transformers/model_doc/yolos)** (from Huazhong University of Science & Technology) released with the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.

View file

@ -6,45 +6,46 @@
* So, we just import both packages, and use the appropriate one based on the environment:
* - When running in node, we use `onnxruntime-node`.
* - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled).
*
*
* This module is not directly exported, but can be accessed through the environment variables:
* ```javascript
* import { env } from '@xenova/transformers';
* console.log(env.backends.onnx);
* ```
*
*
* @module backends/onnx
*/
// NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`.
// In either case, we select the default export if it exists, otherwise we use the named export.
import * as ONNX_NODE from 'onnxruntime-node';
import * as ONNX_WEB from 'onnxruntime-web';
import * as ONNX_NODE from "onnxruntime-node";
import * as ONNX_WEB from "onnxruntime-web";
/** @type {import('onnxruntime-web')} The ONNX runtime module. */
export let ONNX;
export const executionProviders = [
// 'webgpu',
'wasm'
// 'webgpu',
"wasm",
];
if (typeof process !== 'undefined' && process?.release?.name === 'node') {
// Running in a node-like environment.
ONNX = ONNX_NODE.default ?? ONNX_NODE;
// Add `cpu` execution provider, with higher precedence that `wasm`.
executionProviders.unshift('cpu');
if (typeof process !== "undefined" && process?.release?.name === "node") {
// Running in a node-like environment.
ONNX = ONNX_NODE.default ?? ONNX_NODE;
// Add `cpu` execution provider, with higher precedence that `wasm`.
executionProviders.unshift("cpu");
} else {
// Running in a browser-environment
ONNX = ONNX_WEB.default ?? ONNX_WEB;
// Running in a browser-environment
ONNX = ONNX_WEB.default ?? ONNX_WEB;
// SIMD for WebAssembly does not operate correctly in some recent versions of iOS (16.4.x).
// As a temporary fix, we disable it for now.
// For more information, see: https://github.com/microsoft/onnxruntime/issues/15644
const isIOS = typeof navigator !== 'undefined' && /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);
if (isIOS) {
ONNX.env.wasm.simd = false;
}
// SIMD for WebAssembly does not operate correctly in some recent versions of iOS (16.4.x).
// As a temporary fix, we disable it for now.
// For more information, see: https://github.com/microsoft/onnxruntime/issues/15644
const isIOS =
typeof navigator !== "undefined" &&
/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);
if (isIOS) {
ONNX.env.wasm.simd = false;
}
}

View file

@ -1,10 +1,9 @@
/**
* @file Helper module for using model configs. For more information, see the corresponding
* [Python documentation](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoConfig).
*
*
* **Example:** Load an `AutoConfig`.
*
*
* ```javascript
* import { AutoConfig } from '@xenova/transformers';
* let config = await AutoConfig.from_pretrained('bert-base-uncased');
@ -23,19 +22,16 @@
* // ...
* // }
* ```
*
*
* @module configs
*/
import {
getModelJSON,
} from './utils/hub.js';
import { getModelJSON } from "./utils/hub.js";
/**
* @typedef {import('./utils/hub.js').PretrainedOptions} PretrainedOptions
*/
/**
* Loads a config from the specified path.
* @param {string} pretrained_model_name_or_path The path to the config directory.
@ -43,8 +39,13 @@ import {
* @returns {Promise<Array>} A promise that resolves with information about the loaded config.
*/
async function loadConfig(pretrained_model_name_or_path, options) {
let info = await getModelJSON(pretrained_model_name_or_path, 'config.json', true, options);
return info;
let info = await getModelJSON(
pretrained_model_name_or_path,
"config.json",
true,
options,
);
return info;
}
/**
@ -52,56 +53,60 @@ async function loadConfig(pretrained_model_name_or_path, options) {
* [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).
*/
export class PretrainedConfig {
// NOTE: Typo in original
// NOTE: Typo in original
/**
* Create a new PreTrainedTokenizer instance.
* @param {Object} configJSON The JSON of the config.
*/
constructor(configJSON) {
this.model_type = null;
this.is_encoder_decoder = false;
/**
* Create a new PreTrainedTokenizer instance.
* @param {Object} configJSON The JSON of the config.
*/
constructor(configJSON) {
this.model_type = null;
this.is_encoder_decoder = false;
Object.assign(this, configJSON);
}
Object.assign(this, configJSON);
}
/**
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
*
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
* @param {PretrainedOptions} options Additional options for loading the config.
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
*
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
*/
static async from_pretrained(pretrained_model_name_or_path, {
progress_callback = null,
config = null,
cache_dir = null,
local_files_only = false,
revision = 'main',
} = {}) {
let data = config ?? await loadConfig(pretrained_model_name_or_path, {
progress_callback,
config,
cache_dir,
local_files_only,
revision,
})
return new this(data);
}
/**
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
*
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
* @param {PretrainedOptions} options Additional options for loading the config.
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
*
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
*/
static async from_pretrained(
pretrained_model_name_or_path,
{
progress_callback = null,
config = null,
cache_dir = null,
local_files_only = false,
revision = "main",
} = {},
) {
let data =
config ??
(await loadConfig(pretrained_model_name_or_path, {
progress_callback,
config,
cache_dir,
local_files_only,
revision,
}));
return new this(data);
}
}
/**
* Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.
*
*
* @example
* let config = await AutoConfig.from_pretrained('bert-base-uncased');
* let config = await AutoConfig.from_pretrained('bert-base-uncased');
*/
export class AutoConfig {
/** @type {PretrainedConfig.from_pretrained} */
static async from_pretrained(...args) {
return PretrainedConfig.from_pretrained(...args);
}
/** @type {PretrainedConfig.from_pretrained} */
static async from_pretrained(...args) {
return PretrainedConfig.from_pretrained(...args);
}
}

View file

@ -1,37 +1,37 @@
/**
* @file Module used to configure Transformers.js.
*
*
* **Example:** Disable remote models.
* ```javascript
* import { env } from '@xenova/transformers';
* env.allowRemoteModels = false;
* ```
*
*
* **Example:** Set local model path.
* ```javascript
* import { env } from '@xenova/transformers';
* env.localModelPath = '/path/to/local/models/';
* ```
*
*
* **Example:** Set cache directory.
* ```javascript
* import { env } from '@xenova/transformers';
* env.cacheDir = '/path/to/cache/directory/';
* ```
*
*
* @module env
*/
import fs from 'fs';
import path from 'path';
import fs from "fs";
import path from "path";
import { ONNX } from './backends/onnx.js';
import { ONNX } from "./backends/onnx.js";
const { env: onnx_env } = ONNX;
const VERSION = '2.14.0';
const VERSION = "2.14.0";
// Check if various APIs are available (depends on environment)
const WEB_CACHE_AVAILABLE = typeof self !== 'undefined' && 'caches' in self;
const WEB_CACHE_AVAILABLE = typeof self !== "undefined" && "caches" in self;
const FS_AVAILABLE = !isEmpty(fs); // check if file system is available
const PATH_AVAILABLE = !isEmpty(path); // check if path is available
@ -43,23 +43,22 @@ const RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE;
// Only used for environments with access to file system
const DEFAULT_CACHE_DIR = RUNNING_LOCALLY
? path.join(__dirname, '/.cache/')
: null;
? path.join(__dirname, "/.cache/")
: null;
// Set local model path, based on available APIs
const DEFAULT_LOCAL_MODEL_PATH = '/models/';
const DEFAULT_LOCAL_MODEL_PATH = "/models/";
const localModelPath = RUNNING_LOCALLY
? path.join(__dirname, DEFAULT_LOCAL_MODEL_PATH)
: DEFAULT_LOCAL_MODEL_PATH;
? path.join(__dirname, DEFAULT_LOCAL_MODEL_PATH)
: DEFAULT_LOCAL_MODEL_PATH;
// Set path to wasm files. This is needed when running in a web worker.
// https://onnxruntime.ai/docs/api/js/interfaces/Env.WebAssemblyFlags.html#wasmPaths
// We use remote wasm files by default to make it easier for newer users.
// In practice, users should probably self-host the necessary .wasm files.
onnx_env.wasm.wasmPaths = RUNNING_LOCALLY
? path.join(__dirname, '/dist/')
: `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;
? path.join(__dirname, "/dist/")
: `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;
/**
* Global variable used to control execution. This provides users a simple way to configure Transformers.js.
@ -83,44 +82,42 @@ onnx_env.wasm.wasmPaths = RUNNING_LOCALLY
* implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache
*/
export const env = {
/////////////////// Backends settings ///////////////////
backends: {
// onnxruntime-web/onnxruntime-node
onnx: onnx_env,
/////////////////// Backends settings ///////////////////
backends: {
// onnxruntime-web/onnxruntime-node
onnx: onnx_env,
// TensorFlow.js
tfjs: {},
},
// TensorFlow.js
tfjs: {},
},
__dirname,
version: VERSION,
__dirname,
version: VERSION,
/////////////////// Model settings ///////////////////
allowRemoteModels: true,
remoteHost: 'https://huggingface.co/',
remotePathTemplate: '{model}/resolve/{revision}/',
/////////////////// Model settings ///////////////////
allowRemoteModels: true,
remoteHost: "https://huggingface.co/",
remotePathTemplate: "{model}/resolve/{revision}/",
allowLocalModels: true,
localModelPath: localModelPath,
useFS: FS_AVAILABLE,
allowLocalModels: true,
localModelPath: localModelPath,
useFS: FS_AVAILABLE,
/////////////////// Cache settings ///////////////////
useBrowserCache: WEB_CACHE_AVAILABLE,
/////////////////// Cache settings ///////////////////
useBrowserCache: WEB_CACHE_AVAILABLE,
useFSCache: FS_AVAILABLE,
cacheDir: DEFAULT_CACHE_DIR,
useCustomCache: false,
customCache: null,
//////////////////////////////////////////////////////
}
useFSCache: FS_AVAILABLE,
cacheDir: DEFAULT_CACHE_DIR,
useCustomCache: false,
customCache: null,
//////////////////////////////////////////////////////
};
/**
* @param {Object} obj
* @private
*/
function isEmpty(obj) {
return Object.keys(obj).length === 0;
return Object.keys(obj).length === 0;
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,18 @@
/**
* @file Entry point for the Transformers.js library. Only the exports from this file
* are available to the end user, and are grouped as follows:
*
*
* 1. [Pipelines](./pipelines)
* 2. [Environment variables](./env)
* 3. [Models](./models)
* 4. [Tokenizers](./tokenizers)
* 5. [Processors](./processors)
*
*
* @module transformers
*/
export * from './env.js';
export * from './pipelines.js';
export * from "./env.js";
export * from "./pipelines.js";
// export * from './models.js';
// export * from './tokenizers.js';
// export * from './processors.js';

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,9 @@
/**
* @file Core utility functions/classes for Transformers.js.
*
*
* These are only used internally, meaning an end-user shouldn't
* need to access anything here.
*
*
* @module utils/core
*/
@ -17,7 +16,7 @@
* @private
*/
export function dispatchCallback(progress_callback, data) {
if (progress_callback) progress_callback(data);
if (progress_callback) progress_callback(data);
}
/**
@ -28,8 +27,10 @@ export function dispatchCallback(progress_callback, data) {
* @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
*/
export function reverseDictionary(data) {
// https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));
// https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
return Object.fromEntries(
Object.entries(data).map(([key, value]) => [value, key]),
);
}
/**
@ -39,29 +40,30 @@ export function reverseDictionary(data) {
* @returns {string} The escaped string.
*/
export function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
/**
* A base class for creating callable objects.
*
*
* @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}
*/
export const Callable = /** @type {any} */ (class {
export const Callable = /** @type {any} */ (
class {
/**
* Creates a new instance of the Callable class.
*/
* Creates a new instance of the Callable class.
*/
constructor() {
/**
* Creates a closure that delegates to a private method '_call' with the given arguments.
* @type {any}
* @param {...any} args Zero or more arguments to pass to the '_call' method.
* @returns {*} The result of calling the '_call' method.
*/
let closure = function (...args) {
return closure._call(...args)
}
return Object.setPrototypeOf(closure, new.target.prototype)
/**
* Creates a closure that delegates to a private method '_call' with the given arguments.
* @type {any}
* @param {...any} args Zero or more arguments to pass to the '_call' method.
* @returns {*} The result of calling the '_call' method.
*/
let closure = function (...args) {
return closure._call(...args);
};
return Object.setPrototypeOf(closure, new.target.prototype);
}
/**
@ -72,29 +74,29 @@ export const Callable = /** @type {any} */ (class {
* @throws {Error} If the subclass does not implement the `_call` method.
*/
_call(...args) {
throw Error('Must implement _call method in subclass')
throw Error("Must implement _call method in subclass");
}
});
}
);
/**
* Check if a value is a typed array.
* @param {*} val The value to check.
* @returns {boolean} True if the value is a `TypedArray`, false otherwise.
*
*
* Adapted from https://stackoverflow.com/a/71091338/13989043
*/
export function isTypedArray(val) {
return val?.prototype?.__proto__?.constructor?.name === 'TypedArray';
return val?.prototype?.__proto__?.constructor?.name === "TypedArray";
}
/**
* Check if a value is an integer.
* @param {*} x The value to check.
* @returns {boolean} True if the value is a string, false otherwise.
*/
export function isIntegralNumber(x) {
return Number.isInteger(x) || typeof x === 'bigint'
return Number.isInteger(x) || typeof x === "bigint";
}
/**
@ -103,7 +105,7 @@ export function isIntegralNumber(x) {
* @returns {boolean} True if the value exists, false otherwise.
*/
export function exists(x) {
return x !== undefined && x !== null;
return x !== undefined && x !== null;
}
/**
@ -113,13 +115,13 @@ export function exists(x) {
* @returns {number[]} An array containing the dimensions of the input array.
*/
export function calculateDimensions(arr) {
const dimensions = [];
let current = arr;
while (Array.isArray(current)) {
dimensions.push(current.length);
current = current[0];
}
return dimensions;
const dimensions = [];
let current = arr;
while (Array.isArray(current)) {
dimensions.push(current.length);
current = current[0];
}
return dimensions;
}
/**
@ -131,15 +133,15 @@ export function calculateDimensions(arr) {
* @throws {Error} If the key does not exist and no default value is provided.
*/
export function pop(obj, key, defaultValue = undefined) {
const value = obj[key];
if (value !== undefined) {
delete obj[key];
return value;
}
if (defaultValue === undefined) {
throw Error(`Key ${key} does not exist in object.`)
}
return defaultValue;
const value = obj[key];
if (value !== undefined) {
delete obj[key];
return value;
}
if (defaultValue === undefined) {
throw Error(`Key ${key} does not exist in object.`);
}
return defaultValue;
}
/**
@ -149,7 +151,7 @@ export function pop(obj, key, defaultValue = undefined) {
* @returns {Array} The merged array.
*/
export function mergeArrays(...arrs) {
return Array.prototype.concat.apply([], arrs);
return Array.prototype.concat.apply([], arrs);
}
/**
@ -159,9 +161,9 @@ export function mergeArrays(...arrs) {
* @private
*/
export function product(...a) {
// Cartesian product of items
// Adapted from https://stackoverflow.com/a/43053803
return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e])));
// Cartesian product of items
// Adapted from https://stackoverflow.com/a/43053803
return a.reduce((a, b) => a.flatMap((d) => b.map((e) => [d, e])));
}
/**
@ -171,5 +173,5 @@ export function product(...a) {
* @returns {number} The index offset.
*/
export function calculateReflectOffset(i, w) {
return Math.abs((i + w) % (2 * w) - w);
return Math.abs(((i + w) % (2 * w)) - w);
}

View file

@ -1,415 +1,420 @@
/**
* @file Custom data structures.
*
*
* These are only used internally, meaning an end-user shouldn't
* need to access anything here.
*
*
* @module utils/data-structures
*/
/**
* Efficient Heap-based Implementation of a Priority Queue.
* It uses an array-based binary heap, where the root is at index `0`, and the
* children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively.
*
*
* Adapted from the following sources:
* - https://stackoverflow.com/a/42919752/13989043 (original)
* - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)
*/
export class PriorityQueue {
/**
* Create a new PriorityQueue.
* @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
*/
constructor(comparator = (a, b) => a > b) {
this._heap = [];
this._comparator = comparator;
}
/**
* Create a new PriorityQueue.
* @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
*/
constructor(comparator = (a, b) => a > b) {
this._heap = [];
this._comparator = comparator;
}
/**
* The size of the queue
*/
get size() {
return this._heap.length;
}
/**
* The size of the queue
*/
get size() {
return this._heap.length;
}
/**
* Check if the queue is empty.
* @returns {boolean} `true` if the queue is empty, `false` otherwise.
*/
isEmpty() {
return this.size === 0;
}
/**
* Check if the queue is empty.
* @returns {boolean} `true` if the queue is empty, `false` otherwise.
*/
isEmpty() {
return this.size === 0;
}
/**
* Return the element with the highest priority in the queue.
* @returns {any} The highest priority element in the queue.
*/
peek() {
return this._heap[0];
}
/**
* Return the element with the highest priority in the queue.
* @returns {any} The highest priority element in the queue.
*/
peek() {
return this._heap[0];
}
/**
* Add one or more elements to the queue.
* @param {...any} values The values to push into the queue.
* @returns {number} The new size of the queue.
*/
push(...values) {
return this.extend(values);
}
/**
* Add one or more elements to the queue.
* @param {...any} values The values to push into the queue.
* @returns {number} The new size of the queue.
*/
push(...values) {
return this.extend(values);
/**
* Add multiple elements to the queue.
* @param {any[]} values The values to push into the queue.
* @returns {number} The new size of the queue.
*/
extend(values) {
for (const value of values) {
this._heap.push(value);
this._siftUp();
}
return this.size;
}
/**
* Add multiple elements to the queue.
* @param {any[]} values The values to push into the queue.
* @returns {number} The new size of the queue.
*/
extend(values) {
for (const value of values) {
this._heap.push(value);
this._siftUp();
}
return this.size;
/**
* Remove and return the element with the highest priority in the queue.
* @returns {any} The element with the highest priority in the queue.
*/
pop() {
const poppedValue = this.peek();
const bottom = this.size - 1;
if (bottom > 0) {
this._swap(0, bottom);
}
this._heap.pop();
this._siftDown();
return poppedValue;
}
/**
* Remove and return the element with the highest priority in the queue.
* @returns {any} The element with the highest priority in the queue.
*/
pop() {
const poppedValue = this.peek();
const bottom = this.size - 1;
if (bottom > 0) {
this._swap(0, bottom);
}
this._heap.pop();
this._siftDown();
return poppedValue;
}
/**
* Replace the element with the highest priority in the queue with a new value.
* @param {*} value The new value.
* @returns {*} The replaced value.
*/
replace(value) {
const replacedValue = this.peek();
this._heap[0] = value;
this._siftDown();
return replacedValue;
}
/**
* Replace the element with the highest priority in the queue with a new value.
* @param {*} value The new value.
* @returns {*} The replaced value.
*/
replace(value) {
const replacedValue = this.peek();
this._heap[0] = value;
this._siftDown();
return replacedValue;
}
/**
* Compute the index for the parent of the node at index `i`.
* @param {number} i The index of the node to get the parent of.
* @returns {number} The index of the parent node.
* @private
*/
_parent(i) {
return ((i + 1) >>> 1) - 1;
}
/**
* Compute the index for the parent of the node at index `i`.
* @param {number} i The index of the node to get the parent of.
* @returns {number} The index of the parent node.
* @private
*/
_parent(i) {
return ((i + 1) >>> 1) - 1;
}
/**
* Compute the index for the left child of the node at index `i`.
* @param {number} i The index of the node to get the left child of.
* @returns {number} The index of the left child.
* @private
*/
_left(i) {
return (i << 1) + 1;
}
/**
* Compute the index for the left child of the node at index `i`.
* @param {number} i The index of the node to get the left child of.
* @returns {number} The index of the left child.
* @private
*/
_left(i) {
return (i << 1) + 1;
}
/**
* Compute the index for the right child of the node at index `i`.
* @param {number} i The index of the node to get the right child of.
* @returns {number} The index of the right child.
* @private
*/
_right(i) {
return (i + 1) << 1;
}
/**
* Compute the index for the right child of the node at index `i`.
* @param {number} i The index of the node to get the right child of.
* @returns {number} The index of the right child.
* @private
*/
_right(i) {
return (i + 1) << 1;
}
/**
* Check if the element at index `i` is greater than the element at index `j`.
* @param {number} i The index of the first element to compare.
* @param {number} j The index of the second element to compare.
* @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
* @private
*/
_greater(i, j) {
return this._comparator(this._heap[i], this._heap[j]);
}
/**
* Check if the element at index `i` is greater than the element at index `j`.
* @param {number} i The index of the first element to compare.
* @param {number} j The index of the second element to compare.
* @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
* @private
*/
_greater(i, j) {
return this._comparator(this._heap[i], this._heap[j]);
}
/**
* Swap the elements at indices `i` and `j`.
* @param {number} i The index of the first element to swap.
* @param {number} j The index of the second element to swap.
* @private
*/
_swap(i, j) {
const temp = this._heap[i];
this._heap[i] = this._heap[j];
this._heap[j] = temp;
}
/**
* Swap the elements at indices `i` and `j`.
* @param {number} i The index of the first element to swap.
* @param {number} j The index of the second element to swap.
* @private
*/
_swap(i, j) {
const temp = this._heap[i];
this._heap[i] = this._heap[j];
this._heap[j] = temp;
/**
* Maintain the heap property by updating positions in the heap,
* starting at the last element and moving up the heap.
* @private
*/
_siftUp() {
let node = this.size - 1;
while (node > 0 && this._greater(node, this._parent(node))) {
this._swap(node, this._parent(node));
node = this._parent(node);
}
/**
* Maintain the heap property by updating positions in the heap,
* starting at the last element and moving up the heap.
* @private
*/
_siftUp() {
let node = this.size - 1;
while (node > 0 && this._greater(node, this._parent(node))) {
this._swap(node, this._parent(node));
node = this._parent(node);
}
}
/**
* Maintain the heap property by updating positions in the heap,
* starting at the first element and moving down the heap.
* @private
*/
_siftDown() {
let node = 0;
while (
(this._left(node) < this.size && this._greater(this._left(node), node)) ||
(this._right(node) < this.size && this._greater(this._right(node), node))
) {
const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node)))
? this._right(node)
: this._left(node);
this._swap(node, maxChild);
node = maxChild;
}
}
/**
* Maintain the heap property by updating positions in the heap,
* starting at the first element and moving down the heap.
* @private
*/
_siftDown() {
let node = 0;
while (
(this._left(node) < this.size && this._greater(this._left(node), node)) ||
(this._right(node) < this.size && this._greater(this._right(node), node))
) {
const maxChild =
this._right(node) < this.size &&
this._greater(this._right(node), this._left(node))
? this._right(node)
: this._left(node);
this._swap(node, maxChild);
node = maxChild;
}
}
}
/**
* A trie structure to efficiently store and search for strings.
*/
export class CharTrie {
constructor() {
this.root = CharTrieNode.default();
}
constructor() {
this.root = CharTrieNode.default();
}
/**
* Adds one or more `texts` to the trie.
* @param {string[]} texts The strings to add to the trie.
*/
extend(texts) {
for (let text of texts) {
this.push(text);
}
/**
* Adds one or more `texts` to the trie.
* @param {string[]} texts The strings to add to the trie.
*/
extend(texts) {
for (let text of texts) {
this.push(text);
}
}
/**
* Adds text to the trie.
* @param {string} text The string to add to the trie.
*/
push(text) {
let node = this.root;
for (let ch of text) {
let child = node.children.get(ch);
if (child === undefined) {
child = CharTrieNode.default();
node.children.set(ch, child);
}
node = child;
}
node.isLeaf = true;
/**
* Adds text to the trie.
* @param {string} text The string to add to the trie.
*/
push(text) {
let node = this.root;
for (let ch of text) {
let child = node.children.get(ch);
if (child === undefined) {
child = CharTrieNode.default();
node.children.set(ch, child);
}
node = child;
}
node.isLeaf = true;
}
/**
* Searches the trie for all strings with a common prefix of `text`.
* @param {string} text The common prefix to search for.
* @yields {string} Each string in the trie that has `text` as a prefix.
*/
*commonPrefixSearch(text) {
let node = this.root;
let prefix = "";
for (let i = 0; i < text.length && node !== undefined; ++i) {
const ch = text[i];
prefix += ch;
node = node.children.get(ch);
if (node !== undefined && node.isLeaf) {
yield prefix;
}
}
/**
* Searches the trie for all strings with a common prefix of `text`.
* @param {string} text The common prefix to search for.
* @yields {string} Each string in the trie that has `text` as a prefix.
*/
*commonPrefixSearch(text) {
let node = this.root;
let prefix = "";
for (let i = 0; i < text.length && node !== undefined; ++i) {
const ch = text[i];
prefix += ch;
node = node.children.get(ch);
if (node !== undefined && node.isLeaf) {
yield prefix;
}
}
}
}
/**
* Represents a node in a character trie.
*/
class CharTrieNode {
/**
* Create a new CharTrieNode.
* @param {boolean} isLeaf Whether the node is a leaf node or not.
* @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
*/
constructor(isLeaf, children) {
this.isLeaf = isLeaf;
this.children = children;
}
/**
* Create a new CharTrieNode.
* @param {boolean} isLeaf Whether the node is a leaf node or not.
* @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
*/
constructor(isLeaf, children) {
this.isLeaf = isLeaf;
this.children = children;
}
/**
* Returns a new `CharTrieNode` instance with default values.
* @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
*/
static default() {
return new CharTrieNode(false, new Map());
}
/**
* Returns a new `CharTrieNode` instance with default values.
* @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
*/
static default() {
return new CharTrieNode(false, new Map());
}
}
/**
* A lattice data structure to be used for tokenization.
*/
export class TokenLattice {
/**
* Creates a new TokenLattice instance.
*
* @param {string} sentence The input sentence to be tokenized.
* @param {number} bosTokenId The beginning-of-sequence token ID.
* @param {number} eosTokenId The end-of-sequence token ID.
*/
constructor(sentence, bosTokenId, eosTokenId) {
this.sentence = sentence;
this.len = sentence.length;
this.bosTokenId = bosTokenId;
this.eosTokenId = eosTokenId;
this.nodes = [];
this.beginNodes = Array.from({ length: this.len + 1 }, () => []);
this.endNodes = Array.from({ length: this.len + 1 }, () => []);
/**
* Creates a new TokenLattice instance.
*
* @param {string} sentence The input sentence to be tokenized.
* @param {number} bosTokenId The beginning-of-sequence token ID.
* @param {number} eosTokenId The end-of-sequence token ID.
*/
constructor(sentence, bosTokenId, eosTokenId) {
this.sentence = sentence;
this.len = sentence.length;
this.bosTokenId = bosTokenId;
this.eosTokenId = eosTokenId;
this.nodes = [];
this.beginNodes = Array.from({ length: this.len + 1 }, () => []);
this.endNodes = Array.from({ length: this.len + 1 }, () => []);
const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);
const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);
this.nodes.push(bos.clone());
this.nodes.push(eos.clone());
this.beginNodes[this.len].push(eos);
this.endNodes[0].push(bos);
}
const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);
const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);
this.nodes.push(bos.clone());
this.nodes.push(eos.clone());
this.beginNodes[this.len].push(eos);
this.endNodes[0].push(bos);
}
/**
* Inserts a new token node into the token lattice.
*
* @param {number} pos The starting position of the token.
* @param {number} length The length of the token.
* @param {number} score The score of the token.
* @param {number} tokenId The token ID of the token.
*/
insert(pos, length, score, tokenId) {
const nodeId = this.nodes.length;
const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);
this.beginNodes[pos].push(node);
this.endNodes[pos + length].push(node);
this.nodes.push(node);
}
/**
* Inserts a new token node into the token lattice.
*
* @param {number} pos The starting position of the token.
* @param {number} length The length of the token.
* @param {number} score The score of the token.
* @param {number} tokenId The token ID of the token.
*/
insert(pos, length, score, tokenId) {
const nodeId = this.nodes.length;
const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);
this.beginNodes[pos].push(node);
this.endNodes[pos + length].push(node);
this.nodes.push(node);
}
/**
* Implements the Viterbi algorithm to compute the most likely sequence of tokens.
*
* @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
*/
viterbi() {
const len = this.len;
let pos = 0;
while (pos <= len) {
if (this.beginNodes[pos].length == 0) {
return [];
}
for (let rnode of this.beginNodes[pos]) {
rnode.prev = null;
let bestScore = 0.0;
let bestNode = null;
for (let lnode of this.endNodes[pos]) {
const score = lnode.backtraceScore + rnode.score;
if (bestNode === null || score > bestScore) {
bestNode = lnode.clone();
bestScore = score;
}
}
if (bestNode !== null) {
rnode.prev = bestNode;
rnode.backtraceScore = bestScore;
} else {
return [];
}
}
++pos;
/**
* Implements the Viterbi algorithm to compute the most likely sequence of tokens.
*
* @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
*/
viterbi() {
const len = this.len;
let pos = 0;
while (pos <= len) {
if (this.beginNodes[pos].length == 0) {
return [];
}
for (let rnode of this.beginNodes[pos]) {
rnode.prev = null;
let bestScore = 0.0;
let bestNode = null;
for (let lnode of this.endNodes[pos]) {
const score = lnode.backtraceScore + rnode.score;
if (bestNode === null || score > bestScore) {
bestNode = lnode.clone();
bestScore = score;
}
}
const results = [];
const root = this.beginNodes[len][0];
const prev = root.prev;
if (prev === null) {
return [];
if (bestNode !== null) {
rnode.prev = bestNode;
rnode.backtraceScore = bestScore;
} else {
return [];
}
let node = prev.clone();
while (node.prev !== null) {
results.push(node.clone());
const n = node.clone();
node = n.prev.clone();
}
results.reverse();
return results;
}
++pos;
}
/**
* @param {TokenLatticeNode} node
* @returns {string} The array of nodes representing the most likely sequence of tokens.
*/
piece(node) {
return this.sentence.slice(node.pos, node.pos + node.length);
const results = [];
const root = this.beginNodes[len][0];
const prev = root.prev;
if (prev === null) {
return [];
}
/**
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
*/
tokens() {
const nodes = this.viterbi();
return nodes.map(x => this.piece(x));
let node = prev.clone();
while (node.prev !== null) {
results.push(node.clone());
const n = node.clone();
node = n.prev.clone();
}
/**
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
*/
tokenIds() {
const nodes = this.viterbi();
return nodes.map(x => x.tokenId);
}
results.reverse();
return results;
}
/**
* @param {TokenLatticeNode} node
* @returns {string} The array of nodes representing the most likely sequence of tokens.
*/
piece(node) {
return this.sentence.slice(node.pos, node.pos + node.length);
}
/**
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
*/
tokens() {
const nodes = this.viterbi();
return nodes.map((x) => this.piece(x));
}
/**
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
*/
tokenIds() {
const nodes = this.viterbi();
return nodes.map((x) => x.tokenId);
}
}
class TokenLatticeNode {
/**
* Represents a node in a token lattice for a given sentence.
* @param {number} tokenId The ID of the token associated with this node.
* @param {number} nodeId The ID of this node.
* @param {number} pos The starting position of the token in the sentence.
* @param {number} length The length of the token.
* @param {number} score The score associated with the token.
*/
constructor(tokenId, nodeId, pos, length, score) {
this.tokenId = tokenId;
this.nodeId = nodeId;
this.pos = pos;
this.length = length;
this.score = score;
this.prev = null;
this.backtraceScore = 0.0;
}
/**
* Represents a node in a token lattice for a given sentence.
* @param {number} tokenId The ID of the token associated with this node.
* @param {number} nodeId The ID of this node.
* @param {number} pos The starting position of the token in the sentence.
* @param {number} length The length of the token.
* @param {number} score The score associated with the token.
*/
constructor(tokenId, nodeId, pos, length, score) {
this.tokenId = tokenId;
this.nodeId = nodeId;
this.pos = pos;
this.length = length;
this.score = score;
this.prev = null;
this.backtraceScore = 0.0;
}
/**
* Returns a clone of this node.
* @returns {TokenLatticeNode} A clone of this node.
*/
clone() {
const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);
n.prev = this.prev;
n.backtraceScore = this.backtraceScore;
return n;
}
/**
* Returns a clone of this node.
* @returns {TokenLatticeNode} A clone of this node.
*/
clone() {
const n = new TokenLatticeNode(
this.tokenId,
this.nodeId,
this.pos,
this.length,
this.score,
);
n.prev = this.prev;
n.backtraceScore = this.backtraceScore;
return n;
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,5 @@
/** @type {import('onnxruntime-web')} The ONNX runtime module. */
export let ONNX: typeof ONNX_WEB;
export const executionProviders: string[];
import * as ONNX_WEB from 'onnxruntime-web';
//# sourceMappingURL=onnx.d.ts.map
import * as ONNX_WEB from "onnxruntime-web";
//# sourceMappingURL=onnx.d.ts.map

View file

@ -3,23 +3,32 @@
* [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).
*/
export class PretrainedConfig {
/**
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
*
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
* @param {PretrainedOptions} options Additional options for loading the config.
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
*
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
*/
static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, }?: PretrainedOptions): Promise<PretrainedConfig>;
/**
* Create a new PreTrainedTokenizer instance.
* @param {Object} configJSON The JSON of the config.
*/
constructor(configJSON: any);
model_type: any;
is_encoder_decoder: boolean;
/**
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
*
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
* @param {PretrainedOptions} options Additional options for loading the config.
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
*
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
*/
static from_pretrained(
pretrained_model_name_or_path: string,
{
progress_callback,
config,
cache_dir,
local_files_only,
revision,
}?: PretrainedOptions,
): Promise<PretrainedConfig>;
/**
* Create a new PreTrainedTokenizer instance.
* @param {Object} configJSON The JSON of the config.
*/
constructor(configJSON: any);
model_type: any;
is_encoder_decoder: boolean;
}
/**
* Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.
@ -28,16 +37,25 @@ export class PretrainedConfig {
* let config = await AutoConfig.from_pretrained('bert-base-uncased');
*/
export class AutoConfig {
/**
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
*
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
* @param {PretrainedOptions} options Additional options for loading the config.
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
*
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
*/
static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, }?: import("./utils/hub.js").PretrainedOptions): Promise<PretrainedConfig>;
/**
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
*
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
* @param {PretrainedOptions} options Additional options for loading the config.
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
*
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
*/
static from_pretrained(
pretrained_model_name_or_path: string,
{
progress_callback,
config,
cache_dir,
local_files_only,
revision,
}?: import("./utils/hub.js").PretrainedOptions,
): Promise<PretrainedConfig>;
}
export type PretrainedOptions = import('./utils/hub.js').PretrainedOptions;
//# sourceMappingURL=configs.d.ts.map
export type PretrainedOptions = import("./utils/hub.js").PretrainedOptions;
//# sourceMappingURL=configs.d.ts.map

View file

@ -1,21 +1,21 @@
export namespace env {
export namespace backends {
export { onnx_env as onnx };
export let tfjs: {};
}
export { __dirname };
export { VERSION as version };
export let allowRemoteModels: boolean;
export let remoteHost: string;
export let remotePathTemplate: string;
export let allowLocalModels: boolean;
export { localModelPath };
export { FS_AVAILABLE as useFS };
export { WEB_CACHE_AVAILABLE as useBrowserCache };
export { FS_AVAILABLE as useFSCache };
export { DEFAULT_CACHE_DIR as cacheDir };
export let useCustomCache: boolean;
export let customCache: any;
export namespace backends {
export { onnx_env as onnx };
export let tfjs: {};
}
export { __dirname };
export { VERSION as version };
export let allowRemoteModels: boolean;
export let remoteHost: string;
export let remotePathTemplate: string;
export let allowLocalModels: boolean;
export { localModelPath };
export { FS_AVAILABLE as useFS };
export { WEB_CACHE_AVAILABLE as useBrowserCache };
export { FS_AVAILABLE as useFSCache };
export { DEFAULT_CACHE_DIR as cacheDir };
export let useCustomCache: boolean;
export let customCache: any;
}
declare const onnx_env: import("onnxruntime-common").Env;
declare const __dirname: any;
@ -25,4 +25,4 @@ declare const FS_AVAILABLE: boolean;
declare const WEB_CACHE_AVAILABLE: boolean;
declare const DEFAULT_CACHE_DIR: any;
export {};
//# sourceMappingURL=env.d.ts.map
//# sourceMappingURL=env.d.ts.map

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -8,4 +8,4 @@ export * from "./utils/audio.js";
export * from "./utils/image.js";
export * from "./utils/tensor.js";
export * from "./utils/maths.js";
//# sourceMappingURL=transformers.d.ts.map
//# sourceMappingURL=transformers.d.ts.map

View file

@ -4,7 +4,10 @@
* @param {number} sampling_rate The sampling rate to use when decoding the audio.
* @returns {Promise<Float32Array>} The decoded audio as a `Float32Array`.
*/
export function read_audio(url: string | URL, sampling_rate: number): Promise<Float32Array>;
export function read_audio(
url: string | URL,
sampling_rate: number,
): Promise<Float32Array>;
/**
* Generates a Hanning window of length M.
*
@ -29,7 +32,16 @@ export function hanning(M: number): Float64Array;
* @returns {number[][]} Triangular filter bank matrix, which is a 2D array of shape (`num_frequency_bins`, `num_mel_filters`).
* This is a projection matrix to go from a spectrogram to a mel spectrogram.
*/
export function mel_filter_bank(num_frequency_bins: number, num_mel_filters: number, min_frequency: number, max_frequency: number, sampling_rate: number, norm?: string, mel_scale?: string, triangularize_in_mel_space?: boolean): number[][];
export function mel_filter_bank(
num_frequency_bins: number,
num_mel_filters: number,
min_frequency: number,
max_frequency: number,
sampling_rate: number,
norm?: string,
mel_scale?: string,
triangularize_in_mel_space?: boolean,
): number[][];
/**
* Calculates a spectrogram over one waveform using the Short-Time Fourier Transform.
*
@ -81,7 +93,29 @@ export function mel_filter_bank(num_frequency_bins: number, num_mel_filters: num
* @param {boolean} [options.transpose=false] If `true`, the returned spectrogram will have shape `(num_frames, num_frequency_bins/num_mel_filters)`. If `false`, the returned spectrogram will have shape `(num_frequency_bins/num_mel_filters, num_frames)`.
* @returns {{data: Float32Array, dims: number[]}} Spectrogram of shape `(num_frequency_bins, length)` (regular spectrogram) or shape `(num_mel_filters, length)` (mel spectrogram).
*/
export function spectrogram(waveform: Float32Array | Float64Array, window: Float32Array | Float64Array, frame_length: number, hop_length: number, { fft_length, power, center, pad_mode, onesided, preemphasis, mel_filters, mel_floor, log_mel, reference, min_value, db_range, remove_dc_offset, max_num_frames, do_pad, transpose, }?: {
export function spectrogram(
waveform: Float32Array | Float64Array,
window: Float32Array | Float64Array,
frame_length: number,
hop_length: number,
{
fft_length,
power,
center,
pad_mode,
onesided,
preemphasis,
mel_filters,
mel_floor,
log_mel,
reference,
min_value,
db_range,
remove_dc_offset,
max_num_frames,
do_pad,
transpose,
}?: {
fft_length?: number;
power?: number;
center?: boolean;
@ -98,9 +132,10 @@ export function spectrogram(waveform: Float32Array | Float64Array, window: Float
max_num_frames?: number;
do_pad?: boolean;
transpose?: boolean;
}): {
data: Float32Array;
dims: number[];
},
): {
data: Float32Array;
dims: number[];
};
/**
* Returns an array containing the specified window.
@ -113,9 +148,17 @@ export function spectrogram(waveform: Float32Array | Float64Array, window: Float
* @param {boolean} [options.center=true] Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.
* @returns {Float64Array} The window of shape `(window_length,)` or `(frame_length,)`.
*/
export function window_function(window_length: number, name: string, { periodic, frame_length, center, }?: {
export function window_function(
window_length: number,
name: string,
{
periodic,
frame_length,
center,
}?: {
periodic?: boolean;
frame_length?: number;
center?: boolean;
}): Float64Array;
//# sourceMappingURL=audio.d.ts.map
},
): Float64Array;
//# sourceMappingURL=audio.d.ts.map

View file

@ -93,7 +93,7 @@ export function calculateReflectOffset(i: number, w: number): number;
* @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}
*/
export const Callable: new () => {
(...args: any[]): any;
_call(...args: any[]): any;
(...args: any[]): any;
_call(...args: any[]): any;
};
//# sourceMappingURL=core.d.ts.map
//# sourceMappingURL=core.d.ts.map

View file

@ -16,209 +16,215 @@
* - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)
*/
export class PriorityQueue {
/**
* Create a new PriorityQueue.
* @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
*/
constructor(comparator?: Function);
_heap: any[];
_comparator: Function;
/**
* The size of the queue
*/
get size(): number;
/**
* Check if the queue is empty.
* @returns {boolean} `true` if the queue is empty, `false` otherwise.
*/
isEmpty(): boolean;
/**
* Return the element with the highest priority in the queue.
* @returns {any} The highest priority element in the queue.
*/
peek(): any;
/**
* Add one or more elements to the queue.
* @param {...any} values The values to push into the queue.
* @returns {number} The new size of the queue.
*/
push(...values: any[]): number;
/**
* Add multiple elements to the queue.
* @param {any[]} values The values to push into the queue.
* @returns {number} The new size of the queue.
*/
extend(values: any[]): number;
/**
* Remove and return the element with the highest priority in the queue.
* @returns {any} The element with the highest priority in the queue.
*/
pop(): any;
/**
* Replace the element with the highest priority in the queue with a new value.
* @param {*} value The new value.
* @returns {*} The replaced value.
*/
replace(value: any): any;
/**
* Compute the index for the parent of the node at index `i`.
* @param {number} i The index of the node to get the parent of.
* @returns {number} The index of the parent node.
* @private
*/
private _parent;
/**
* Compute the index for the left child of the node at index `i`.
* @param {number} i The index of the node to get the left child of.
* @returns {number} The index of the left child.
* @private
*/
private _left;
/**
* Compute the index for the right child of the node at index `i`.
* @param {number} i The index of the node to get the right child of.
* @returns {number} The index of the right child.
* @private
*/
private _right;
/**
* Check if the element at index `i` is greater than the element at index `j`.
* @param {number} i The index of the first element to compare.
* @param {number} j The index of the second element to compare.
* @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
* @private
*/
private _greater;
/**
* Swap the elements at indices `i` and `j`.
* @param {number} i The index of the first element to swap.
* @param {number} j The index of the second element to swap.
* @private
*/
private _swap;
/**
* Maintain the heap property by updating positions in the heap,
* starting at the last element and moving up the heap.
* @private
*/
private _siftUp;
/**
* Maintain the heap property by updating positions in the heap,
* starting at the first element and moving down the heap.
* @private
*/
private _siftDown;
/**
* Create a new PriorityQueue.
* @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
*/
constructor(comparator?: Function);
_heap: any[];
_comparator: Function;
/**
* The size of the queue
*/
get size(): number;
/**
* Check if the queue is empty.
* @returns {boolean} `true` if the queue is empty, `false` otherwise.
*/
isEmpty(): boolean;
/**
* Return the element with the highest priority in the queue.
* @returns {any} The highest priority element in the queue.
*/
peek(): any;
/**
* Add one or more elements to the queue.
* @param {...any} values The values to push into the queue.
* @returns {number} The new size of the queue.
*/
push(...values: any[]): number;
/**
* Add multiple elements to the queue.
* @param {any[]} values The values to push into the queue.
* @returns {number} The new size of the queue.
*/
extend(values: any[]): number;
/**
* Remove and return the element with the highest priority in the queue.
* @returns {any} The element with the highest priority in the queue.
*/
pop(): any;
/**
* Replace the element with the highest priority in the queue with a new value.
* @param {*} value The new value.
* @returns {*} The replaced value.
*/
replace(value: any): any;
/**
* Compute the index for the parent of the node at index `i`.
* @param {number} i The index of the node to get the parent of.
* @returns {number} The index of the parent node.
* @private
*/
private _parent;
/**
* Compute the index for the left child of the node at index `i`.
* @param {number} i The index of the node to get the left child of.
* @returns {number} The index of the left child.
* @private
*/
private _left;
/**
* Compute the index for the right child of the node at index `i`.
* @param {number} i The index of the node to get the right child of.
* @returns {number} The index of the right child.
* @private
*/
private _right;
/**
* Check if the element at index `i` is greater than the element at index `j`.
* @param {number} i The index of the first element to compare.
* @param {number} j The index of the second element to compare.
* @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
* @private
*/
private _greater;
/**
* Swap the elements at indices `i` and `j`.
* @param {number} i The index of the first element to swap.
* @param {number} j The index of the second element to swap.
* @private
*/
private _swap;
/**
* Maintain the heap property by updating positions in the heap,
* starting at the last element and moving up the heap.
* @private
*/
private _siftUp;
/**
* Maintain the heap property by updating positions in the heap,
* starting at the first element and moving down the heap.
* @private
*/
private _siftDown;
}
/**
* A trie structure to efficiently store and search for strings.
*/
export class CharTrie {
root: CharTrieNode;
/**
* Adds one or more `texts` to the trie.
* @param {string[]} texts The strings to add to the trie.
*/
extend(texts: string[]): void;
/**
* Adds text to the trie.
* @param {string} text The string to add to the trie.
*/
push(text: string): void;
/**
* Searches the trie for all strings with a common prefix of `text`.
* @param {string} text The common prefix to search for.
* @yields {string} Each string in the trie that has `text` as a prefix.
*/
commonPrefixSearch(text: string): Generator<string, void, unknown>;
root: CharTrieNode;
/**
* Adds one or more `texts` to the trie.
* @param {string[]} texts The strings to add to the trie.
*/
extend(texts: string[]): void;
/**
* Adds text to the trie.
* @param {string} text The string to add to the trie.
*/
push(text: string): void;
/**
* Searches the trie for all strings with a common prefix of `text`.
* @param {string} text The common prefix to search for.
* @yields {string} Each string in the trie that has `text` as a prefix.
*/
commonPrefixSearch(text: string): Generator<string, void, unknown>;
}
/**
* A lattice data structure to be used for tokenization.
*/
export class TokenLattice {
/**
* Creates a new TokenLattice instance.
*
* @param {string} sentence The input sentence to be tokenized.
* @param {number} bosTokenId The beginning-of-sequence token ID.
* @param {number} eosTokenId The end-of-sequence token ID.
*/
constructor(sentence: string, bosTokenId: number, eosTokenId: number);
sentence: string;
len: number;
bosTokenId: number;
eosTokenId: number;
nodes: TokenLatticeNode[];
beginNodes: any[][];
endNodes: any[][];
/**
* Inserts a new token node into the token lattice.
*
* @param {number} pos The starting position of the token.
* @param {number} length The length of the token.
* @param {number} score The score of the token.
* @param {number} tokenId The token ID of the token.
*/
insert(pos: number, length: number, score: number, tokenId: number): void;
/**
* Implements the Viterbi algorithm to compute the most likely sequence of tokens.
*
* @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
*/
viterbi(): TokenLatticeNode[];
/**
* @param {TokenLatticeNode} node
* @returns {string} The array of nodes representing the most likely sequence of tokens.
*/
piece(node: TokenLatticeNode): string;
/**
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
*/
tokens(): any[];
/**
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
*/
tokenIds(): any[];
/**
* Creates a new TokenLattice instance.
*
* @param {string} sentence The input sentence to be tokenized.
* @param {number} bosTokenId The beginning-of-sequence token ID.
* @param {number} eosTokenId The end-of-sequence token ID.
*/
constructor(sentence: string, bosTokenId: number, eosTokenId: number);
sentence: string;
len: number;
bosTokenId: number;
eosTokenId: number;
nodes: TokenLatticeNode[];
beginNodes: any[][];
endNodes: any[][];
/**
* Inserts a new token node into the token lattice.
*
* @param {number} pos The starting position of the token.
* @param {number} length The length of the token.
* @param {number} score The score of the token.
* @param {number} tokenId The token ID of the token.
*/
insert(pos: number, length: number, score: number, tokenId: number): void;
/**
* Implements the Viterbi algorithm to compute the most likely sequence of tokens.
*
* @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
*/
viterbi(): TokenLatticeNode[];
/**
* @param {TokenLatticeNode} node
* @returns {string} The array of nodes representing the most likely sequence of tokens.
*/
piece(node: TokenLatticeNode): string;
/**
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
*/
tokens(): any[];
/**
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
*/
tokenIds(): any[];
}
/**
* Represents a node in a character trie.
*/
declare class CharTrieNode {
/**
* Returns a new `CharTrieNode` instance with default values.
* @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
*/
static default(): CharTrieNode;
/**
* Create a new CharTrieNode.
* @param {boolean} isLeaf Whether the node is a leaf node or not.
* @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
*/
constructor(isLeaf: boolean, children: Map<string, CharTrieNode>);
isLeaf: boolean;
children: Map<string, CharTrieNode>;
/**
* Returns a new `CharTrieNode` instance with default values.
* @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
*/
static default(): CharTrieNode;
/**
* Create a new CharTrieNode.
* @param {boolean} isLeaf Whether the node is a leaf node or not.
* @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
*/
constructor(isLeaf: boolean, children: Map<string, CharTrieNode>);
isLeaf: boolean;
children: Map<string, CharTrieNode>;
}
declare class TokenLatticeNode {
/**
* Represents a node in a token lattice for a given sentence.
* @param {number} tokenId The ID of the token associated with this node.
* @param {number} nodeId The ID of this node.
* @param {number} pos The starting position of the token in the sentence.
* @param {number} length The length of the token.
* @param {number} score The score associated with the token.
*/
constructor(tokenId: number, nodeId: number, pos: number, length: number, score: number);
tokenId: number;
nodeId: number;
pos: number;
length: number;
score: number;
prev: any;
backtraceScore: number;
/**
* Returns a clone of this node.
* @returns {TokenLatticeNode} A clone of this node.
*/
clone(): TokenLatticeNode;
/**
* Represents a node in a token lattice for a given sentence.
* @param {number} tokenId The ID of the token associated with this node.
* @param {number} nodeId The ID of this node.
* @param {number} pos The starting position of the token in the sentence.
* @param {number} length The length of the token.
* @param {number} score The score associated with the token.
*/
constructor(
tokenId: number,
nodeId: number,
pos: number,
length: number,
score: number,
);
tokenId: number;
nodeId: number;
pos: number;
length: number;
score: number;
prev: any;
backtraceScore: number;
/**
* Returns a clone of this node.
* @returns {TokenLatticeNode} A clone of this node.
*/
clone(): TokenLatticeNode;
}
export {};
//# sourceMappingURL=data-structures.d.ts.map
//# sourceMappingURL=data-structures.d.ts.map

View file

@ -1,6 +1,6 @@
declare const LogitsProcessorList_base: new () => {
(...args: any[]): any;
_call(...args: any[]): any;
(...args: any[]): any;
_call(...args: any[]): any;
};
/**
* A class representing a list of logits processors. A logits processor is a function that modifies the logits
@ -10,47 +10,47 @@ declare const LogitsProcessorList_base: new () => {
* @extends Callable
*/
export class LogitsProcessorList extends LogitsProcessorList_base {
processors: any[];
/**
* Adds a new logits processor to the list.
*
* @param {LogitsProcessor} item The logits processor function to add.
*/
push(item: LogitsProcessor): void;
/**
* Adds multiple logits processors to the list.
*
* @param {LogitsProcessor[]} items The logits processor functions to add.
*/
extend(items: LogitsProcessor[]): void;
/**
* Applies all logits processors in the list to a batch of logits, modifying them in-place.
*
* @param {number[]} input_ids The input IDs for the language model.
* @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single
* input sequence in the batch.
*/
_call(input_ids: number[], batchedLogits: number[][]): void;
[Symbol.iterator](): IterableIterator<any>;
processors: any[];
/**
* Adds a new logits processor to the list.
*
* @param {LogitsProcessor} item The logits processor function to add.
*/
push(item: LogitsProcessor): void;
/**
* Adds multiple logits processors to the list.
*
* @param {LogitsProcessor[]} items The logits processor functions to add.
*/
extend(items: LogitsProcessor[]): void;
/**
* Applies all logits processors in the list to a batch of logits, modifying them in-place.
*
* @param {number[]} input_ids The input IDs for the language model.
* @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single
* input sequence in the batch.
*/
_call(input_ids: number[], batchedLogits: number[][]): void;
[Symbol.iterator](): IterableIterator<any>;
}
declare const LogitsProcessor_base: new () => {
(...args: any[]): any;
_call(...args: any[]): any;
(...args: any[]): any;
_call(...args: any[]): any;
};
/**
* Base class for processing logits.
* @extends Callable
*/
export class LogitsProcessor extends LogitsProcessor_base {
/**
* Apply the processor to the input logits.
*
* @abstract
* @param {Array} input_ids The input ids.
* @param {Tensor} logits The logits to process.
* @throws {Error} Throws an error if `_call` is not implemented in the subclass.
*/
_call(input_ids: any[], logits: Tensor): void;
/**
* Apply the processor to the input logits.
*
* @abstract
* @param {Array} input_ids The input ids.
* @param {Tensor} logits The logits to process.
* @throws {Error} Throws an error if `_call` is not implemented in the subclass.
*/
_call(input_ids: any[], logits: Tensor): void;
}
/**
* A logits processor that forces a specific token to be generated by the decoder.
@ -58,42 +58,42 @@ export class LogitsProcessor extends LogitsProcessor_base {
* @extends LogitsProcessor
*/
export class ForceTokensLogitsProcessor extends LogitsProcessor {
/**
* Constructs a new instance of `ForceTokensLogitsProcessor`.
*
* @param {Array} forced_decoder_ids The ids of tokens that should be forced.
*/
constructor(forced_decoder_ids: any[]);
force_token_map: {
[k: string]: any;
};
/**
* Apply the processor to the input logits.
*
* @param {Array} input_ids The input ids.
* @param {Tensor} logits The logits to process.
* @returns {Tensor} The processed logits.
*/
_call(input_ids: any[], logits: Tensor): Tensor;
/**
* Constructs a new instance of `ForceTokensLogitsProcessor`.
*
* @param {Array} forced_decoder_ids The ids of tokens that should be forced.
*/
constructor(forced_decoder_ids: any[]);
force_token_map: {
[k: string]: any;
};
/**
* Apply the processor to the input logits.
*
* @param {Array} input_ids The input ids.
* @param {Tensor} logits The logits to process.
* @returns {Tensor} The processed logits.
*/
_call(input_ids: any[], logits: Tensor): Tensor;
}
/**
* A LogitsProcessor that forces a BOS token at the beginning of the generated sequence.
* @extends LogitsProcessor
*/
export class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {
/**
* Create a ForcedBOSTokenLogitsProcessor.
* @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.
*/
constructor(bos_token_id: number);
bos_token_id: number;
/**
* Apply the BOS token forcing to the logits.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The logits with BOS token forcing.
*/
_call(input_ids: any[], logits: any): any;
/**
* Create a ForcedBOSTokenLogitsProcessor.
* @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.
*/
constructor(bos_token_id: number);
bos_token_id: number;
/**
* Apply the BOS token forcing to the logits.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The logits with BOS token forcing.
*/
_call(input_ids: any[], logits: any): any;
}
/**
* A logits processor that forces end-of-sequence token probability to 1.
@ -101,21 +101,21 @@ export class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {
* @extends LogitsProcessor
*/
export class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {
/**
* Create a ForcedEOSTokenLogitsProcessor.
* @param {number} max_length Max length of the sequence.
* @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced.
*/
constructor(max_length: number, forced_eos_token_id: number | number[]);
max_length: number;
forced_eos_token_id: number | number[];
/**
* Apply the processor to input_ids and logits.
*
* @param {number[]} input_ids The input ids.
* @param {Tensor} logits The logits tensor.
*/
_call(input_ids: number[], logits: Tensor): void;
/**
* Create a ForcedEOSTokenLogitsProcessor.
* @param {number} max_length Max length of the sequence.
* @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced.
*/
constructor(max_length: number, forced_eos_token_id: number | number[]);
max_length: number;
forced_eos_token_id: number | number[];
/**
* Apply the processor to input_ids and logits.
*
* @param {number[]} input_ids The input ids.
* @param {Tensor} logits The logits tensor.
*/
_call(input_ids: number[], logits: Tensor): void;
}
/**
* A LogitsProcessor that suppresses a list of tokens as soon as the `generate` function starts
@ -124,53 +124,53 @@ export class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {
* @extends LogitsProcessor
*/
export class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {
/**
* Create a SuppressTokensAtBeginLogitsProcessor.
* @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.
* @param {number} begin_index The number of tokens to generate before suppressing tokens.
*/
constructor(begin_suppress_tokens: number[], begin_index: number);
begin_suppress_tokens: number[];
begin_index: number;
/**
* Apply the BOS token forcing to the logits.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The logits with BOS token forcing.
*/
_call(input_ids: any[], logits: any): any;
/**
* Create a SuppressTokensAtBeginLogitsProcessor.
* @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.
* @param {number} begin_index The number of tokens to generate before suppressing tokens.
*/
constructor(begin_suppress_tokens: number[], begin_index: number);
begin_suppress_tokens: number[];
begin_index: number;
/**
* Apply the BOS token forcing to the logits.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The logits with BOS token forcing.
*/
_call(input_ids: any[], logits: any): any;
}
/**
* A LogitsProcessor that handles adding timestamps to generated text.
* @extends LogitsProcessor
*/
export class WhisperTimeStampLogitsProcessor extends LogitsProcessor {
/**
* Constructs a new WhisperTimeStampLogitsProcessor.
* @param {Object} generate_config The config object passed to the `generate()` method of a transformer model.
* @param {number} generate_config.eos_token_id The ID of the end-of-sequence token.
* @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp.
* @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp.
* @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear.
*/
constructor(generate_config: {
eos_token_id: number;
no_timestamps_token_id: number;
forced_decoder_ids?: number[][];
max_initial_timestamp_index?: number;
});
/**
* Constructs a new WhisperTimeStampLogitsProcessor.
* @param {Object} generate_config The config object passed to the `generate()` method of a transformer model.
* @param {number} generate_config.eos_token_id The ID of the end-of-sequence token.
* @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp.
* @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp.
* @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear.
*/
constructor(generate_config: {
eos_token_id: number;
no_timestamps_token_id: number;
timestamp_begin: number;
begin_index: number;
max_initial_timestamp_index: number;
/**
* Modify the logits to handle timestamp tokens.
* @param {Array} input_ids The input sequence of tokens.
* @param {Tensor} logits The logits output by the model.
* @returns {Tensor} The modified logits.
*/
_call(input_ids: any[], logits: Tensor): Tensor;
forced_decoder_ids?: number[][];
max_initial_timestamp_index?: number;
});
eos_token_id: number;
no_timestamps_token_id: number;
timestamp_begin: number;
begin_index: number;
max_initial_timestamp_index: number;
/**
* Modify the logits to handle timestamp tokens.
* @param {Array} input_ids The input sequence of tokens.
* @param {Tensor} logits The logits output by the model.
* @returns {Tensor} The modified logits.
*/
_call(input_ids: any[], logits: Tensor): Tensor;
}
/**
* A logits processor that disallows ngrams of a certain size to be repeated.
@ -178,38 +178,41 @@ export class WhisperTimeStampLogitsProcessor extends LogitsProcessor {
* @extends LogitsProcessor
*/
export class NoRepeatNGramLogitsProcessor extends LogitsProcessor {
/**
* Create a NoRepeatNGramLogitsProcessor.
* @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.
*/
constructor(no_repeat_ngram_size: number);
no_repeat_ngram_size: number;
/**
* Generate n-grams from a sequence of token ids.
* @param {number[]} prevInputIds List of previous input ids
* @returns {Map<string, number[]>} Map of generated n-grams
*/
getNgrams(prevInputIds: number[]): Map<string, number[]>;
/**
* Generate n-grams from a sequence of token ids.
* @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
* @param {number[]} prevInputIds List of previous input ids
* @returns {number[]} Map of generated n-grams
*/
getGeneratedNgrams(bannedNgrams: Map<string, number[]>, prevInputIds: number[]): number[];
/**
* Calculate banned n-gram tokens
* @param {number[]} prevInputIds List of previous input ids
* @returns {number[]} Map of generated n-grams
*/
calcBannedNgramTokens(prevInputIds: number[]): number[];
/**
* Apply the no-repeat-ngram processor to the logits.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The logits with no-repeat-ngram processing.
*/
_call(input_ids: any[], logits: any): any;
/**
* Create a NoRepeatNGramLogitsProcessor.
* @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.
*/
constructor(no_repeat_ngram_size: number);
no_repeat_ngram_size: number;
/**
* Generate n-grams from a sequence of token ids.
* @param {number[]} prevInputIds List of previous input ids
* @returns {Map<string, number[]>} Map of generated n-grams
*/
getNgrams(prevInputIds: number[]): Map<string, number[]>;
/**
* Generate n-grams from a sequence of token ids.
* @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
* @param {number[]} prevInputIds List of previous input ids
* @returns {number[]} Map of generated n-grams
*/
getGeneratedNgrams(
bannedNgrams: Map<string, number[]>,
prevInputIds: number[],
): number[];
/**
* Calculate banned n-gram tokens
* @param {number[]} prevInputIds List of previous input ids
* @returns {number[]} Map of generated n-grams
*/
calcBannedNgramTokens(prevInputIds: number[]): number[];
/**
* Apply the no-repeat-ngram processor to the logits.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The logits with no-repeat-ngram processing.
*/
_call(input_ids: any[], logits: any): any;
}
/**
* A logits processor that penalises repeated output tokens.
@ -217,19 +220,19 @@ export class NoRepeatNGramLogitsProcessor extends LogitsProcessor {
* @extends LogitsProcessor
*/
export class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {
/**
* Create a RepetitionPenaltyLogitsProcessor.
* @param {number} penalty The penalty to apply for repeated tokens.
*/
constructor(penalty: number);
penalty: number;
/**
* Apply the repetition penalty to the logits.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The logits with repetition penalty processing.
*/
_call(input_ids: any[], logits: any): any;
/**
* Create a RepetitionPenaltyLogitsProcessor.
* @param {number} penalty The penalty to apply for repeated tokens.
*/
constructor(penalty: number);
penalty: number;
/**
* Apply the repetition penalty to the logits.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The logits with repetition penalty processing.
*/
_call(input_ids: any[], logits: any): any;
}
/**
* A logits processor that enforces a minimum number of tokens.
@ -237,21 +240,21 @@ export class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {
* @extends LogitsProcessor
*/
export class MinLengthLogitsProcessor extends LogitsProcessor {
/**
* Create a MinLengthLogitsProcessor.
* @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.
* @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
*/
constructor(min_length: number, eos_token_id: number | number[]);
min_length: number;
eos_token_id: number[];
/**
* Apply logit processor.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The processed logits.
*/
_call(input_ids: any[], logits: any): any;
/**
* Create a MinLengthLogitsProcessor.
* @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.
* @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
*/
constructor(min_length: number, eos_token_id: number | number[]);
min_length: number;
eos_token_id: number[];
/**
* Apply logit processor.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The processed logits.
*/
_call(input_ids: any[], logits: any): any;
}
/**
* A logits processor that enforces a minimum number of new tokens.
@ -259,40 +262,44 @@ export class MinLengthLogitsProcessor extends LogitsProcessor {
* @extends LogitsProcessor
*/
export class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {
/**
* Create a MinNewTokensLengthLogitsProcessor.
* @param {number} prompt_length_to_skip The input tokens length.
* @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.
* @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
*/
constructor(prompt_length_to_skip: number, min_new_tokens: number, eos_token_id: number | number[]);
prompt_length_to_skip: number;
min_new_tokens: number;
eos_token_id: number[];
/**
* Apply logit processor.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The processed logits.
*/
_call(input_ids: any[], logits: any): any;
/**
* Create a MinNewTokensLengthLogitsProcessor.
* @param {number} prompt_length_to_skip The input tokens length.
* @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.
* @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
*/
constructor(
prompt_length_to_skip: number,
min_new_tokens: number,
eos_token_id: number | number[],
);
prompt_length_to_skip: number;
min_new_tokens: number;
eos_token_id: number[];
/**
* Apply logit processor.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The processed logits.
*/
_call(input_ids: any[], logits: any): any;
}
export class NoBadWordsLogitsProcessor extends LogitsProcessor {
/**
* Create a `NoBadWordsLogitsProcessor`.
* @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.
* @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
*/
constructor(bad_words_ids: number[][], eos_token_id: number | number[]);
bad_words_ids: number[][];
eos_token_id: number[];
/**
* Apply logit processor.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The processed logits.
*/
_call(input_ids: any[], logits: any): any;
/**
* Create a `NoBadWordsLogitsProcessor`.
* @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.
* @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
*/
constructor(bad_words_ids: number[][], eos_token_id: number | number[]);
bad_words_ids: number[][];
eos_token_id: number[];
/**
* Apply logit processor.
* @param {Array} input_ids The input IDs.
* @param {Object} logits The logits.
* @returns {Object} The processed logits.
*/
_call(input_ids: any[], logits: any): any;
}
/**
* @typedef {Object} GenerationConfigType The default configuration parameters.
@ -355,239 +362,241 @@ export class NoBadWordsLogitsProcessor extends LogitsProcessor {
* Class that holds a configuration for a generation task.
* @type {new (kwargs?: GenerationConfigType) => GenerationConfigType}
*/
export const GenerationConfig: new (kwargs?: GenerationConfigType) => GenerationConfigType;
export const GenerationConfig: new (
kwargs?: GenerationConfigType,
) => GenerationConfigType;
declare const Sampler_base: new () => {
(...args: any[]): any;
_call(...args: any[]): any;
(...args: any[]): any;
_call(...args: any[]): any;
};
/**
* Sampler is a base class for all sampling methods used for text generation.
*/
export class Sampler extends Sampler_base {
/**
* Returns a Sampler object based on the specified options.
* @param {GenerationConfigType} generation_config An object containing options for the sampler.
* @returns {Sampler} A Sampler object.
*/
static getSampler(generation_config: GenerationConfigType): Sampler;
/**
* Creates a new Sampler object with the specified generation config.
* @param {GenerationConfigType} generation_config The generation config.
*/
constructor(generation_config: GenerationConfigType);
generation_config: GenerationConfigType;
/**
* Executes the sampler, using the specified logits.
* @param {Tensor} logits
* @param {number} index
* @returns {void}
*/
_call(logits: Tensor, index?: number): void;
/**
* Abstract method for sampling the logits.
* @param {Tensor} logits
* @param {number} index
* @throws {Error}
*/
sample(logits: Tensor, index: number): void;
/**
* Returns the specified logits as an array, with temperature applied.
* @param {Tensor} logits
* @param {number} index
* @returns {Float32Array}
*/
getLogits(logits: Tensor, index: number): Float32Array;
/**
* Selects an item randomly based on the specified probabilities.
* @param {Array} probabilities An array of probabilities to use for selection.
* @returns {number} The index of the selected item.
*/
randomSelect(probabilities: any[]): number;
/**
* Returns a Sampler object based on the specified options.
* @param {GenerationConfigType} generation_config An object containing options for the sampler.
* @returns {Sampler} A Sampler object.
*/
static getSampler(generation_config: GenerationConfigType): Sampler;
/**
* Creates a new Sampler object with the specified generation config.
* @param {GenerationConfigType} generation_config The generation config.
*/
constructor(generation_config: GenerationConfigType);
generation_config: GenerationConfigType;
/**
* Executes the sampler, using the specified logits.
* @param {Tensor} logits
* @param {number} index
* @returns {void}
*/
_call(logits: Tensor, index?: number): void;
/**
* Abstract method for sampling the logits.
* @param {Tensor} logits
* @param {number} index
* @throws {Error}
*/
sample(logits: Tensor, index: number): void;
/**
* Returns the specified logits as an array, with temperature applied.
* @param {Tensor} logits
* @param {number} index
* @returns {Float32Array}
*/
getLogits(logits: Tensor, index: number): Float32Array;
/**
* Selects an item randomly based on the specified probabilities.
* @param {Array} probabilities An array of probabilities to use for selection.
* @returns {number} The index of the selected item.
*/
randomSelect(probabilities: any[]): number;
}
/**
* The default configuration parameters.
*/
export type GenerationConfigType = {
/**
* The maximum length the generated tokens can have. Corresponds to the length of the input prompt + `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set.
*/
max_length?: number;
/**
* The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
*/
max_new_tokens?: number;
/**
* The minimum length of the sequence to be generated. Corresponds to the length of the input prompt + `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set.
*/
min_length?: number;
/**
* The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
*/
min_new_tokens?: number;
/**
* Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
* - `true`, where the generation stops as soon as there are `num_beams` complete candidates;
* - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates;
* - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).
*/
early_stopping?: boolean | "never";
/**
* The maximum amount of time you allow the computation to run for in seconds. Generation will still finish the current pass after allocated time has been passed.
*/
max_time?: number;
/**
* Whether or not to use sampling; use greedy decoding otherwise.
*/
do_sample?: boolean;
/**
* Number of beams for beam search. 1 means no beam search.
*/
num_beams?: number;
/**
* Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
*/
num_beam_groups?: number;
/**
* The values balance the model confidence and the degeneration penalty in contrastive search decoding.
*/
penalty_alpha?: number;
/**
* Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.
*/
use_cache?: boolean;
/**
* The value used to modulate the next token probabilities.
*/
temperature?: number;
/**
* The number of highest probability vocabulary tokens to keep for top-k-filtering.
*/
top_k?: number;
/**
* If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.
*/
top_p?: number;
/**
* Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.
*/
typical_p?: number;
/**
* If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
*/
epsilon_cutoff?: number;
/**
* Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
*/
eta_cutoff?: number;
/**
* This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
*/
diversity_penalty?: number;
/**
* The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
*/
repetition_penalty?: number;
/**
* The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
*/
encoder_repetition_penalty?: number;
/**
* Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.
*/
length_penalty?: number;
/**
* If set to int > 0, all ngrams of that size can only occur once.
*/
no_repeat_ngram_size?: number;
/**
* List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`.
*/
bad_words_ids?: number[][];
/**
* List of token ids that must be generated. If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.
*/
force_words_ids?: number[][] | number[][][];
/**
* Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.
*/
renormalize_logits?: boolean;
/**
* Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.
*/
constraints?: any[];
/**
* The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for multilingual models like mBART where the first generated token needs to be the target language token.
*/
forced_bos_token_id?: number;
/**
* The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a list to set multiple *end-of-sequence* tokens.
*/
forced_eos_token_id?: number | number[];
/**
* Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.
*/
remove_invalid_values?: boolean;
/**
* This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay.
*/
exponential_decay_length_penalty?: number[];
/**
* A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
*/
suppress_tokens?: number[];
/**
* A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
*/
begin_suppress_tokens?: number[];
/**
* A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token of index 123.
*/
forced_decoder_ids?: number[][];
/**
* The number of independently computed returned sequences for each element in the batch.
*/
num_return_sequences?: number;
/**
* Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
*/
output_attentions?: boolean;
/**
* Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
*/
output_hidden_states?: boolean;
/**
* Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
*/
output_scores?: boolean;
/**
* Whether or not to return a `ModelOutput` instead of a plain tuple.
*/
return_dict_in_generate?: boolean;
/**
* The id of the *padding* token.
*/
pad_token_id?: number;
/**
* The id of the *beginning-of-sequence* token.
*/
bos_token_id?: number;
/**
* The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
*/
eos_token_id?: number | number[];
/**
* If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.
*/
encoder_no_repeat_ngram_size?: number;
/**
* If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
*/
decoder_start_token_id?: number;
/**
* Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not present in `generate`'s signature will be used in the model forward pass.
*/
generation_kwargs?: any;
/**
* The maximum length the generated tokens can have. Corresponds to the length of the input prompt + `max_new_tokens`. Its effect is overridden by `max_new_tokens`, if also set.
*/
max_length?: number;
/**
* The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.
*/
max_new_tokens?: number;
/**
* The minimum length of the sequence to be generated. Corresponds to the length of the input prompt + `min_new_tokens`. Its effect is overridden by `min_new_tokens`, if also set.
*/
min_length?: number;
/**
* The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.
*/
min_new_tokens?: number;
/**
* Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
* - `true`, where the generation stops as soon as there are `num_beams` complete candidates;
* - `false`, where an heuristic is applied and the generation stops when is it very unlikely to find better candidates;
* - `"never"`, where the beam search procedure only stops when there cannot be better candidates (canonical beam search algorithm).
*/
early_stopping?: boolean | "never";
/**
* The maximum amount of time you allow the computation to run for in seconds. Generation will still finish the current pass after allocated time has been passed.
*/
max_time?: number;
/**
* Whether or not to use sampling; use greedy decoding otherwise.
*/
do_sample?: boolean;
/**
* Number of beams for beam search. 1 means no beam search.
*/
num_beams?: number;
/**
* Number of groups to divide `num_beams` into in order to ensure diversity among different groups of beams. See [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
*/
num_beam_groups?: number;
/**
* The values balance the model confidence and the degeneration penalty in contrastive search decoding.
*/
penalty_alpha?: number;
/**
* Whether or not the model should use the past last key/values attentions (if applicable to the model) to speed up decoding.
*/
use_cache?: boolean;
/**
* The value used to modulate the next token probabilities.
*/
temperature?: number;
/**
* The number of highest probability vocabulary tokens to keep for top-k-filtering.
*/
top_k?: number;
/**
* If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.
*/
top_p?: number;
/**
* Local typicality measures how similar the conditional probability of predicting a target token next is to the expected conditional probability of predicting a random token next, given the partial text already generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that add up to `typical_p` or higher are kept for generation. See [this paper](https://arxiv.org/pdf/2202.00666.pdf) for more details.
*/
typical_p?: number;
/**
* If set to float strictly between 0 and 1, only tokens with a conditional probability greater than `epsilon_cutoff` will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
*/
epsilon_cutoff?: number;
/**
* Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between 0 and 1, a token is only considered if it is greater than either `eta_cutoff` or `sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits)))`. The latter term is intuitively the expected next token probability, scaled by `sqrt(eta_cutoff)`. In the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. See [Truncation Sampling as Language Model Desmoothing](https://arxiv.org/abs/2210.15191) for more details.
*/
eta_cutoff?: number;
/**
* This value is subtracted from a beam's score if it generates a token same as any beam from other group at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is enabled.
*/
diversity_penalty?: number;
/**
* The parameter for repetition penalty. 1.0 means no penalty. See [this paper](https://arxiv.org/pdf/1909.05858.pdf) for more details.
*/
repetition_penalty?: number;
/**
* The parameter for encoder_repetition_penalty. An exponential penalty on sequences that are not in the original input. 1.0 means no penalty.
*/
encoder_repetition_penalty?: number;
/**
* Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to the sequence length, which in turn is used to divide the score of the sequence. Since the score is the log likelihood of the sequence (i.e. negative), `length_penalty` > 0.0 promotes longer sequences, while `length_penalty` < 0.0 encourages shorter sequences.
*/
length_penalty?: number;
/**
* If set to int > 0, all ngrams of that size can only occur once.
*/
no_repeat_ngram_size?: number;
/**
* List of token ids that are not allowed to be generated. In order to get the token ids of the words that should not appear in the generated text, use `(await tokenizer(bad_words, {add_prefix_space: true, add_special_tokens: false})).input_ids`.
*/
bad_words_ids?: number[][];
/**
* List of token ids that must be generated. If given a `number[][]`, this is treated as a simple list of words that must be included, the opposite to `bad_words_ids`. If given `number[][][]`, this triggers a [disjunctive constraint](https://github.com/huggingface/transformers/issues/14081), where one can allow different forms of each word.
*/
force_words_ids?: number[][] | number[][][];
/**
* Whether to renormalize the logits after applying all the logits processors or warpers (including the custom ones). It's highly recommended to set this flag to `true` as the search algorithms suppose the score logits are normalized but some logit processors or warpers break the normalization.
*/
renormalize_logits?: boolean;
/**
* Custom constraints that can be added to the generation to ensure that the output will contain the use of certain tokens as defined by `Constraint` objects, in the most sensible way possible.
*/
constraints?: any[];
/**
* The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful for multilingual models like mBART where the first generated token needs to be the target language token.
*/
forced_bos_token_id?: number;
/**
* The id of the token to force as the last generated token when `max_length` is reached. Optionally, use a list to set multiple *end-of-sequence* tokens.
*/
forced_eos_token_id?: number | number[];
/**
* Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to crash. Note that using `remove_invalid_values` can slow down generation.
*/
remove_invalid_values?: boolean;
/**
* This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been generated. The tuple shall consist of: `(start_index, decay_factor)` where `start_index` indicates where penalty starts and `decay_factor` represents the factor of exponential decay.
*/
exponential_decay_length_penalty?: number[];
/**
* A list of tokens that will be suppressed at generation. The `SupressTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
*/
suppress_tokens?: number[];
/**
* A list of tokens that will be suppressed at the beginning of the generation. The `SupressBeginTokens` logit processor will set their log probs to `-inf` so that they are not sampled.
*/
begin_suppress_tokens?: number[];
/**
* A list of pairs of integers which indicates a mapping from generation indices to token indices that will be forced before sampling. For example, `[[1, 123]]` means the second generated token will always be a token of index 123.
*/
forced_decoder_ids?: number[][];
/**
* The number of independently computed returned sequences for each element in the batch.
*/
num_return_sequences?: number;
/**
* Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more details.
*/
output_attentions?: boolean;
/**
* Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more details.
*/
output_hidden_states?: boolean;
/**
* Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
*/
output_scores?: boolean;
/**
* Whether or not to return a `ModelOutput` instead of a plain tuple.
*/
return_dict_in_generate?: boolean;
/**
* The id of the *padding* token.
*/
pad_token_id?: number;
/**
* The id of the *beginning-of-sequence* token.
*/
bos_token_id?: number;
/**
* The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
*/
eos_token_id?: number | number[];
/**
* If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the `decoder_input_ids`.
*/
encoder_no_repeat_ngram_size?: number;
/**
* If an encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
*/
decoder_start_token_id?: number;
/**
* Additional generation kwargs will be forwarded to the `generate` function of the model. Kwargs that are not present in `generate`'s signature will be used in the model forward pass.
*/
generation_kwargs?: any;
};
import { Tensor } from './tensor.js';
import { Tensor } from "./tensor.js";
export {};
//# sourceMappingURL=generation.d.ts.map

View file

@ -4,7 +4,9 @@
* @param {URL|string} urlOrPath The URL/path of the file to get.
* @returns {Promise<FileResponse|Response>} A promise that resolves to a FileResponse object (if the file is retrieved using the FileSystem API), or a Response object (if the file is retrieved using the Fetch API).
*/
export function getFile(urlOrPath: URL | string): Promise<FileResponse | Response>;
export function getFile(
urlOrPath: URL | string,
): Promise<FileResponse | Response>;
/**
*
* Retrieves a file from either a remote URL using the Fetch API or from the local file system using the FileSystem API.
@ -20,7 +22,12 @@ export function getFile(urlOrPath: URL | string): Promise<FileResponse | Respons
* @throws Will throw an error if the file is not found and `fatal` is true.
* @returns {Promise} A Promise that resolves with the file content as a buffer.
*/
export function getModelFile(path_or_repo_id: string, filename: string, fatal?: boolean, options?: PretrainedOptions): Promise<any>;
export function getModelFile(
path_or_repo_id: string,
filename: string,
fatal?: boolean,
options?: PretrainedOptions,
): Promise<any>;
/**
* Fetches a JSON file from a given path and file name.
*
@ -31,43 +38,48 @@ export function getModelFile(path_or_repo_id: string, filename: string, fatal?:
* @returns {Promise<Object>} The JSON data parsed into a JavaScript object.
* @throws Will throw an error if the file is not found and `fatal` is true.
*/
export function getModelJSON(modelPath: string, fileName: string, fatal?: boolean, options?: PretrainedOptions): Promise<any>;
export function getModelJSON(
modelPath: string,
fileName: string,
fatal?: boolean,
options?: PretrainedOptions,
): Promise<any>;
/**
* Options for loading a pretrained model.
*/
export type PretrainedOptions = {
/**
* Whether to load the 8-bit quantized version of the model (only applicable when loading model files).
*/
quantized?: boolean | null;
/**
* If specified, this function will be called during model construction, to provide the user with progress updates.
*/
progress_callback?: Function;
/**
* Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:
* - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).
* - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.
*/
config?: any;
/**
* Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.
*/
cache_dir?: string;
/**
* Whether or not to only look at local files (e.g., not try downloading the model).
*/
local_files_only?: boolean;
/**
* The specific model version to use. It can be a branch name, a tag name, or a commit id,
* since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
* NOTE: This setting is ignored for local requests.
*/
revision?: string;
/**
* If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.
*/
model_file_name?: string;
/**
* Whether to load the 8-bit quantized version of the model (only applicable when loading model files).
*/
quantized?: boolean | null;
/**
* If specified, this function will be called during model construction, to provide the user with progress updates.
*/
progress_callback?: Function;
/**
* Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when:
* - The model is a model provided by the library (loaded with the *model id* string of a pretrained model).
* - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory.
*/
config?: any;
/**
* Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.
*/
cache_dir?: string;
/**
* Whether or not to only look at local files (e.g., not try downloading the model).
*/
local_files_only?: boolean;
/**
* The specific model version to use. It can be a branch name, a tag name, or a commit id,
* since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
* NOTE: This setting is ignored for local requests.
*/
revision?: string;
/**
* If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.
*/
model_file_name?: string;
};
/**
* @typedef {Object} PretrainedOptions Options for loading a pretrained model.
@ -84,71 +96,71 @@ export type PretrainedOptions = {
* @property {string} [model_file_name=null] If specified, load the model with this name (excluding the .onnx suffix). Currently only valid for encoder- or decoder-only models.
*/
declare class FileResponse {
/**
* Creates a new `FileResponse` object.
* @param {string|URL} filePath
*/
constructor(filePath: string | URL);
/**
* Mapping from file extensions to MIME types.
*/
_CONTENT_TYPE_MAP: {
txt: string;
html: string;
css: string;
js: string;
json: string;
png: string;
jpg: string;
jpeg: string;
gif: string;
};
filePath: string | URL;
headers: Headers;
exists: any;
status: number;
statusText: string;
body: ReadableStream<any>;
/**
* Updates the 'content-type' header property of the response based on the extension of
* the file specified by the filePath property of the current object.
* @returns {void}
*/
updateContentType(): void;
/**
* Clone the current FileResponse object.
* @returns {FileResponse} A new FileResponse object with the same properties as the current object.
*/
clone(): FileResponse;
/**
* Reads the contents of the file specified by the filePath property and returns a Promise that
* resolves with an ArrayBuffer containing the file's contents.
* @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
* @throws {Error} If the file cannot be read.
*/
arrayBuffer(): Promise<ArrayBuffer>;
/**
* Reads the contents of the file specified by the filePath property and returns a Promise that
* resolves with a Blob containing the file's contents.
* @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.
* @throws {Error} If the file cannot be read.
*/
blob(): Promise<Blob>;
/**
* Reads the contents of the file specified by the filePath property and returns a Promise that
* resolves with a string containing the file's contents.
* @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.
* @throws {Error} If the file cannot be read.
*/
text(): Promise<string>;
/**
* Reads the contents of the file specified by the filePath property and returns a Promise that
* resolves with a parsed JavaScript object containing the file's contents.
*
* @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
* @throws {Error} If the file cannot be read.
*/
json(): Promise<any>;
/**
* Creates a new `FileResponse` object.
* @param {string|URL} filePath
*/
constructor(filePath: string | URL);
/**
* Mapping from file extensions to MIME types.
*/
_CONTENT_TYPE_MAP: {
txt: string;
html: string;
css: string;
js: string;
json: string;
png: string;
jpg: string;
jpeg: string;
gif: string;
};
filePath: string | URL;
headers: Headers;
exists: any;
status: number;
statusText: string;
body: ReadableStream<any>;
/**
* Updates the 'content-type' header property of the response based on the extension of
* the file specified by the filePath property of the current object.
* @returns {void}
*/
updateContentType(): void;
/**
* Clone the current FileResponse object.
* @returns {FileResponse} A new FileResponse object with the same properties as the current object.
*/
clone(): FileResponse;
/**
* Reads the contents of the file specified by the filePath property and returns a Promise that
* resolves with an ArrayBuffer containing the file's contents.
* @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
* @throws {Error} If the file cannot be read.
*/
arrayBuffer(): Promise<ArrayBuffer>;
/**
* Reads the contents of the file specified by the filePath property and returns a Promise that
* resolves with a Blob containing the file's contents.
* @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.
* @throws {Error} If the file cannot be read.
*/
blob(): Promise<Blob>;
/**
* Reads the contents of the file specified by the filePath property and returns a Promise that
* resolves with a string containing the file's contents.
* @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.
* @throws {Error} If the file cannot be read.
*/
text(): Promise<string>;
/**
* Reads the contents of the file specified by the filePath property and returns a Promise that
* resolves with a parsed JavaScript object containing the file's contents.
*
* @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
* @throws {Error} If the file cannot be read.
*/
json(): Promise<any>;
}
export {};
//# sourceMappingURL=hub.d.ts.map
//# sourceMappingURL=hub.d.ts.map

View file

@ -1,111 +1,125 @@
export class RawImage {
/**
* Helper method for reading an image from a variety of input types.
* @param {RawImage|string|URL} input
* @returns The image object.
*
* **Example:** Read image from a URL.
* ```javascript
* let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
* // RawImage {
* // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],
* // "width": 800,
* // "height": 533,
* // "channels": 3
* // }
* ```
*/
static read(input: RawImage | string | URL): Promise<RawImage>;
/**
* Read an image from a URL or file path.
* @param {string|URL} url The URL or file path to read the image from.
* @returns {Promise<RawImage>} The image object.
*/
static fromURL(url: string | URL): Promise<RawImage>;
/**
* Helper method to create a new Image from a blob.
* @param {Blob} blob The blob to read the image from.
* @returns {Promise<RawImage>} The image object.
*/
static fromBlob(blob: Blob): Promise<RawImage>;
/**
* Helper method to create a new Image from a tensor
* @param {import('./tensor.js').Tensor} tensor
*/
static fromTensor(tensor: import('./tensor.js').Tensor, channel_format?: string): RawImage;
/**
* Create a new `RawImage` object.
* @param {Uint8ClampedArray|Uint8Array} data The pixel data.
* @param {number} width The width of the image.
* @param {number} height The height of the image.
* @param {1|2|3|4} channels The number of channels.
*/
constructor(data: Uint8ClampedArray | Uint8Array, width: number, height: number, channels: 1 | 2 | 3 | 4);
data: Uint8Array | Uint8ClampedArray;
width: number;
height: number;
channels: 2 | 1 | 3 | 4;
/**
* Returns the size of the image (width, height).
* @returns {[number, number]} The size of the image (width, height).
*/
get size(): [number, number];
/**
* Convert the image to grayscale format.
* @returns {RawImage} `this` to support chaining.
*/
grayscale(): RawImage;
/**
* Convert the image to RGB format.
* @returns {RawImage} `this` to support chaining.
*/
rgb(): RawImage;
/**
* Convert the image to RGBA format.
* @returns {RawImage} `this` to support chaining.
*/
rgba(): RawImage;
/**
* Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.
* @param {number} width The width of the new image.
* @param {number} height The height of the new image.
* @param {Object} options Additional options for resizing.
* @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.
* @returns {Promise<RawImage>} `this` to support chaining.
*/
resize(width: number, height: number, { resample, }?: {
resample?: 0 | 1 | 2 | 3 | 4 | 5 | string;
}): Promise<RawImage>;
pad([left, right, top, bottom]: [any, any, any, any]): Promise<any>;
crop([x_min, y_min, x_max, y_max]: [any, any, any, any]): Promise<any>;
center_crop(crop_width: any, crop_height: any): Promise<any>;
toBlob(type?: string, quality?: number): Promise<any>;
toCanvas(): any;
/**
* Helper method to update the image data.
* @param {Uint8ClampedArray} data The new image data.
* @param {number} width The new width of the image.
* @param {number} height The new height of the image.
* @param {1|2|3|4|null} [channels] The new number of channels of the image.
* @private
*/
private _update;
/**
* Clone the image
* @returns {RawImage} The cloned image
*/
clone(): RawImage;
/**
* Helper method for converting image to have a certain number of channels
* @param {number} numChannels The number of channels. Must be 1, 3, or 4.
* @returns {RawImage} `this` to support chaining.
*/
convert(numChannels: number): RawImage;
/**
* Save the image to the given path.
* @param {string} path The path to save the image to.
*/
save(path: string): Promise<any>;
toSharp(): any;
/**
* Helper method for reading an image from a variety of input types.
* @param {RawImage|string|URL} input
* @returns The image object.
*
* **Example:** Read image from a URL.
* ```javascript
* let image = await RawImage.read('https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/football-match.jpg');
* // RawImage {
* // "data": Uint8ClampedArray [ 25, 25, 25, 19, 19, 19, ... ],
* // "width": 800,
* // "height": 533,
* // "channels": 3
* // }
* ```
*/
static read(input: RawImage | string | URL): Promise<RawImage>;
/**
* Read an image from a URL or file path.
* @param {string|URL} url The URL or file path to read the image from.
* @returns {Promise<RawImage>} The image object.
*/
static fromURL(url: string | URL): Promise<RawImage>;
/**
* Helper method to create a new Image from a blob.
* @param {Blob} blob The blob to read the image from.
* @returns {Promise<RawImage>} The image object.
*/
static fromBlob(blob: Blob): Promise<RawImage>;
/**
* Helper method to create a new Image from a tensor
* @param {import('./tensor.js').Tensor} tensor
*/
static fromTensor(
tensor: import("./tensor.js").Tensor,
channel_format?: string,
): RawImage;
/**
* Create a new `RawImage` object.
* @param {Uint8ClampedArray|Uint8Array} data The pixel data.
* @param {number} width The width of the image.
* @param {number} height The height of the image.
* @param {1|2|3|4} channels The number of channels.
*/
constructor(
data: Uint8ClampedArray | Uint8Array,
width: number,
height: number,
channels: 1 | 2 | 3 | 4,
);
data: Uint8Array | Uint8ClampedArray;
width: number;
height: number;
channels: 2 | 1 | 3 | 4;
/**
* Returns the size of the image (width, height).
* @returns {[number, number]} The size of the image (width, height).
*/
get size(): [number, number];
/**
* Convert the image to grayscale format.
* @returns {RawImage} `this` to support chaining.
*/
grayscale(): RawImage;
/**
* Convert the image to RGB format.
* @returns {RawImage} `this` to support chaining.
*/
rgb(): RawImage;
/**
* Convert the image to RGBA format.
* @returns {RawImage} `this` to support chaining.
*/
rgba(): RawImage;
/**
* Resize the image to the given dimensions. This method uses the canvas API to perform the resizing.
* @param {number} width The width of the new image.
* @param {number} height The height of the new image.
* @param {Object} options Additional options for resizing.
* @param {0|1|2|3|4|5|string} [options.resample] The resampling method to use.
* @returns {Promise<RawImage>} `this` to support chaining.
*/
resize(
width: number,
height: number,
{
resample,
}?: {
resample?: 0 | 1 | 2 | 3 | 4 | 5 | string;
},
): Promise<RawImage>;
pad([left, right, top, bottom]: [any, any, any, any]): Promise<any>;
crop([x_min, y_min, x_max, y_max]: [any, any, any, any]): Promise<any>;
center_crop(crop_width: any, crop_height: any): Promise<any>;
toBlob(type?: string, quality?: number): Promise<any>;
toCanvas(): any;
/**
* Helper method to update the image data.
* @param {Uint8ClampedArray} data The new image data.
* @param {number} width The new width of the image.
* @param {number} height The new height of the image.
* @param {1|2|3|4|null} [channels] The new number of channels of the image.
* @private
*/
private _update;
/**
* Clone the image
* @returns {RawImage} The cloned image
*/
clone(): RawImage;
/**
* Helper method for converting image to have a certain number of channels
* @param {number} numChannels The number of channels. Must be 1, 3, or 4.
* @returns {RawImage} `this` to support chaining.
*/
convert(numChannels: number): RawImage;
/**
* Save the image to the given path.
* @param {string} path The path to save the image to.
*/
save(path: string): Promise<any>;
toSharp(): any;
}
//# sourceMappingURL=image.d.ts.map
//# sourceMappingURL=image.d.ts.map

View file

@ -14,7 +14,13 @@
/**
* @param {TypedArray} input
*/
export function interpolate_data(input: TypedArray, [in_channels, in_height, in_width]: [any, any, any], [out_height, out_width]: [any, any], mode?: string, align_corners?: boolean): any;
export function interpolate_data(
input: TypedArray,
[in_channels, in_height, in_width]: [any, any, any],
[out_height, out_width]: [any, any],
mode?: string,
align_corners?: boolean,
): any;
/**
* Helper method to transpose a `AnyTypedArray` directly
* @template {AnyTypedArray} T
@ -23,7 +29,11 @@ export function interpolate_data(input: TypedArray, [in_channels, in_height, in_
* @param {number[]} axes
* @returns {[T, number[]]} The transposed array and the new shape.
*/
export function transpose_data<T extends AnyTypedArray>(array: T, dims: number[], axes: number[]): [T, number[]];
export function transpose_data<T extends AnyTypedArray>(
array: T,
dims: number[],
axes: number[],
): [T, number[]];
/**
* Compute the softmax of an array of numbers.
* @template {TypedArray|number[]} T
@ -51,7 +61,10 @@ export function dot(arr1: number[], arr2: number[]): number;
* @param {number|null} [top_k=0] The number of top items to return (default: 0 = return all)
* @returns {[number, any][]} The top k items, sorted by descending order
*/
export function getTopItems(items: any[] | TypedArray, top_k?: number | null): [number, any][];
export function getTopItems(
items: any[] | TypedArray,
top_k?: number | null,
): [number, any][];
/**
* Computes the cosine similarity between two arrays.
*
@ -94,15 +107,24 @@ export function medianFilter(data: AnyTypedArray, windowSize: number): any;
*/
export function round(num: number, decimals: number): number;
export class FFT {
constructor(fft_length: any);
fft_length: any;
isPowerOfTwo: boolean;
fft: P2FFT | NP2FFT;
outputBufferSize: number;
realTransform(out: any, input: any): void;
transform(out: any, input: any): void;
constructor(fft_length: any);
fft_length: any;
isPowerOfTwo: boolean;
fft: P2FFT | NP2FFT;
outputBufferSize: number;
realTransform(out: any, input: any): void;
transform(out: any, input: any): void;
}
export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array;
export type TypedArray =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array;
export type BigTypedArray = BigInt64Array | BigUint64Array;
export type AnyTypedArray = TypedArray | BigTypedArray;
/**
@ -113,140 +135,166 @@ export type AnyTypedArray = TypedArray | BigTypedArray;
* Code adapted from https://www.npmjs.com/package/fft.js
*/
declare class P2FFT {
/**
* @param {number} size The size of the input array. Must be a power of two larger than 1.
* @throws {Error} FFT size must be a power of two larger than 1.
*/
constructor(size: number);
size: number;
_csize: number;
table: Float64Array;
_width: number;
_bitrev: Int32Array;
/**
* Create a complex number array with size `2 * size`
*
* @returns {Float64Array} A complex number array with size `2 * size`
*/
createComplexArray(): Float64Array;
/**
* Converts a complex number representation stored in a Float64Array to an array of real numbers.
*
* @param {Float64Array} complex The complex number representation to be converted.
* @param {number[]} [storage] An optional array to store the result in.
* @returns {number[]} An array of real numbers representing the input complex number representation.
*/
fromComplexArray(complex: Float64Array, storage?: number[]): number[];
/**
* Convert a real-valued input array to a complex-valued output array.
* @param {Float64Array} input The real-valued input array.
* @param {Float64Array} [storage] Optional buffer to store the output array.
* @returns {Float64Array} The complex-valued output array.
*/
toComplexArray(input: Float64Array, storage?: Float64Array): Float64Array;
/**
* Completes the spectrum by adding its mirrored negative frequency components.
* @param {Float64Array} spectrum The input spectrum.
* @returns {void}
*/
completeSpectrum(spectrum: Float64Array): void;
/**
* Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.
*
* @param {Float64Array} out The output buffer to store the result.
* @param {Float64Array} data The input data to transform.
*
* @throws {Error} Input and output buffers must be different.
*
* @returns {void}
*/
transform(out: Float64Array, data: Float64Array): void;
/**
* Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.
* The input buffer must contain real values only, while the output buffer will contain complex values. The input and
* output buffers must be different.
*
* @param {Float64Array} out The output buffer.
* @param {Float64Array} data The input buffer containing real values.
*
* @throws {Error} If the input and output buffers are the same.
*/
realTransform(out: Float64Array, data: Float64Array): void;
/**
* Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.
* The `out` array must be a different buffer than the `data` array. The `out` array will contain the
* result of the transformation. The `data` array will not be modified.
*
* @param {Float64Array} out The output buffer for the transformed data.
* @param {Float64Array} data The input data to transform.
* @throws {Error} If `out` and `data` refer to the same buffer.
* @returns {void}
*/
inverseTransform(out: Float64Array, data: Float64Array): void;
/**
* Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.
*
* @param {Float64Array} out The output buffer for the transformed data.
* @param {Float64Array} data The input buffer of data to be transformed.
* @param {number} inv A scaling factor to apply to the transform.
* @returns {void}
*/
_transform4(out: Float64Array, data: Float64Array, inv: number): void;
/**
* Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.
*
* @param {Float64Array} data The input buffer of data to be transformed.
* @param {Float64Array} out The output buffer for the transformed data.
* @param {number} outOff The offset at which to write the output data.
* @param {number} off The offset at which to begin reading the input data.
* @param {number} step The step size for indexing the input data.
* @returns {void}
*/
_singleTransform2(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number): void;
/**
* Performs radix-4 transformation on input data of length 8
*
* @param {Float64Array} data Input data array of length 8
* @param {Float64Array} out Output data array of length 8
* @param {number} outOff Index of output array to start writing from
* @param {number} off Index of input array to start reading from
* @param {number} step Step size between elements in input array
* @param {number} inv Scaling factor for inverse transform
*
* @returns {void}
*/
_singleTransform4(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number, inv: number): void;
/**
* Real input radix-4 implementation
* @param {Float64Array} out Output array for the transformed data
* @param {Float64Array} data Input array of real data to be transformed
* @param {number} inv The scale factor used to normalize the inverse transform
*/
_realTransform4(out: Float64Array, data: Float64Array, inv: number): void;
/**
* Performs a single real input radix-2 transformation on the provided data
*
* @param {Float64Array} data The input data array
* @param {Float64Array} out The output data array
* @param {number} outOff The output offset
* @param {number} off The input offset
* @param {number} step The step
*
* @returns {void}
*/
_singleRealTransform2(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number): void;
/**
* Computes a single real-valued transform using radix-4 algorithm.
* This method is only called for len=8.
*
* @param {Float64Array} data The input data array.
* @param {Float64Array} out The output data array.
* @param {number} outOff The offset into the output array.
* @param {number} off The offset into the input array.
* @param {number} step The step size for the input array.
* @param {number} inv The value of inverse.
*/
_singleRealTransform4(data: Float64Array, out: Float64Array, outOff: number, off: number, step: number, inv: number): void;
/**
* @param {number} size The size of the input array. Must be a power of two larger than 1.
* @throws {Error} FFT size must be a power of two larger than 1.
*/
constructor(size: number);
size: number;
_csize: number;
table: Float64Array;
_width: number;
_bitrev: Int32Array;
/**
* Create a complex number array with size `2 * size`
*
* @returns {Float64Array} A complex number array with size `2 * size`
*/
createComplexArray(): Float64Array;
/**
* Converts a complex number representation stored in a Float64Array to an array of real numbers.
*
* @param {Float64Array} complex The complex number representation to be converted.
* @param {number[]} [storage] An optional array to store the result in.
* @returns {number[]} An array of real numbers representing the input complex number representation.
*/
fromComplexArray(complex: Float64Array, storage?: number[]): number[];
/**
* Convert a real-valued input array to a complex-valued output array.
* @param {Float64Array} input The real-valued input array.
* @param {Float64Array} [storage] Optional buffer to store the output array.
* @returns {Float64Array} The complex-valued output array.
*/
toComplexArray(input: Float64Array, storage?: Float64Array): Float64Array;
/**
* Completes the spectrum by adding its mirrored negative frequency components.
* @param {Float64Array} spectrum The input spectrum.
* @returns {void}
*/
completeSpectrum(spectrum: Float64Array): void;
/**
* Performs a Fast Fourier Transform (FFT) on the given input data and stores the result in the output buffer.
*
* @param {Float64Array} out The output buffer to store the result.
* @param {Float64Array} data The input data to transform.
*
* @throws {Error} Input and output buffers must be different.
*
* @returns {void}
*/
transform(out: Float64Array, data: Float64Array): void;
/**
* Performs a real-valued forward FFT on the given input buffer and stores the result in the given output buffer.
* The input buffer must contain real values only, while the output buffer will contain complex values. The input and
* output buffers must be different.
*
* @param {Float64Array} out The output buffer.
* @param {Float64Array} data The input buffer containing real values.
*
* @throws {Error} If the input and output buffers are the same.
*/
realTransform(out: Float64Array, data: Float64Array): void;
/**
* Performs an inverse FFT transformation on the given `data` array, and stores the result in `out`.
* The `out` array must be a different buffer than the `data` array. The `out` array will contain the
* result of the transformation. The `data` array will not be modified.
*
* @param {Float64Array} out The output buffer for the transformed data.
* @param {Float64Array} data The input data to transform.
* @throws {Error} If `out` and `data` refer to the same buffer.
* @returns {void}
*/
inverseTransform(out: Float64Array, data: Float64Array): void;
/**
* Performs a radix-4 implementation of a discrete Fourier transform on a given set of data.
*
* @param {Float64Array} out The output buffer for the transformed data.
* @param {Float64Array} data The input buffer of data to be transformed.
* @param {number} inv A scaling factor to apply to the transform.
* @returns {void}
*/
_transform4(out: Float64Array, data: Float64Array, inv: number): void;
/**
* Performs a radix-2 implementation of a discrete Fourier transform on a given set of data.
*
* @param {Float64Array} data The input buffer of data to be transformed.
* @param {Float64Array} out The output buffer for the transformed data.
* @param {number} outOff The offset at which to write the output data.
* @param {number} off The offset at which to begin reading the input data.
* @param {number} step The step size for indexing the input data.
* @returns {void}
*/
_singleTransform2(
data: Float64Array,
out: Float64Array,
outOff: number,
off: number,
step: number,
): void;
/**
* Performs radix-4 transformation on input data of length 8
*
* @param {Float64Array} data Input data array of length 8
* @param {Float64Array} out Output data array of length 8
* @param {number} outOff Index of output array to start writing from
* @param {number} off Index of input array to start reading from
* @param {number} step Step size between elements in input array
* @param {number} inv Scaling factor for inverse transform
*
* @returns {void}
*/
_singleTransform4(
data: Float64Array,
out: Float64Array,
outOff: number,
off: number,
step: number,
inv: number,
): void;
/**
* Real input radix-4 implementation
* @param {Float64Array} out Output array for the transformed data
* @param {Float64Array} data Input array of real data to be transformed
* @param {number} inv The scale factor used to normalize the inverse transform
*/
_realTransform4(out: Float64Array, data: Float64Array, inv: number): void;
/**
* Performs a single real input radix-2 transformation on the provided data
*
* @param {Float64Array} data The input data array
* @param {Float64Array} out The output data array
* @param {number} outOff The output offset
* @param {number} off The input offset
* @param {number} step The step
*
* @returns {void}
*/
_singleRealTransform2(
data: Float64Array,
out: Float64Array,
outOff: number,
off: number,
step: number,
): void;
/**
* Computes a single real-valued transform using radix-4 algorithm.
* This method is only called for len=8.
*
* @param {Float64Array} data The input data array.
* @param {Float64Array} out The output data array.
* @param {number} outOff The offset into the output array.
* @param {number} off The offset into the input array.
* @param {number} step The step size for the input array.
* @param {number} inv The value of inverse.
*/
_singleRealTransform4(
data: Float64Array,
out: Float64Array,
outOff: number,
off: number,
step: number,
inv: number,
): void;
}
/**
* NP2FFT class provides functionality for performing Fast Fourier Transform on arrays
@ -255,23 +303,23 @@ declare class P2FFT {
* For more information, see: https://math.stackexchange.com/questions/77118/non-power-of-2-ffts/77156#77156
*/
declare class NP2FFT {
/**
* Constructs a new NP2FFT object.
* @param {number} fft_length The length of the FFT
*/
constructor(fft_length: number);
bufferSize: number;
_a: number;
_chirpBuffer: Float64Array;
_buffer1: Float64Array;
_buffer2: Float64Array;
_outBuffer1: Float64Array;
_outBuffer2: Float64Array;
_slicedChirpBuffer: Float64Array;
_f: P2FFT;
_transform(output: any, input: any, real: any): void;
transform(output: any, input: any): void;
realTransform(output: any, input: any): void;
/**
* Constructs a new NP2FFT object.
* @param {number} fft_length The length of the FFT
*/
constructor(fft_length: number);
bufferSize: number;
_a: number;
_chirpBuffer: Float64Array;
_buffer1: Float64Array;
_buffer2: Float64Array;
_outBuffer1: Float64Array;
_outBuffer2: Float64Array;
_slicedChirpBuffer: Float64Array;
_f: P2FFT;
_transform(output: any, input: any, real: any): void;
transform(output: any, input: any): void;
realTransform(output: any, input: any): void;
}
export {};
//# sourceMappingURL=maths.d.ts.map
//# sourceMappingURL=maths.d.ts.map

View file

@ -13,14 +13,22 @@ export function transpose(tensor: any, axes: any[]): Tensor;
* @param {boolean} align_corners Whether to align corners.
* @returns {Tensor} The interpolated tensor.
*/
export function interpolate(input: Tensor, [out_height, out_width]: number[], mode?: string, align_corners?: boolean): Tensor;
export function interpolate(
input: Tensor,
[out_height, out_width]: number[],
mode?: string,
align_corners?: boolean,
): Tensor;
/**
* Perform mean pooling of the last hidden state followed by a normalization step.
* @param {Tensor} last_hidden_state Tensor of shape [batchSize, seqLength, embedDim]
* @param {Tensor} attention_mask Tensor of shape [batchSize, seqLength]
* @returns {Tensor} Returns a new Tensor of shape [batchSize, embedDim].
*/
export function mean_pooling(last_hidden_state: Tensor, attention_mask: Tensor): Tensor;
export function mean_pooling(
last_hidden_state: Tensor,
attention_mask: Tensor,
): Tensor;
/**
* Concatenates an array of tensors along a specified dimension.
* @param {Tensor[]} tensors The array of tensors to concatenate.
@ -43,7 +51,12 @@ export function stack(tensors: Tensor[], dim?: number): Tensor;
* @param {boolean} keepdim whether the output tensor has dim retained or not.
* @returns {Tensor[]} A tuple of (std, mean) tensors.
*/
export function std_mean(input: Tensor, dim?: number | null, correction?: number, keepdim?: boolean): Tensor[];
export function std_mean(
input: Tensor,
dim?: number | null,
correction?: number,
keepdim?: boolean,
): Tensor[];
/**
* Returns the mean value of each row of the input tensor in the given dimension dim.
* @param {Tensor} input the input tensor.
@ -51,7 +64,11 @@ export function std_mean(input: Tensor, dim?: number | null, correction?: number
* @param {boolean} keepdim whether the output tensor has dim retained or not.
* @returns A new tensor with means taken along the specified dimension.
*/
export function mean(input: Tensor, dim?: number | null, keepdim?: boolean): Tensor;
export function mean(
input: Tensor,
dim?: number | null,
keepdim?: boolean,
): Tensor;
/**
*
* Measures similarity between two temporal sequences (e.g., input audio and output tokens
@ -72,228 +89,236 @@ export function ones(size: number[]): Tensor;
*/
export function ones_like(tensor: Tensor): Tensor;
export class Tensor {
/**
* Create a new Tensor or copy an existing Tensor.
* @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
*/
constructor(...args: [DataType, DataArray, number[]] | [import('onnxruntime-common').Tensor]);
/** @type {number[]} Dimensions of the tensor. */
dims: number[];
/** @type {DataType} Type of the tensor. */
type: DataType;
/** @type {DataArray} The data stored in the tensor. */
data: DataArray;
/** @type {number} The number of elements in the tensor. */
size: number;
/**
* Index into a Tensor object.
* @param {number} index The index to access.
* @returns {Tensor} The data at the specified index.
*/
_getitem(index: number): Tensor;
/**
* @param {number|bigint} item The item to search for in the tensor
* @returns {number} The index of the first occurrence of item in the tensor data.
*/
indexOf(item: number | bigint): number;
/**
* @param {number} index
* @param {number} iterSize
* @param {any} iterDims
* @returns {Tensor}
*/
_subarray(index: number, iterSize: number, iterDims: any): Tensor;
/**
* Returns the value of this tensor as a standard JavaScript Number. This only works
* for tensors with one element. For other cases, see `Tensor.tolist()`.
* @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
* @throws {Error} If the tensor has more than one element.
*/
item(): number | bigint;
/**
* Convert tensor data to a n-dimensional JS list
* @returns {Array}
*/
tolist(): any[];
/**
* Return a new Tensor with the sigmoid function applied to each element.
* @returns {Tensor} The tensor with the sigmoid function applied.
*/
sigmoid(): Tensor;
/**
* Applies the sigmoid function to the tensor in place.
* @returns {Tensor} Returns `this`.
*/
sigmoid_(): Tensor;
/**
* Return a new Tensor with every element multiplied by a constant.
* @param {number} val The value to multiply by.
* @returns {Tensor} The new tensor.
*/
mul(val: number): Tensor;
/**
* Multiply the tensor by a constant in place.
* @param {number} val The value to multiply by.
* @returns {Tensor} Returns `this`.
*/
mul_(val: number): Tensor;
/**
* Return a new Tensor with every element added by a constant.
* @param {number} val The value to add by.
* @returns {Tensor} The new tensor.
*/
add(val: number): Tensor;
/**
* Add the tensor by a constant in place.
* @param {number} val The value to add by.
* @returns {Tensor} Returns `this`.
*/
add_(val: number): Tensor;
clone(): Tensor;
slice(...slices: any[]): Tensor;
/**
* Return a transposed version of this Tensor, according to the provided dimensions.
* @param {...number} dims Dimensions to transpose.
* @returns {Tensor} The transposed tensor.
*/
transpose(...dims: number[]): Tensor;
/**
* Returns the sum of each row of the input tensor in the given dimension dim.
*
* @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
* @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
* @returns The summed tensor
*/
sum(dim?: number, keepdim?: boolean): Tensor;
/**
* Returns the matrix norm or vector norm of a given tensor.
* @param {number|string} [p='fro'] The order of norm
* @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
* If dim is None, the norm will be calculated across all dimensions of input.
* @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
* @returns {Tensor} The norm of the tensor.
*/
norm(p?: number | string, dim?: number, keepdim?: boolean): Tensor;
/**
* Performs `L_p` normalization of inputs over specified dimension. Operates in place.
* @param {number} [p=2] The exponent value in the norm formulation
* @param {number} [dim=1] The dimension to reduce
* @returns {Tensor} `this` for operation chaining.
*/
normalize_(p?: number, dim?: number): Tensor;
/**
* Performs `L_p` normalization of inputs over specified dimension.
* @param {number} [p=2] The exponent value in the norm formulation
* @param {number} [dim=1] The dimension to reduce
* @returns {Tensor} The normalized tensor.
*/
normalize(p?: number, dim?: number): Tensor;
/**
* Compute and return the stride of this tensor.
* Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
* @returns {number[]} The stride of this tensor.
*/
stride(): number[];
/**
* Returns a tensor with all specified dimensions of input of size 1 removed.
*
* NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
* If you would like a copy, use `tensor.clone()` before squeezing.
*
* @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.
* @returns The squeezed tensor
*/
squeeze(dim?: number): Tensor;
/**
* In-place version of @see {@link Tensor.squeeze}
*/
squeeze_(dim?: any): this;
/**
* Returns a new tensor with a dimension of size one inserted at the specified position.
*
* NOTE: The returned tensor shares the same underlying data with this tensor.
*
* @param {number} dim The index at which to insert the singleton dimension
* @returns The unsqueezed tensor
*/
unsqueeze(dim?: number): Tensor;
/**
* In-place version of @see {@link Tensor.unsqueeze}
*/
unsqueeze_(dim?: any): this;
/**
* In-place version of @see {@link Tensor.flatten}
*/
flatten_(start_dim?: number, end_dim?: number): this;
/**
* Flattens input by reshaping it into a one-dimensional tensor.
* If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
* and ending with `end_dim` are flattened. The order of elements in input is unchanged.
* @param {number} start_dim the first dim to flatten
* @param {number} end_dim the last dim to flatten
* @returns The flattened tensor.
*/
flatten(start_dim?: number, end_dim?: number): Tensor;
/**
* Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
* @param {...number} dims the desired size
* @returns {Tensor} The tensor with the same data but different shape
*/
view(...dims: number[]): Tensor;
neg_(): this;
neg(): Tensor;
/**
* In-place version of @see {@link Tensor.clamp}
*/
clamp_(min: any, max: any): this;
/**
* Clamps all elements in input into the range [ min, max ]
* @param {number} min lower-bound of the range to be clamped to
* @param {number} max upper-bound of the range to be clamped to
* @returns the output tensor.
*/
clamp(min: number, max: number): Tensor;
/**
* In-place version of @see {@link Tensor.round}
*/
round_(): this;
/**
* Rounds elements of input to the nearest integer.
* @returns the output tensor.
*/
round(): Tensor;
/**
* Performs Tensor dtype conversion.
* @param {DataType} type The desired data type.
* @returns {Tensor} The converted tensor.
*/
to(type: DataType): Tensor;
/**
* Returns an iterator object for iterating over the tensor data in row-major order.
* If the tensor has more than one dimension, the iterator will yield subarrays.
* @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
*/
[Symbol.iterator](): Iterator<any, any, undefined>;
/**
* Create a new Tensor or copy an existing Tensor.
* @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
*/
constructor(
...args:
| [DataType, DataArray, number[]]
| [import("onnxruntime-common").Tensor]
);
/** @type {number[]} Dimensions of the tensor. */
dims: number[];
/** @type {DataType} Type of the tensor. */
type: DataType;
/** @type {DataArray} The data stored in the tensor. */
data: DataArray;
/** @type {number} The number of elements in the tensor. */
size: number;
/**
* Index into a Tensor object.
* @param {number} index The index to access.
* @returns {Tensor} The data at the specified index.
*/
_getitem(index: number): Tensor;
/**
* @param {number|bigint} item The item to search for in the tensor
* @returns {number} The index of the first occurrence of item in the tensor data.
*/
indexOf(item: number | bigint): number;
/**
* @param {number} index
* @param {number} iterSize
* @param {any} iterDims
* @returns {Tensor}
*/
_subarray(index: number, iterSize: number, iterDims: any): Tensor;
/**
* Returns the value of this tensor as a standard JavaScript Number. This only works
* for tensors with one element. For other cases, see `Tensor.tolist()`.
* @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
* @throws {Error} If the tensor has more than one element.
*/
item(): number | bigint;
/**
* Convert tensor data to a n-dimensional JS list
* @returns {Array}
*/
tolist(): any[];
/**
* Return a new Tensor with the sigmoid function applied to each element.
* @returns {Tensor} The tensor with the sigmoid function applied.
*/
sigmoid(): Tensor;
/**
* Applies the sigmoid function to the tensor in place.
* @returns {Tensor} Returns `this`.
*/
sigmoid_(): Tensor;
/**
* Return a new Tensor with every element multiplied by a constant.
* @param {number} val The value to multiply by.
* @returns {Tensor} The new tensor.
*/
mul(val: number): Tensor;
/**
* Multiply the tensor by a constant in place.
* @param {number} val The value to multiply by.
* @returns {Tensor} Returns `this`.
*/
mul_(val: number): Tensor;
/**
* Return a new Tensor with every element added by a constant.
* @param {number} val The value to add by.
* @returns {Tensor} The new tensor.
*/
add(val: number): Tensor;
/**
* Add the tensor by a constant in place.
* @param {number} val The value to add by.
* @returns {Tensor} Returns `this`.
*/
add_(val: number): Tensor;
clone(): Tensor;
slice(...slices: any[]): Tensor;
/**
* Return a transposed version of this Tensor, according to the provided dimensions.
* @param {...number} dims Dimensions to transpose.
* @returns {Tensor} The transposed tensor.
*/
transpose(...dims: number[]): Tensor;
/**
* Returns the sum of each row of the input tensor in the given dimension dim.
*
* @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
* @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
* @returns The summed tensor
*/
sum(dim?: number, keepdim?: boolean): Tensor;
/**
* Returns the matrix norm or vector norm of a given tensor.
* @param {number|string} [p='fro'] The order of norm
* @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
* If dim is None, the norm will be calculated across all dimensions of input.
* @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
* @returns {Tensor} The norm of the tensor.
*/
norm(p?: number | string, dim?: number, keepdim?: boolean): Tensor;
/**
* Performs `L_p` normalization of inputs over specified dimension. Operates in place.
* @param {number} [p=2] The exponent value in the norm formulation
* @param {number} [dim=1] The dimension to reduce
* @returns {Tensor} `this` for operation chaining.
*/
normalize_(p?: number, dim?: number): Tensor;
/**
* Performs `L_p` normalization of inputs over specified dimension.
* @param {number} [p=2] The exponent value in the norm formulation
* @param {number} [dim=1] The dimension to reduce
* @returns {Tensor} The normalized tensor.
*/
normalize(p?: number, dim?: number): Tensor;
/**
* Compute and return the stride of this tensor.
* Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
* @returns {number[]} The stride of this tensor.
*/
stride(): number[];
/**
* Returns a tensor with all specified dimensions of input of size 1 removed.
*
* NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
* If you would like a copy, use `tensor.clone()` before squeezing.
*
* @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.
* @returns The squeezed tensor
*/
squeeze(dim?: number): Tensor;
/**
* In-place version of @see {@link Tensor.squeeze}
*/
squeeze_(dim?: any): this;
/**
* Returns a new tensor with a dimension of size one inserted at the specified position.
*
* NOTE: The returned tensor shares the same underlying data with this tensor.
*
* @param {number} dim The index at which to insert the singleton dimension
* @returns The unsqueezed tensor
*/
unsqueeze(dim?: number): Tensor;
/**
* In-place version of @see {@link Tensor.unsqueeze}
*/
unsqueeze_(dim?: any): this;
/**
* In-place version of @see {@link Tensor.flatten}
*/
flatten_(start_dim?: number, end_dim?: number): this;
/**
* Flattens input by reshaping it into a one-dimensional tensor.
* If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
* and ending with `end_dim` are flattened. The order of elements in input is unchanged.
* @param {number} start_dim the first dim to flatten
* @param {number} end_dim the last dim to flatten
* @returns The flattened tensor.
*/
flatten(start_dim?: number, end_dim?: number): Tensor;
/**
* Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
* @param {...number} dims the desired size
* @returns {Tensor} The tensor with the same data but different shape
*/
view(...dims: number[]): Tensor;
neg_(): this;
neg(): Tensor;
/**
* In-place version of @see {@link Tensor.clamp}
*/
clamp_(min: any, max: any): this;
/**
* Clamps all elements in input into the range [ min, max ]
* @param {number} min lower-bound of the range to be clamped to
* @param {number} max upper-bound of the range to be clamped to
* @returns the output tensor.
*/
clamp(min: number, max: number): Tensor;
/**
* In-place version of @see {@link Tensor.round}
*/
round_(): this;
/**
* Rounds elements of input to the nearest integer.
* @returns the output tensor.
*/
round(): Tensor;
/**
* Performs Tensor dtype conversion.
* @param {DataType} type The desired data type.
* @returns {Tensor} The converted tensor.
*/
to(type: DataType): Tensor;
/**
* Returns an iterator object for iterating over the tensor data in row-major order.
* If the tensor has more than one dimension, the iterator will yield subarrays.
* @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
*/
[Symbol.iterator](): Iterator<any, any, undefined>;
}
/**
* This creates a nested array of a given type and depth (see examples).
*/
export type NestArray<T, Depth extends number, Acc extends never[] = []> = Acc['length'] extends Depth ? T : NestArray<T[], Depth, [...Acc, never]>;
export type NestArray<
T,
Depth extends number,
Acc extends never[] = [],
> = Acc["length"] extends Depth ? T : NestArray<T[], Depth, [...Acc, never]>;
export type DataType = keyof typeof DataTypeMap;
export type DataArray = import('./maths.js').AnyTypedArray | any[];
export type DataArray = import("./maths.js").AnyTypedArray | any[];
declare const DataTypeMap: Readonly<{
float32: Float32ArrayConstructor;
float64: Float64ArrayConstructor;
string: ArrayConstructor;
int8: Int8ArrayConstructor;
uint8: Uint8ArrayConstructor;
int16: Int16ArrayConstructor;
uint16: Uint16ArrayConstructor;
int32: Int32ArrayConstructor;
uint32: Uint32ArrayConstructor;
int64: BigInt64ArrayConstructor;
uint64: BigUint64ArrayConstructor;
bool: Uint8ArrayConstructor;
float32: Float32ArrayConstructor;
float64: Float64ArrayConstructor;
string: ArrayConstructor;
int8: Int8ArrayConstructor;
uint8: Uint8ArrayConstructor;
int16: Int16ArrayConstructor;
uint16: Uint16ArrayConstructor;
int32: Int32ArrayConstructor;
uint32: Uint32ArrayConstructor;
int64: BigInt64ArrayConstructor;
uint64: BigUint64ArrayConstructor;
bool: Uint8ArrayConstructor;
}>;
export {};
//# sourceMappingURL=tensor.d.ts.map
//# sourceMappingURL=tensor.d.ts.map

View file

@ -1,3 +1,3 @@
module.exports = {
presets: [require.resolve('@docusaurus/core/lib/babel/preset')],
presets: [require.resolve("@docusaurus/core/lib/babel/preset")],
};

View file

@ -22,7 +22,7 @@ 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
## 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

View file

@ -7,6 +7,6 @@ sidebar_position: 3
You can use the same [methods to manually add context as Chat](../chat/context-selection.md).
In addition, tool call responses are automatically included as context items.
In addition, tool call responses are automatically included as context items.
This enables Agent mode to see the result of the previous action and decide what to do next.
This enables Agent mode to see the result of the previous action and decide what to do next.

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