Merge branch 'continuedev:main' into patch-4

This commit is contained in:
Huy Huynh 2025-07-20 14:54:00 -03:00 • committed by GitHub
commit bc72e45aa2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
98 changed files with 15575 additions and 2735 deletions

View file

@ -572,6 +572,43 @@ jobs:
cd packages/config-yaml
npm test
openai-adapters-tests:
needs: install-openai-adapters
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Run openai-adapters tests
run: |
cd packages/openai-adapters
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [install-root, install-vscode, install-config-yaml]
@ -613,6 +650,9 @@ jobs:
echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
echo "$FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
- name: Debug Outputs
run: |
@ -1068,6 +1108,7 @@ jobs:
- config-yaml-checks
- install-config-yaml
- install-openai-adapters
- openai-adapters-tests
steps:
- name: Decide whether the needed jobs succeeded or failed

View file

@ -6,6 +6,13 @@ on:
- main
paths:
- "packages/config-yaml/**"
- ".github/workflows/release-config-yaml.yml"
- ".github/workflows/reusable-release.yml"
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
@ -16,3 +23,12 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}

View file

@ -6,6 +6,13 @@ on:
- main
paths:
- "packages/fetch/**"
- ".github/workflows/release-fetch.yml"
- ".github/workflows/reusable-release.yml"
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
@ -16,3 +23,12 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}

View file

@ -16,3 +16,11 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}

View file

@ -6,6 +6,13 @@ on:
- main
paths:
- "packages/openai-adapters/**"
- ".github/workflows/release-openai-adapters.yml"
- ".github/workflows/reusable-release.yml"
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
@ -16,3 +23,12 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}

View file

@ -14,6 +14,24 @@ on:
required: true
SEMANTIC_RELEASE_NPM_TOKEN:
required: true
OPENAI_API_KEY:
required: false
ANTHROPIC_API_KEY:
required: false
GEMINI_API_KEY:
required: false
MISTRAL_API_KEY:
required: false
AZURE_OPENAI_API_KEY:
required: false
AZURE_FOUNDRY_CODESTRAL_API_KEY:
required: false
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY:
required: false
AZURE_OPENAI_GPT41_API_KEY:
required: false
VOYAGE_API_KEY:
required: false
permissions:
contents: write
@ -46,10 +64,20 @@ jobs:
- name: Run tests
run: npm test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
run: npx semantic-release
run: npx semantic-release

View file

@ -19,5 +19,13 @@
"max-depth": ["error", { "max": 6 }],
"max-nested-callbacks": ["error", { "max": 4 }],
"max-params": ["error", { "max": 8 }]
}
},
"overrides": [
{
"files": ["**/*.vitest.ts"],
"rules": {
"max-lines-per-function": "off"
}
}
]
}

View file

@ -24,6 +24,7 @@ import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
import { compactConversation } from "./util/conversationCompaction";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
@ -549,6 +550,28 @@ export class Core {
return await ChatDescriber.describe(currentModel, {}, msg.data.text);
});
on("conversation/compact", async (msg) => {
const currentModel = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
if (!currentModel) {
throw new Error("No chat model selected");
}
try {
await compactConversation({
sessionId: msg.data.sessionId,
index: msg.data.index,
historyManager,
currentModel,
});
return undefined;
} catch (error) {
console.error("Error compacting conversation:", error);
return undefined;
}
});
// Autocomplete
on("autocomplete/complete", async (msg) => {
const outcome =

42
core/index.d.ts vendored
View file

@ -369,10 +369,32 @@ export interface ThinkingChatMessage {
toolCalls?: ToolCallDelta[];
}
/**
* This is meant to be equivalent to the OpenAI [usage object](https://platform.openai.com/docs/api-reference/chat/object#chat/object-usage)
* but potentially with additional information that is needed for other providers.
*/
export interface Usage {
completionTokens: number;
promptTokens: number;
promptTokensDetails?: {
cachedTokens?: number;
/** This an Anthropic-specific property */
cacheWriteTokens?: number;
audioTokens?: number;
};
completionTokensDetails?: {
acceptedPredictionTokens?: number;
reasoningTokens?: number;
rejectedPredictionTokens?: number;
audioTokens?: number;
};
}
export interface AssistantChatMessage {
role: "assistant";
content: MessageContent;
toolCalls?: ToolCallDelta[];
usage?: Usage;
}
export interface SystemChatMessage {
@ -472,6 +494,7 @@ export interface ChatHistoryItem {
isGatheringContext?: boolean;
reasoning?: Reasoning;
appliedRules?: RuleWithSource[];
conversationSummary?: string;
}
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
@ -490,12 +513,14 @@ export interface LLMInteractionStartChat extends LLMInteractionBase {
kind: "startChat";
messages: ChatMessage[];
options: CompletionOptions;
provider: string;
}
export interface LLMInteractionStartComplete extends LLMInteractionBase {
kind: "startComplete";
prompt: string;
options: CompletionOptions;
provider: string;
}
export interface LLMInteractionStartFim extends LLMInteractionBase {
@ -503,6 +528,7 @@ export interface LLMInteractionStartFim extends LLMInteractionBase {
prefix: string;
suffix: string;
options: CompletionOptions;
provider: string;
}
export interface LLMInteractionChunk extends LLMInteractionBase {
@ -519,6 +545,7 @@ export interface LLMInteractionEnd extends LLMInteractionBase {
promptTokens: number;
generatedTokens: number;
thinkingTokens: number;
usage: Usage | undefined;
}
export interface LLMInteractionSuccess extends LLMInteractionEnd {
@ -1685,23 +1712,12 @@ export interface CompleteOnboardingPayload {
apiKey?: string;
}
export type PruningStatus = "deleted-last-input" | "pruned" | "not-pruned";
export interface CompiledMessagesResult {
compiledChatMessages: ChatMessage[];
pruningStatus: PruningStatus;
didPrune: boolean;
contextPercentage: number;
}
export interface MessageOption {
precompiled: boolean;
}
export type WarningMessageLevel = "warning" | "fatal";
export type WarningCategory = "exceeded-context-length" | "deleted-last-input";
export interface WarningMessage {
message: string;
level: WarningMessageLevel;
category: WarningCategory;
}

View file

@ -53,7 +53,7 @@ describe("DocsCrawler", () => {
};
}
describe("GitHub Crawler", () => {
describe.skip("GitHub Crawler", () => {
const repoUrl =
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";

View file

@ -5,7 +5,6 @@ import {
CompiledMessagesResult,
MessageContent,
MessagePart,
PruningStatus,
Tool,
} from "../index.js";
import { autodetectTemplateType } from "./autodetect.js";
@ -363,9 +362,6 @@ function getTokenCountingBufferSafety(contextLength: number) {
}
const MIN_RESPONSE_TOKENS = 1000;
function getMinResponseTokens(maxTokens: number) {
return Math.min(MIN_RESPONSE_TOKENS, maxTokens);
}
function pruneRawPromptFromTop(
modelName: string,
@ -425,6 +421,8 @@ function compileChatMessages({
supportsImages: boolean;
tools?: Tool[];
}): CompiledMessagesResult {
let didPrune = false;
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
// If images not supported, convert MessagePart[] to string
@ -446,22 +444,15 @@ function compileChatMessages({
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
while (msgsCopy.length > 1) {
if (isUserOrToolMsg(msgsCopy.at(-1))) {
break;
}
msgsCopy.pop();
// Extract the tool sequence from the end of the message array
const toolSequence = extractToolSequence(msgsCopy);
// Count tokens for all messages in the tool sequence
let lastMessagesTokens = 0;
for (const msg of toolSequence) {
lastMessagesTokens += countChatMessageTokens(modelName, msg);
}
// // Extract the tool sequence from the end of the message array
// const toolSequence = extractToolSequence(msgsCopy);
// // Count tokens for all messages in the tool sequence
// let lastMessagesTokens = 0;
// for (const msg of toolSequence) {
// lastMessagesTokens += countChatMessageTokens(modelName, msg);
// }
// System message
let systemMsgTokens = 0;
if (systemMsg) {
@ -475,7 +466,7 @@ function compileChatMessages({
}
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
const minOutputTokens = getMinResponseTokens(maxTokens);
const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens);
let inputTokensAvailable = contextLength;
@ -486,19 +477,19 @@ function compileChatMessages({
// Non-negotiable messages
inputTokensAvailable -= toolTokens;
inputTokensAvailable -= systemMsgTokens;
// inputTokensAvailable -= lastMessagesTokens;
inputTokensAvailable -= lastMessagesTokens;
// Make sure there's enough context for the non-excludable items
if (inputTokensAvailable < 0) {
throw new Error(
`Not enough context available to include the system message, last user message, and tools.
There must be at least ${minOutputTokens} tokens remaining for output.
Request had the following token counts:
- contextLength: ${contextLength}
- counting safety buffer: ${countingSafetyBuffer}
- tools: ~${toolTokens}
- system message: ~${systemMsgTokens}
- max output tokens: ${maxTokens}`,
There must be at least ${minOutputTokens} tokens remaining for output.
Request had the following token counts:
- contextLength: ${contextLength}
- counting safety buffer: ${countingSafetyBuffer}
- tools: ~${toolTokens}
- system message: ~${systemMsgTokens}
- max output tokens: ${maxTokens}`,
);
}
@ -513,12 +504,10 @@ function compileChatMessages({
};
});
let pruningStatus: PruningStatus = "not-pruned";
while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
const message = historyWithTokens.shift()!;
currentTotal -= message.tokens;
pruningStatus = "pruned";
didPrune = true;
// At this point make sure no latent tool response without corresponding call
while (historyWithTokens[0]?.role === "tool") {
@ -527,18 +516,24 @@ function compileChatMessages({
}
}
if (historyWithTokens.length === 0) {
pruningStatus = "deleted-last-input";
}
// Now reassemble
const reassembled: ChatMessage[] = [];
if (systemMsg) {
reassembled.push(systemMsg);
}
reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
reassembled.push(...toolSequence);
return { compiledChatMessages: reassembled, pruningStatus };
const inputTokens =
currentTotal + systemMsgTokens + toolTokens + lastMessagesTokens;
const availableTokens =
contextLength - countingSafetyBuffer - minOutputTokens;
const contextPercentage = inputTokens / availableTokens;
return {
compiledChatMessages: reassembled,
didPrune,
contextPercentage,
};
}
export {

View file

@ -28,6 +28,7 @@ import {
RequestOptions,
TabAutocompleteOptions,
TemplateType,
Usage,
} from "../index.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
@ -327,6 +328,7 @@ export abstract class BaseLLM implements ILLM {
completion: string,
thinking: string | undefined,
interaction: ILLMInteractionLog | undefined,
usage: Usage | undefined,
error?: any,
): InteractionStatus {
let promptTokens = this.countTokens(prompt);
@ -368,6 +370,7 @@ export abstract class BaseLLM implements ILLM {
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "cancelled";
} else {
@ -379,6 +382,7 @@ export abstract class BaseLLM implements ILLM {
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "error";
}
@ -388,6 +392,7 @@ export abstract class BaseLLM implements ILLM {
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "success";
}
@ -574,6 +579,7 @@ export abstract class BaseLLM implements ILLM {
prefix,
suffix,
options: completionOptions,
provider: this.providerName,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, fimLog);
@ -622,6 +628,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
);
} catch (e) {
status = this._logEnd(
@ -630,6 +637,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
e,
);
throw e;
@ -641,6 +649,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
"cancel",
);
}
@ -681,6 +690,7 @@ export abstract class BaseLLM implements ILLM {
kind: "startComplete",
prompt,
options: completionOptions,
provider: this.providerName,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -736,6 +746,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
);
} catch (e) {
status = this._logEnd(
@ -744,6 +755,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
e,
);
throw e;
@ -755,6 +767,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
"cancel",
);
}
@ -796,6 +809,7 @@ export abstract class BaseLLM implements ILLM {
kind: "startComplete",
prompt: prompt,
options: completionOptions,
provider: this.providerName,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -829,6 +843,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
);
} catch (e) {
status = this._logEnd(
@ -837,6 +852,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
e,
);
throw e;
@ -848,6 +864,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
"cancel",
);
}
@ -923,7 +940,7 @@ export abstract class BaseLLM implements ILLM {
let messages = _messages;
// If not precompiled, compile the chat messages
if (!messageOptions || messageOptions.precompiled === false) {
if (!messageOptions?.precompiled) {
const { compiledChatMessages } = compileChatMessages({
modelName: completionOptions.model,
msgs: _messages,
@ -944,6 +961,7 @@ export abstract class BaseLLM implements ILLM {
kind: "startChat",
messages,
options: completionOptions,
provider: this.providerName,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -952,6 +970,7 @@ export abstract class BaseLLM implements ILLM {
let thinking = "";
let completion = "";
let usage: Usage | undefined = undefined;
try {
if (this.templateMessages) {
@ -1018,6 +1037,11 @@ export abstract class BaseLLM implements ILLM {
kind: "message",
message: chunk,
});
if (chunk.role === "assistant" && chunk.usage) {
usage = chunk.usage;
}
yield chunk;
}
}
@ -1028,6 +1052,7 @@ export abstract class BaseLLM implements ILLM {
completion,
thinking,
interaction,
usage,
);
} catch (e) {
status = this._logEnd(
@ -1036,6 +1061,7 @@ export abstract class BaseLLM implements ILLM {
completion,
thinking,
interaction,
usage,
e,
);
throw e;
@ -1047,6 +1073,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
usage,
"cancel",
);
}

View file

@ -1,5 +1,10 @@
import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
Usage,
} from "../../index.js";
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
@ -234,15 +239,49 @@ class Anthropic extends BaseLLM {
if (options.stream === false) {
const data = await response.json();
yield { role: "assistant", content: data.content[0].text };
const cost = data.usage
? {
inputTokens: data.usage.input_tokens,
outputTokens: data.usage.output_tokens,
totalTokens: data.usage.input_tokens + data.usage.output_tokens,
}
: {};
yield {
role: "assistant",
content: data.content[0].text,
...(Object.keys(cost).length > 0 ? { cost } : {}),
};
return;
}
let lastToolUseId: string | undefined;
let lastToolUseName: string | undefined;
let usage: Usage = {
promptTokens: 0,
completionTokens: 0,
promptTokensDetails: {
cachedTokens: 0,
cacheWriteTokens: 0,
},
};
for await (const value of streamSse(response)) {
// https://docs.anthropic.com/en/api/messages-streaming#event-types
switch (value.type) {
case "message_start":
// Capture initial usage information
usage.promptTokens = value.message.usage.input_tokens;
usage.promptTokensDetails!.cachedTokens =
value.message.usage.cache_read_input_tokens;
usage.promptTokensDetails!.cacheWriteTokens =
value.message.usage.cache_creation_input_tokens;
break;
case "message_delta":
// Update usage information during streaming
if (value.usage) {
usage.completionTokens = value.usage.output_tokens;
}
break;
case "content_block_start":
if (value.content_block.type === "tool_use") {
lastToolUseId = value.content_block.id;
@ -250,7 +289,6 @@ class Anthropic extends BaseLLM {
}
// handle redacted thinking
if (value.content_block.type === "redacted_thinking") {
console.log("redacted thinking", value.content_block.data);
yield {
role: "thinking",
content: "",
@ -303,6 +341,12 @@ class Anthropic extends BaseLLM {
break;
}
}
yield {
role: "assistant",
content: "",
usage,
};
}
}

View file

@ -0,0 +1,495 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../index.js";
import Anthropic from "./Anthropic.js";
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("Anthropic", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("streamChat should send a valid request", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "hello" }],
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
'{"type": "content_block_stop"}',
],
});
});
test("chat should send a valid request", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "hello" }],
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
'{"type": "content_block_stop"}',
],
});
});
test("streamComplete should send a valid request", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "streamComplete",
params: ["Complete this: Hello", new AbortController().signal],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "Complete this: Hello" }],
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}',
'{"type": "content_block_stop"}',
],
});
});
test("complete should send a valid request", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "complete",
params: ["Complete this: Hello", new AbortController().signal],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "Complete this: Hello" }],
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}',
'{"type": "content_block_stop"}',
],
});
});
describe("Different configurations", () => {
test("should handle system message", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "streamChat",
params: [
[
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello!" },
],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "Hello!" }],
},
],
system: "You are a helpful assistant.",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
'{"type": "content_block_stop"}',
],
});
});
test("should handle tool calls", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
const tools = [
{
type: "function" as const,
function: {
name: "get_weather",
description: "Get the current weather",
parameters: {
type: "object",
properties: {
location: { type: "string" },
},
required: ["location"],
},
},
},
];
await runLlmTest({
llm: anthropic,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "What's the weather in New York?" }],
new AbortController().signal,
{ tools },
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [
{ type: "text", text: "What's the weather in New York?" },
],
},
],
tools: [
{
name: "get_weather",
description: "Get the current weather",
input_schema: {
type: "object",
properties: {
location: { type: "string" },
},
required: ["location"],
},
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_start", "content_block": {"type": "tool_use", "id": "toolu_123", "name": "get_weather"}}',
'{"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": "{\\"location\\": \\"New York\\""}}',
'{"type": "content_block_stop"}',
],
});
});
test("should handle custom max tokens", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
{ maxTokens: 1000 },
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 1000,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "hello" }],
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello!"}}',
'{"type": "content_block_stop"}',
],
});
});
});
describe("Error handling", () => {
test("should throw error when API key is missing", async () => {
const anthropic = new Anthropic({
apiKey: "",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await expect(
runLlmTest({
llm: anthropic,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
},
}),
).rejects.toThrow(
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
);
});
});
});

View file

@ -17,7 +17,7 @@ import OpenAI from "./OpenAI.js";
class Docker extends OpenAI implements ModelInstaller {
static providerName = "docker";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:12434/engines/v1",
apiBase: "http://localhost:12434/engines/v1/",
model: "gemma3-4B-F4", // Default model
};

View file

@ -5,7 +5,7 @@ import OpenAI from "./OpenAI.js";
class Fireworks extends OpenAI {
static providerName = "fireworks";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.fireworks.ai/inference/v1",
apiBase: "https://api.fireworks.ai/inference/v1/",
};
private static modelConversion: { [key: string]: string } = {

View file

@ -0,0 +1,12 @@
import Fireworks from "./Fireworks.js";
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
createOpenAISubclassTests(Fireworks, {
providerName: "fireworks",
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
modelConversions: {
"starcoder-7b": "accounts/fireworks/models/starcoder-7b",
},
modelConversionContent:
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
});

View file

@ -0,0 +1,12 @@
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
import Groq from "./Groq.js";
createOpenAISubclassTests(Groq, {
providerName: "groq",
defaultApiBase: "https://api.groq.com/openai/v1/",
modelConversions: {
"mistral-8x7b": "mixtral-8x7b-32768",
"llama3-8b": "llama3-8b-8192",
"llama3-70b": "llama3-70b-8192",
},
});

View file

@ -5,7 +5,7 @@ import OpenAI from "./OpenAI";
class Kindo extends OpenAI {
static providerName = "kindo";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://llm.kindo.ai/v1",
apiBase: "https://llm.kindo.ai/v1/",
requestOptions: {
headers: {
"kindo-token-transaction-type": "CONTINUE",

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",

View file

@ -0,0 +1,294 @@
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
// Import core OpenAI-compatible providers
import OpenAI from "./OpenAI.js";
import Groq from "./Groq.js";
import Fireworks from "./Fireworks.js";
import Together from "./Together.js";
import Deepseek from "./Deepseek.js";
import OpenRouter from "./OpenRouter.js";
import xAI from "./xAI.js";
import Mistral from "./Mistral.js";
import LMStudio from "./LMStudio.js";
import Cerebras from "./Cerebras.js";
import DeepInfra from "./DeepInfra.js";
import Nvidia from "./Nvidia.js";
// Base OpenAI tests
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../index.js";
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
// Disable OpenAI adapter to use our custom fetch mock
(llm as any).useOpenAIAdapterFor = [];
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("OpenAI", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("streamChat should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
});
// Core OpenAI-compatible providers
createOpenAISubclassTests(Groq, {
providerName: "groq",
defaultApiBase: "https://api.groq.com/openai/v1/",
modelConversions: {
"mistral-8x7b": "mistral-8x7b",
"llama3-8b": "llama3-8b-8192",
},
modelConversionContent: "[INST] hello [/INST]",
modelConversionMaxTokens: 4096,
});
createOpenAISubclassTests(Fireworks, {
providerName: "fireworks",
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
modelConversions: {
"starcoder-7b": "starcoder-7b",
},
modelConversionContent:
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
});
createOpenAISubclassTests(Together, {
providerName: "together",
defaultApiBase: "https://api.together.xyz/v1/",
modelConversions: {
"codellama-7b": "codellama-7b",
"llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
},
modelConversionContent: "hello",
customStreamCompleteEndpoint: "completions",
});
createOpenAISubclassTests(Deepseek, {
providerName: "deepseek",
defaultApiBase: "https://api.deepseek.com/",
});
createOpenAISubclassTests(OpenRouter, {
providerName: "openrouter",
defaultApiBase: "https://openrouter.ai/api/v1/",
});
createOpenAISubclassTests(xAI, {
providerName: "xAI",
defaultApiBase: "https://api.x.ai/v1/",
modelConversions: {
"grok-beta": "grok-beta",
},
modelConversionContent: "hello",
});
createOpenAISubclassTests(Mistral, {
providerName: "mistral",
defaultApiBase: "https://api.mistral.ai/v1/",
modelConversions: {
"mistral-7b": "mistral-7b",
"mistral-8x7b": "open-mixtral-8x7b",
},
modelConversionContent: "hello",
});
createOpenAISubclassTests(LMStudio, {
providerName: "lmstudio",
defaultApiBase: "http://localhost:1234/v1/",
});
createOpenAISubclassTests(Cerebras, {
providerName: "cerebras",
defaultApiBase: "https://api.cerebras.ai/v1/",
modelConversions: {
"llama3.1-8b": "llama3.1-8b",
"llama3.1-70b": "llama3.1-70b",
},
modelConversionContent:
"<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
});
createOpenAISubclassTests(DeepInfra, {
providerName: "deepinfra",
defaultApiBase: "https://api.deepinfra.com/v1/openai/",
customEmbeddingsUrl:
"https://api.deepinfra.com/v1/inference/text-embedding-ada-002",
customEmbeddingsHeaders: {
Authorization: "bearer test-api-key",
},
customEmbeddingsBody: {
inputs: ["Hello", "World"],
},
});
createOpenAISubclassTests(Nvidia, {
providerName: "nvidia",
defaultApiBase: "https://integrate.api.nvidia.com/v1/",
customEmbeddingsHeaders: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
},
customEmbeddingsBody: {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
input_type: "passage",
truncate: "END",
},
});

View file

@ -0,0 +1,453 @@
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
// Import all OpenAI-compatible providers
import OpenAI from "./OpenAI.js";
import Groq from "./Groq.js";
import Fireworks from "./Fireworks.js";
import Together from "./Together.js";
import Deepseek from "./Deepseek.js";
import OpenRouter from "./OpenRouter.js";
import xAI from "./xAI.js";
import Mistral from "./Mistral.js";
import LMStudio from "./LMStudio.js";
import Cerebras from "./Cerebras.js";
import DeepInfra from "./DeepInfra.js";
import Nvidia from "./Nvidia.js";
import SambaNova from "./SambaNova.js";
import Scaleway from "./Scaleway.js";
import Venice from "./Venice.js";
import Moonshot from "./Moonshot.js";
import Novita from "./Novita.js";
import SiliconFlow from "./SiliconFlow.js";
import Kindo from "./Kindo.js";
import Azure from "./Azure.js";
import Inception from "./Inception.js";
import Docker from "./Docker.js";
import Voyage from "./Voyage.js";
import Vllm from "./Vllm.js";
import TextGenWebUI from "./TextGenWebUI.js";
// import Relace from "./Relace.js"; // Skip - causing import issues
import FunctionNetwork from "./FunctionNetwork.js";
import NCompass from "./NCompass.js";
import LlamaStack from "./LlamaStack.js";
import Nebius from "./Nebius.js";
import OVHcloud from "./OVHcloud.js";
// Base OpenAI tests
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../index.js";
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
// Disable OpenAI adapter to use our custom fetch mock
(llm as any).useOpenAIAdapterFor = [];
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("OpenAI", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("streamChat should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("should handle embeddings", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "text-embedding-ada-002",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "embed",
params: [["Hello", "World"]],
expectedRequest: {
url: "https://api.openai.com/v1/embeddings",
method: "POST",
headers: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
"api-key": "test-api-key",
},
body: {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
},
});
});
});
// OpenAI-compatible providers
createOpenAISubclassTests(Groq, {
providerName: "groq",
defaultApiBase: "https://api.groq.com/openai/v1/",
modelConversions: {
"mistral-8x7b": "mixtral-8x7b-32768",
"llama3-8b": "llama3-8b-8192",
"llama3-70b": "llama3-70b-8192",
},
modelConversionContent: "[INST] hello [/INST]",
modelConversionMaxTokens: 4096,
});
createOpenAISubclassTests(Fireworks, {
providerName: "fireworks",
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
modelConversions: {
"starcoder-7b": "accounts/fireworks/models/starcoder-7b",
},
modelConversionContent:
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
});
createOpenAISubclassTests(Together, {
providerName: "together",
defaultApiBase: "https://api.together.xyz/v1/",
modelConversions: {
"codellama-7b": "codellama-7b",
"llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
"mistral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1",
},
modelConversionContent: "hello",
customStreamCompleteEndpoint: "completions",
});
createOpenAISubclassTests(Deepseek, {
providerName: "deepseek",
defaultApiBase: "https://api.deepseek.com/",
});
createOpenAISubclassTests(OpenRouter, {
providerName: "openrouter",
defaultApiBase: "https://openrouter.ai/api/v1/",
});
createOpenAISubclassTests(xAI, {
providerName: "xAI",
defaultApiBase: "https://api.x.ai/v1/",
modelConversions: {
"grok-beta": "grok-beta",
},
modelConversionContent: "hello",
});
createOpenAISubclassTests(Mistral, {
providerName: "mistral",
defaultApiBase: "https://api.mistral.ai/v1/",
modelConversions: {
"mistral-7b": "mistral-7b",
"mistral-8x7b": "open-mixtral-8x7b",
},
modelConversionContent: "hello",
});
createOpenAISubclassTests(LMStudio, {
providerName: "lmstudio",
defaultApiBase: "http://localhost:1234/v1/",
});
createOpenAISubclassTests(Cerebras, {
providerName: "cerebras",
defaultApiBase: "https://api.cerebras.ai/v1/",
modelConversions: {
"llama3.1-8b": "llama3.1-8b",
"llama3.1-70b": "llama3.1-70b",
},
modelConversionContent:
"<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
});
createOpenAISubclassTests(DeepInfra, {
providerName: "deepinfra",
defaultApiBase: "https://api.deepinfra.com/v1/openai/",
customEmbeddingsUrl:
"https://api.deepinfra.com/v1/inference/text-embedding-ada-002",
customEmbeddingsHeaders: {
Authorization: "bearer test-api-key",
},
customEmbeddingsBody: {
inputs: ["Hello", "World"],
},
});
createOpenAISubclassTests(Nvidia, {
providerName: "nvidia",
defaultApiBase: "https://integrate.api.nvidia.com/v1/",
customEmbeddingsHeaders: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
},
customEmbeddingsBody: {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
input_type: "passage",
truncate: "END",
},
});
createOpenAISubclassTests(SambaNova, {
providerName: "sambanova",
defaultApiBase: "https://api.sambanova.ai/v1/",
});
createOpenAISubclassTests(Scaleway, {
providerName: "scaleway",
defaultApiBase: "https://api.scaleway.ai/v1/",
});
createOpenAISubclassTests(Venice, {
providerName: "venice",
defaultApiBase: "https://api.venice.ai/api/v1/",
});
createOpenAISubclassTests(Moonshot, {
providerName: "moonshot",
defaultApiBase: "https://api.moonshot.cn/v1/",
});
createOpenAISubclassTests(Novita, {
providerName: "novita",
defaultApiBase: "https://api.novita.ai/v3/openai/",
customStreamCompleteEndpoint: "completions",
});
createOpenAISubclassTests(SiliconFlow, {
providerName: "siliconflow",
defaultApiBase: "https://api.siliconflow.cn/v1/",
});
createOpenAISubclassTests(Kindo, {
providerName: "kindo",
defaultApiBase: "https://llm.kindo.ai/v1/",
});
createOpenAISubclassTests(Azure, {
providerName: "azure",
});
createOpenAISubclassTests(Inception, {
providerName: "inception",
defaultApiBase: "https://api.inceptionlabs.ai/v1/",
customBodyOptions: {
temperature: 0.0,
presence_penalty: 1.5,
stop: ["<|endoftext|>"],
},
});
createOpenAISubclassTests(Docker, {
providerName: "docker",
defaultApiBase: "http://localhost:12434/engines/v1/",
});
createOpenAISubclassTests(Voyage, {
providerName: "voyage",
defaultApiBase: "https://api.voyageai.com/v1/",
});
createOpenAISubclassTests(Vllm, {
providerName: "vllm",
defaultApiBase: "https://api.openai.com/v1/",
});
createOpenAISubclassTests(TextGenWebUI, {
providerName: "text-gen-webui",
defaultApiBase: "http://localhost:5000/v1/",
});
createOpenAISubclassTests(FunctionNetwork, {
providerName: "function-network",
defaultApiBase: "https://api.function.network/v1/",
customEmbeddingsHeaders: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
},
});
createOpenAISubclassTests(NCompass, {
providerName: "ncompass",
defaultApiBase: "https://api.ncompass.tech/v1/",
customEmbeddingsUrl: "https://api.gcp.ncompass.tech/v1/embeddings",
customEmbeddingsHeaders: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
},
customEmbeddingsBody: {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
},
});
createOpenAISubclassTests(LlamaStack, {
providerName: "llamastack",
defaultApiBase: "http://localhost:8321/v1/openai/v1/",
});
createOpenAISubclassTests(Nebius, {
providerName: "nebius",
defaultApiBase: "https://api.studio.nebius.ai/v1/",
});
createOpenAISubclassTests(OVHcloud, {
providerName: "ovhcloud",
defaultApiBase: "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
});

View file

@ -0,0 +1,427 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../index.js";
import OpenAI from "./OpenAI.js";
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
// Disable OpenAI adapter to use our custom fetch mock
(llm as any).useOpenAIAdapterFor = [];
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("OpenAI", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("streamChat should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("chat should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("streamComplete should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "streamComplete",
params: ["Hello", new AbortController().signal],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "Hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("complete should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "complete",
params: ["Hello", new AbortController().signal],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "Hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("should handle O1 models correctly", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "o1-preview",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
{ maxTokens: 100 },
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "o1-preview",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_completion_tokens: 100,
},
},
mockStream: [{ choices: [{ delta: { content: "Hello world" } }] }],
});
});
test("should handle tools", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
const tools = [
{
type: "function" as const,
function: {
name: "test_function",
description: "Test function",
parameters: { type: "object", properties: {} },
},
},
];
await runLlmTest({
llm: openai,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
{ tools },
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
tools: [
{
type: "function",
function: {
name: "test_function",
description: "Test function",
parameters: { type: "object", properties: {} },
},
},
],
},
},
mockStream: [{ choices: [{ delta: { content: "I'll help you" } }] }],
});
});
test("should handle custom max tokens", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
{ maxTokens: 500 },
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 500,
},
},
mockStream: [{ choices: [{ delta: { content: "Hello" } }] }],
});
});
test("should handle embeddings", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "text-embedding-ada-002",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "embed",
params: [["Hello", "World"]],
expectedRequest: {
url: "https://api.openai.com/v1/embeddings",
method: "POST",
headers: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
"api-key": "test-api-key",
},
body: {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
},
});
});
});

View file

@ -6,7 +6,7 @@ import OpenAI from "./OpenAI";
class Venice extends OpenAI {
static providerName = "venice";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.venice.ai/api/v1",
apiBase: "https://api.venice.ai/api/v1/",
};
protected _convertArgs(

View file

@ -0,0 +1,93 @@
import { expect, jest } from "@jest/globals";
import { ILLM } from "../../index.js";
export interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: string[]; // array of string chunks for SSE
}
export async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = jest.fn<any>();
if (mockStream) {
const encoder = new TextEncoder();
let streamIndex = 0;
mockFetch.mockResolvedValue(
new Response(
new ReadableStream({
start(controller) {
mockStream.forEach((chunk) => {
controller.enqueue(new TextEncoder().encode(chunk));
});
controller.close();
},
}),
{
headers: {
"Content-Type": "text/event-stream",
},
},
),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: {
"Content-Type": "application/json",
},
}),
);
}
// @ts-ignore
llm.fetch = mockFetch;
// @ts-ignore
if (typeof llm[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
// @ts-ignore
const result = await llm[methodToTest](...params);
if (mockStream) {
// Consume the stream to ensure it's processed correctly
for await (const _ of result) {
}
}
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0] as [string, RequestInit];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(expectedRequest.headers);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}

View file

@ -0,0 +1,758 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../../index.js";
import ContinueProxy from "./ContinueProxy.js";
vi.mock("@continuedev/config-yaml", async (importOriginal) => {
const mod = (await importOriginal()) as any;
return {
...mod,
parseProxyModelName: vi.fn(() => ({
provider: "test-provider",
model: "test-model",
ownerSlug: "test-owner",
packageSlug: "test-package",
})),
};
});
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("ContinueProxy", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("rerank should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "rerank",
params: [
"test query",
[{ content: "document1" }, { content: "document2" }],
],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
},
body: {
query: "test query",
documents: ["document1", "document2"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockResponse: {
data: [
{ index: 0, relevance_score: 0.9 },
{ index: 1, relevance_score: 0.1 },
],
},
});
});
test("streamChat should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "streamChat",
params: [[{ role: "user", content: "hello" }]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "response"}}]}',
"[DONE]",
],
});
});
test("chat should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "chat",
params: [[{ role: "user", content: "hello" }]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "Hello! How can I help you today?"}}]}',
"[DONE]",
],
});
});
test("streamComplete should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "streamComplete",
params: ["Complete this: Hello"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "Complete this: Hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": " world!"}}]}',
"[DONE]",
],
});
});
test("complete should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "complete",
params: ["Complete this: Hello"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "Complete this: Hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": " world!"}}]}',
"[DONE]",
],
});
});
test("streamFim should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "streamFim",
params: ["function test() {\n ", "\n}"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": "test-api-key",
Authorization: "Bearer test-api-key",
},
body: {
model: "test-model",
prompt: "function test() {\n ",
suffix: "\n}",
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "console.log("Hello");"}}]}',
"[DONE]",
],
});
});
test("embed should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "embed",
params: [["text to embed", "another text"]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
input: ["text to embed", "another text"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
},
});
});
test("listModels should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "listModels",
params: [],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/models",
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
},
mockResponse: {
data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }],
},
});
});
describe("Different provider configurations", () => {
test("should handle on-prem proxy URL", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
onPremProxyUrl: "https://my-proxy.company.com/",
});
await runLlmTest({
llm: proxy,
methodToTest: "rerank",
params: [
"test query",
[{ content: "document1" }, { content: "document2" }],
],
expectedRequest: {
url: "https://my-proxy.company.com/model-proxy/v1/rerank",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
},
body: {
query: "test query",
documents: ["document1", "document2"],
model: "test-model",
continueProperties: {
apiBase: undefined,
apiKeyLocation: undefined,
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [
{ index: 0, relevance_score: 0.9 },
{ index: 1, relevance_score: 0.1 },
],
},
});
});
test("should handle environment variables", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
env: {
CUSTOM_VAR: "custom-value",
ANOTHER_VAR: "another-value",
},
});
await runLlmTest({
llm: proxy,
methodToTest: "streamChat",
params: [[{ role: "user", content: "hello" }]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
env: {
CUSTOM_VAR: "custom-value",
ANOTHER_VAR: "another-value",
},
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "response"}}]}',
"[DONE]",
],
});
});
test("should handle API key location", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: "env:OPENAI_API_KEY",
});
await runLlmTest({
llm: proxy,
methodToTest: "embed",
params: [["test text"]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
input: ["test text"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: "env:OPENAI_API_KEY",
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }],
},
});
});
test("should handle env secret locations", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
envSecretLocations: {
AZURE_API_KEY: "env:AZURE_API_KEY",
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
},
});
await runLlmTest({
llm: proxy,
methodToTest: "streamFim",
params: ["const x = ", ";"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": "test-api-key",
Authorization: "Bearer test-api-key",
},
body: {
model: "test-model",
prompt: "const x = ",
suffix: ";",
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
envSecretLocations: {
AZURE_API_KEY: "env:AZURE_API_KEY",
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
},
orgScopeId: null,
},
},
},
mockStream: ['{"choices": [{"delta": {"content": "42"}}]}', "[DONE]"],
});
});
test("should handle organization scope ID", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: "org_12345",
});
await runLlmTest({
llm: proxy,
methodToTest: "listModels",
params: [],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/models",
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
},
mockResponse: {
data: [{ id: "gpt-4" }],
},
});
});
});
describe("Edge cases", () => {
test("should handle empty chunks array for rerank", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "rerank",
params: ["test query", []],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
},
body: {
query: "test query",
documents: [],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: undefined,
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [],
},
});
});
test("should handle complex chat messages", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
const complexMessages = [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello!" },
{ role: "assistant", content: "Hi there! How can I help you today?" },
{ role: "user", content: "What's the weather like?" },
];
await runLlmTest({
llm: proxy,
methodToTest: "streamChat",
params: [complexMessages],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: complexMessages,
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "I don\'t have access to current weather data."}}]}',
"[DONE]",
],
});
});
test("should handle single embedding chunk", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "embed",
params: [["single text"]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
input: ["single text"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: undefined,
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }],
},
});
});
});
});

View file

@ -0,0 +1,375 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../../index.js";
import OpenAI from "../OpenAI.js";
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
// Disable OpenAI adapter to use our custom fetch mock
(llm as any).useOpenAIAdapterFor = [];
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
export interface OpenAISubclassConfig {
providerName: string;
defaultApiBase?: string;
modelConversions?: { [key: string]: string };
customOptions?: any;
modelConversionContent?: string;
modelConversionMaxTokens?: number;
customStreamCompleteEndpoint?: string;
customEmbeddingsUrl?: string;
customEmbeddingsHeaders?: { [key: string]: string };
customEmbeddingsBody?: any;
customBodyOptions?: any;
}
function getExpectedUrl(
config: OpenAISubclassConfig,
endpoint: string,
model: string = "gpt-4",
) {
let baseUrl = config.defaultApiBase || "https://api.openai.com/v1/";
if (config.providerName === "azure") {
return `${baseUrl}openai/deployments/${model}/${endpoint}?api-version=2023-07-01-preview`;
} else if (config.providerName === "ncompass") {
return `${baseUrl}${endpoint}`;
}
return `${baseUrl}${endpoint}`;
}
export const createOpenAISubclassTests = (
ProviderClass: typeof OpenAI,
config: OpenAISubclassConfig,
) => {
describe(config.providerName, () => {
afterEach(() => {
vi.clearAllMocks();
});
test("should have correct provider name", () => {
expect(ProviderClass.providerName).toBe(config.providerName);
});
if (config.defaultApiBase) {
test("should have correct default API base", () => {
expect(ProviderClass.defaultOptions?.apiBase).toBe(
config.defaultApiBase,
);
});
}
test("streamChat should send a valid request", async () => {
const provider = new ProviderClass({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
});
await runLlmTest({
llm: provider,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: getExpectedUrl(config, "chat/completions"),
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
...config.customBodyOptions,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("chat should send a valid request", async () => {
const provider = new ProviderClass({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
});
await runLlmTest({
llm: provider,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: getExpectedUrl(config, "chat/completions"),
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
...config.customBodyOptions,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("streamComplete should send a valid request", async () => {
const provider = new ProviderClass({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
});
await runLlmTest({
llm: provider,
methodToTest: "streamComplete",
params: ["Hello", new AbortController().signal],
expectedRequest: {
url: getExpectedUrl(
config,
config.customStreamCompleteEndpoint || "chat/completions",
),
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body:
config.customStreamCompleteEndpoint === "completions"
? {
model: "gpt-4",
prompt: "Hello",
stream: true,
max_tokens: 2048,
...config.customBodyOptions,
}
: {
model: "gpt-4",
messages: [{ role: "user", content: "Hello" }],
stream: true,
max_tokens: 2048,
...config.customBodyOptions,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("complete should send a valid request", async () => {
const provider = new ProviderClass({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
});
await runLlmTest({
llm: provider,
methodToTest: "complete",
params: ["Hello", new AbortController().signal],
expectedRequest: {
url: getExpectedUrl(config, "chat/completions"),
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "Hello" }],
stream: true,
max_tokens: 2048,
...config.customBodyOptions,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("should handle embeddings", async () => {
const provider = new ProviderClass({
apiKey: "test-api-key",
model: "text-embedding-ada-002",
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
});
// Skip test if provider doesn't support embeddings (e.g., ncompass with undefined endpoint)
if (config.providerName === "ncompass" && !config.customEmbeddingsUrl) {
return;
}
await runLlmTest({
llm: provider,
methodToTest: "embed",
params: [["Hello", "World"]],
expectedRequest: {
url:
config.customEmbeddingsUrl ||
`${config.defaultApiBase || "https://api.openai.com/v1/"}embeddings`,
method: "POST",
headers: config.customEmbeddingsHeaders || {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
"api-key": "test-api-key",
},
body: config.customEmbeddingsBody || {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
},
},
mockResponse: {
data: [
{ embedding: [0.1, 0.2, 0.3] },
{ embedding: [0.4, 0.5, 0.6] },
],
},
});
});
});
};

View file

@ -44,6 +44,7 @@ describe("LLMLogFormatter", () => {
content: "You are a helpful assistant",
},
],
provider: "watsonx",
});
logger._logItem({
interactionId: "1",
@ -79,6 +80,7 @@ describe("LLMLogFormatter", () => {
promptTokens: 10,
generatedTokens: 20,
thinkingTokens: 0,
usage: undefined,
});
expect(output.getText()).toBe(
@ -113,6 +115,7 @@ describe("LLMLogFormatter", () => {
model: "granite3.2-dense:8b",
},
prompt: "A horse is a horse",
provider: "watsonx",
});
logger._logItem({
interactionId: "1",
@ -149,6 +152,7 @@ describe("LLMLogFormatter", () => {
},
prefix: "A\nB",
suffix: "D\nE",
provider: "watsonx",
});
logger._logItem({
interactionId: "1",
@ -225,6 +229,7 @@ describe("LLMLogFormatter", () => {
promptTokens: 10,
generatedTokens: 20,
thinkingTokens: 0,
usage: undefined,
});
logger._logItem({
interactionId: "3",

View file

@ -0,0 +1,181 @@
import { Usage } from "../..";
export interface CostBreakdown {
cost: number;
breakdown: string;
}
function calculateAnthropicCost(
model: string,
usage: Usage,
): CostBreakdown | null {
// Normalize model name to handle various formats
const normalizedModel = model.toLowerCase();
// Define pricing per million tokens (MTok)
const pricing: Record<
string,
{ input: number; output: number; cacheWrite: number; cacheRead: number }
> = {
// Claude Opus 4 (most intelligent model)
"claude-3-opus": {
input: 15,
output: 75,
cacheWrite: 18.75,
cacheRead: 1.5,
},
"claude-3-opus-20240229": {
input: 15,
output: 75,
cacheWrite: 18.75,
cacheRead: 1.5,
},
// Claude Sonnet 4 (optimal balance)
"claude-3-5-sonnet": {
input: 3,
output: 15,
cacheWrite: 3.75,
cacheRead: 0.3,
},
"claude-3-5-sonnet-20241022": {
input: 3,
output: 15,
cacheWrite: 3.75,
cacheRead: 0.3,
},
"claude-3-5-sonnet-20240620": {
input: 3,
output: 15,
cacheWrite: 3.75,
cacheRead: 0.3,
},
// Claude Haiku 3.5 (fastest, most cost-effective)
"claude-3-5-haiku": {
input: 0.8,
output: 4,
cacheWrite: 1,
cacheRead: 0.08,
},
"claude-3-5-haiku-20241022": {
input: 0.8,
output: 4,
cacheWrite: 1,
cacheRead: 0.08,
},
// Legacy Claude 3 Haiku
"claude-3-haiku": {
input: 0.25,
output: 1.25,
cacheWrite: 0.3,
cacheRead: 0.03,
},
"claude-3-haiku-20240307": {
input: 0.25,
output: 1.25,
cacheWrite: 0.3,
cacheRead: 0.03,
},
};
// Find matching pricing model
let modelPricing = pricing[normalizedModel];
// If exact match not found, try to find by partial match
if (!modelPricing) {
for (const [key, value] of Object.entries(pricing)) {
if (normalizedModel.includes(key) || key.includes(normalizedModel)) {
modelPricing = value;
break;
}
}
}
// If still no match, try common patterns
if (!modelPricing) {
if (normalizedModel.includes("opus")) {
modelPricing = pricing["claude-3-opus"];
} else if (normalizedModel.includes("sonnet")) {
modelPricing = pricing["claude-3-5-sonnet"];
} else if (normalizedModel.includes("haiku")) {
modelPricing = pricing["claude-3-5-haiku"];
}
}
if (!modelPricing) {
return null; // Unknown model
}
// Calculate costs
const inputCost = (usage.promptTokens / 1_000_000) * modelPricing.input;
const outputCost = (usage.completionTokens / 1_000_000) * modelPricing.output;
// Build breakdown components
const breakdownParts: string[] = [];
// Input tokens breakdown
if (usage.promptTokens > 0) {
breakdownParts.push(
`Input: ${usage.promptTokens.toLocaleString()} tokens × $${modelPricing.input}/MTok = $${inputCost.toFixed(6)}`,
);
}
// Output tokens breakdown
if (usage.completionTokens > 0) {
breakdownParts.push(
`Output: ${usage.completionTokens.toLocaleString()} tokens × $${modelPricing.output}/MTok = $${outputCost.toFixed(6)}`,
);
}
// Handle prompt caching costs if available
let cacheCost = 0;
if (usage.promptTokensDetails) {
const { cachedTokens, cacheWriteTokens } = usage.promptTokensDetails;
if (cacheWriteTokens && cacheWriteTokens > 0) {
const cacheWriteCost =
(cacheWriteTokens / 1_000_000) * modelPricing.cacheWrite;
cacheCost += cacheWriteCost;
breakdownParts.push(
`Cache Write: ${cacheWriteTokens.toLocaleString()} tokens × $${modelPricing.cacheWrite}/MTok = $${cacheWriteCost.toFixed(6)}`,
);
}
if (cachedTokens && cachedTokens > 0) {
const cacheReadCost = (cachedTokens / 1_000_000) * modelPricing.cacheRead;
cacheCost += cacheReadCost;
breakdownParts.push(
`Cache Read: ${cachedTokens.toLocaleString()} tokens × $${modelPricing.cacheRead}/MTok = $${cacheReadCost.toFixed(6)}`,
);
}
}
const totalCost = inputCost + outputCost + cacheCost;
// Build final breakdown string
let breakdown = `Model: ${model}\n`;
breakdown += breakdownParts.join("\n");
if (breakdownParts.length > 1) {
breakdown += `\nTotal: $${totalCost.toFixed(6)}`;
}
return {
cost: totalCost,
breakdown,
};
}
export function calculateRequestCost(
provider: string,
model: string,
usage: Usage,
): CostBreakdown | null {
switch (provider) {
case "anthropic":
return calculateAnthropicCost(model, usage);
default:
return null;
}
}

View file

@ -190,7 +190,8 @@
"@types/json-schema": "^7.0.15",
"cross-env": "^7.0.3",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2"
"ts-node": "^10.9.2",
"vitest": "^1.6.1"
}
},
"node_modules/@75lb/deep-merge": {

View file

@ -186,6 +186,13 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
string | undefined,
];
"conversation/compact": [
{
index: number;
sessionId: string;
},
string | undefined,
];
"stats/getTokensPerDay": [
undefined,
{ day: string; promptTokens: number; generatedTokens: number }[],

View file

@ -47,6 +47,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"llm/compileChat",
"streamDiffLines",
"chatDescriber/describe",
"conversation/compact",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase

View file

@ -1,7 +1,6 @@
// core/util/GlobalContext.test.ts
import { GlobalContext, GlobalContextType } from "./GlobalContext";
import fs from "node:fs";
import path from "path";
import { GlobalContext } from "./GlobalContext";
import { getGlobalContextFilePath } from "./paths";
describe("GlobalContext", () => {
@ -69,13 +68,40 @@ describe("GlobalContext", () => {
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
expect(consoleWarnMock).toHaveBeenCalledWith(
expect.stringContaining("Error parsing global context"),
expect.stringContaining(
"Error parsing global context, deleting corrupted file",
),
);
// Clean up
consoleWarnMock.mockRestore();
});
it("should delete corrupted file on get and allow fresh start", () => {
// Write invalid JSON to the file
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
expect(fs.existsSync(globalContextFilePath)).toBe(true);
const consoleWarnMock = jest
.spyOn(console, "warn")
.mockImplementation(() => {});
// Try to get a value - this should delete the corrupted file
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
// File should be deleted after corruption is detected
expect(fs.existsSync(globalContextFilePath)).toBe(false);
// Now we should be able to update and get values normally
globalContext.update("indexingPaused", true);
const newValue = globalContext.get("indexingPaused");
expect(newValue).toBe(true);
// Clean up
consoleWarnMock.mockRestore();
});
it("should handle JSON parsing errors gracefully on update", () => {
// Write invalid JSON to the file
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
@ -87,15 +113,45 @@ describe("GlobalContext", () => {
// Attempt to update
globalContext.update("indexingPaused", true);
// The update should have been skipped due to JSON parsing error
// So attempting to get the value should return undefined
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
expect(consoleWarnMock).toHaveBeenCalledWith(
expect.stringContaining("Error updating global context"),
expect.stringContaining(
"Error updating global context, deleting corrupted file",
),
);
// The update should have recreated the file with just the new value
const value = globalContext.get("indexingPaused");
expect(value).toBe(true);
// Clean up
consoleWarnMock.mockRestore();
});
it("should delete and recreate corrupted file on update", () => {
// Write invalid JSON to the file
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
expect(fs.existsSync(globalContextFilePath)).toBe(true);
const consoleWarnMock = jest
.spyOn(console, "warn")
.mockImplementation(() => {});
// Try to update - this should delete the corrupted file and recreate it
globalContext.update("indexingPaused", true);
// File should still exist but with valid JSON now
expect(fs.existsSync(globalContextFilePath)).toBe(true);
// Should be able to read the value
const value = globalContext.get("indexingPaused");
expect(value).toBe(true);
// Should be able to add more values
globalContext.update("hasAlreadyCreatedAPromptFile", false);
expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(false);
// Original value should still be there
expect(globalContext.get("indexingPaused")).toBe(true);
// Clean up
consoleWarnMock.mockRestore();
});

View file

@ -68,7 +68,28 @@ export class GlobalContext {
try {
parsed = JSON.parse(data);
} catch (e: any) {
console.warn(`Error updating global context: ${e}`);
console.warn(
`Error updating global context, deleting corrupted file: ${e}`,
);
// Delete the corrupted file and recreate it fresh
try {
fs.unlinkSync(filepath);
} catch (deleteError) {
console.warn(
`Error deleting corrupted global context file: ${deleteError}`,
);
}
// Recreate the file with just the new value
fs.writeFileSync(
filepath,
JSON.stringify(
{
[key]: value,
},
null,
2,
),
);
return;
}
@ -90,7 +111,17 @@ export class GlobalContext {
const parsed = JSON.parse(data);
return parsed[key];
} catch (e: any) {
console.warn(`Error parsing global context: ${e}`);
console.warn(
`Error parsing global context, deleting corrupted file: ${e}`,
);
// Delete the corrupted file so it can be recreated fresh
try {
fs.unlinkSync(filepath);
} catch (deleteError) {
console.warn(
`Error deleting corrupted global context file: ${deleteError}`,
);
}
return undefined;
}
}

View file

@ -0,0 +1,89 @@
import { ILLM } from "..";
import { HistoryManager } from "./history";
import { stripImages } from "./messageContent";
export interface CompactionParams {
sessionId: string;
index: number;
historyManager: HistoryManager;
currentModel: ILLM;
}
/**
* Compacts conversation history up to a specified index by generating a summary.
* This helper function extracts the compaction logic from the main core handler.
*
* @param params - Object containing sessionId, index, historyManager, and currentModel
* @returns Promise<void> - Updates the session with the conversation summary
*/
export async function compactConversation({
sessionId,
index,
historyManager,
currentModel,
}: CompactionParams): Promise<void> {
// Get the current session
const session = historyManager.load(sessionId);
const historyUpToIndex = session.history.slice(0, index + 1);
// Apply the same filtering logic as in constructMessages, but exclude the target message
// if it already has a summary (we're re-compacting)
let summaryContent = "";
let filteredHistory = historyUpToIndex;
// First, check if the target message already has a summary and ignore it
const targetMessageHasSummary = historyUpToIndex[index].conversationSummary;
const searchHistory = targetMessageHasSummary
? historyUpToIndex.slice(0, index)
: historyUpToIndex;
// Find the most recent conversation summary (excluding target if it has one)
for (let i = searchHistory.length - 1; i >= 0; i--) {
const summary = searchHistory[i].conversationSummary;
if (summary) {
summaryContent = summary;
// Only include messages that come AFTER the message with the summary
filteredHistory = historyUpToIndex.slice(i + 1);
break;
}
}
// Create messages from filtered history
const messages = filteredHistory.map((item: any) => item.message);
// If there's a previous summary, include it as a user message at the beginning
if (summaryContent) {
messages.unshift({
role: "user",
content: `Previous conversation summary:\n\n${summaryContent}`,
});
}
const compactionPrompt = {
role: "user" as const,
content:
"Create a comprehensive summary of this conversation that captures all essential information needed to continue the work seamlessly. Structure your response to preserve technical accuracy and context continuity.\n\nYour summary should include:\n\n1. **Conversation Overview**: Describe the main topic and progression of the discussion, including any shifts in focus or direction.\n\n2. **Active Development**: Detail what was being implemented, modified, or debugged most recently. Include specific technical approaches and methodologies used.\n\n3. **Technical Stack**: List all relevant technologies, frameworks, libraries, coding patterns, and architectural decisions discussed.\n\n4. **File Operations**: Document all files that were created, modified, or referenced, including their purposes and key changes. Include important code snippets and their locations.\n\n5. **Solutions & Troubleshooting**: Summarize problems encountered and how they were resolved, including any debugging steps or workarounds applied.\n\n6. **Outstanding Work**: Clearly identify any incomplete tasks, pending implementations, or next steps that were discussed. Include direct references to user requests and current progress.\n\nIf there's a previous summary in the conversation, integrate its relevant information while removing outdated details. Focus on technical precision and include specific identifiers (file paths, function names, class names, etc.) that would be essential for continuation. Write in third person and maintain an objective, technical tone.",
};
// Generate the summary using the current model
const response = await currentModel.chat(
[...messages, compactionPrompt],
new AbortController().signal,
{},
);
// Update the target message with the conversation summary
const updatedHistory = [...session.history];
updatedHistory[index] = {
...updatedHistory[index],
conversationSummary: stripImages(response.content),
};
// Update the session with the new history
const updatedSession = {
...session,
history: updatedHistory,
};
historyManager.save(updatedSession);
}

View file

@ -21,7 +21,7 @@ function safeParseArray<T>(
}
}
class HistoryManager {
export class HistoryManager {
list(options: ListHistoryOptions): SessionMetadata[] {
const filepath = getSessionsListPath();
if (!fs.existsSync(filepath)) {

View file

@ -186,6 +186,41 @@ aws_secret_access_key = hijklmno
aws_session_token = pqrstuvwxyz # Optional: means short term creds.
```
You can also use an AWS `accessKeyId` and `secretAccessKey` for authentication instead of a local credentials profile.
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: Claude 3.7 Sonnet
provider: bedrock
model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
env:
region: us-east-1
accessKeyId: ${{ secrets.AWS_ACCESS_KEY_ID }} # can also enter key inline here for local assistants
secretAccessKey: ${{ secrets.AWS_SECRET_ACCESS_KEY }} # can also enter key inline here for local assistants
roles:
- chat
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "Claude 3.7 Sonnet",
"provider": "bedrock",
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
"region": "us-east-1",
"accessKeyId": "[YOUR_ACCESS_KEY_ID]",
"secretAccessKey": "[YOUR_SECRET_ACCESS_KEY]"
}
]
}
```
</Tab>
</Tabs>
## Custom Imported Models
To setup Bedrock using custom imported models, add the following to your config file:

View file

@ -9,18 +9,18 @@ slug: ../xai
## Chat model
We recommend configuring **grok-2-latest** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models).
We recommend configuring **grok-4** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models).
<Tabs>
<Tab title="Config">
Add the [xAI Grok 2 model block](https://hub.continue.dev/xai/grok-2) on the hub.
Add the [xAI Grok 4 model block](https://hub.continue.dev/xai/grok-4) on the hub.
</Tab>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: Grok 2
- name: Grok 4
provider: xAI
model: grok-2-latest
model: grok-4
apiKey: <YOUR_XAI_API_KEY>
```
</Tab>
@ -29,9 +29,9 @@ We recommend configuring **grok-2-latest** as your chat model. For information o
{
"models": [
{
"title": "Grok 2",
"title": "Grok 4",
"provider": "xAI",
"model": "grok-2-latest",
"model": "grok-4",
"apiKey": "<YOUR_XAI_API_KEY>"
}
]

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=1.0.29
pluginVersion=1.0.30
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -113,6 +113,7 @@ class MessageTypes {
"llm/compileChat",
"streamDiffLines",
"chatDescriber/describe",
"conversation/compact",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase

View file

@ -38,4 +38,4 @@ All e2e tests are separated (by folder) into
### Quirks
- For non-macOS systems, `codesign` is not available. You should run `npm run e2e:all-non-mac` instead of `npm run e2e:all`.
- For non-macOS systems, `codesign` is not available. You should run `npm run e2e:all-non-mac` instead of `npm run e2e:all`.

View file

@ -1,15 +1,19 @@
import { expect } from "chai";
import { Key } from "vscode-extension-tester";
import { access, constants } from 'fs/promises';
import { access, constants } from "fs/promises";
import * as path from "path";
import { DEFAULT_TIMEOUT } from "./constants";
export class TestUtils {
public static CONTINUE_GLOBAL_DIR = process.env.CONTINUE_GLOBAL_DIR ?? "";
public static getGlobalContextFilePath(): string {
return path.join(TestUtils.CONTINUE_GLOBAL_DIR, "index", "globalContext.json");
return path.join(
TestUtils.CONTINUE_GLOBAL_DIR,
"index",
"globalContext.json",
);
}
public static async fileExists(path: string): Promise<boolean> {

View file

@ -12,12 +12,14 @@ export class NextEditActions {
public static async acceptNextEditSuggestion(editor: TextEditor) {
const hasDecoration = await NextEditActions.forceNextEdit(editor);
expect(hasDecoration).to.be.true;
await new Workbench().executeCommand("Continue: Accept Next Edit Suggestion");
await new Workbench().executeCommand(
"Continue: Accept Next Edit Suggestion",
);
// Check if HELLO is written into the editor.
const editorText = await editor.getTextAtLine(1);
return editorText === "HELLO";
}
@ -27,12 +29,12 @@ export class NextEditActions {
public static async rejectNextEditSuggestion(editor: TextEditor) {
const hasDecoration = await NextEditActions.forceNextEdit(editor);
expect(hasDecoration).to.be.true;
await new Workbench().executeCommand("Continue: Hide Next Edit Suggestion");
// Check if the editor text didn't change.
const editorText = await editor.getText();
return editorText === "def main():\n ";
}
@ -45,16 +47,16 @@ export class NextEditActions {
await new Workbench().executeCommand("Continue: Force Next Edit");
await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XL);
const svgDecoration = await TestUtils.waitForSuccess(
() => NextEditSelectors.getSvgDecoration(VSBrowser.instance.driver),
DEFAULT_TIMEOUT.XL
DEFAULT_TIMEOUT.XL,
);
return svgDecoration !== null;
}
public static async reload(): Promise<void> {
await new Workbench().executeCommand('workbench.action.reloadWindow');
await new Workbench().executeCommand("workbench.action.reloadWindow");
}
}

View file

@ -100,10 +100,7 @@ export class GUISelectors {
}
public static getNthMessageDeleteButton(view: WebView, index: number) {
return SelectorUtils.getElementByDataTestId(
view,
`delete-button-${index}`,
);
return SelectorUtils.getElementByDataTestId(view, `delete-button-${index}`);
}
public static getModelDropdownOption(view: WebView, option: string) {

View file

@ -8,7 +8,7 @@ export class NextEditSelectors {
try {
const decorations = await driver.findElement(
// By.xpath("//*[contains(@class, 'ced-') and matches(@class, 'ced-2-TextEditorDecorationType[0-9]+-4')]")
By.css("[class*='TextEditorDecorationType']")
By.css("[class*='TextEditorDecorationType']"),
);
return decorations ?? null;
} catch (error) {
@ -16,4 +16,4 @@ export class NextEditSelectors {
return null;
}
}
}
}

View file

@ -584,4 +584,4 @@ describe("GUI Test", () => {
);
}).timeout(DEFAULT_TIMEOUT.XL);
});
});
});

View file

@ -7,55 +7,59 @@ import { NextEditActions } from "../actions/NextEdit.actions";
import { DEFAULT_TIMEOUT } from "../constants";
import { TestUtils } from "../TestUtils";
describe("Next Edit", () => {
describe("Next Edit", () => {
let editor: TextEditor;
before(async function () {
// this.timeout(DEFAULT_TIMEOUT.XL);
const globalContextPath = TestUtils.getGlobalContextFilePath();
// Update config.json to add optInNextEditFeature.
// globalContext.json does not exist in CI before this test runs.
if (await TestUtils.fileExists(globalContextPath)) {
const globalContext = await fs.readFile(globalContextPath, "utf8");
const sharedConfig = JSON.parse(globalContext).sharedConfig;
const sharedConfigWithNextEditEnabled = {
...sharedConfig,
"optInNextEditFeature": true
optInNextEditFeature: true,
};
const globalContextWithNextEditEnabled = {
...JSON.parse(globalContext),
"sharedConfig": sharedConfigWithNextEditEnabled
sharedConfig: sharedConfigWithNextEditEnabled,
};
await fs.writeFile(globalContextPath, JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8");
await fs.writeFile(
globalContextPath,
JSON.stringify(globalContextWithNextEditEnabled, null, 2),
"utf8",
);
} else {
await fs.writeFile(
globalContextPath,
JSON.stringify(
{
sharedConfig: {
optInNextEditFeature: true
},
selectedModelsByProfileId: {
local: {
chat: "TEST LLM",
edit: "TEST LLM",
apply: "TEST LLM",
embed: "Transformers.js (Built-In)",
autocomplete: "TEST LLM",
rerank: null,
summarize: null
}
}
},
null,
2,
),
);
globalContextPath,
JSON.stringify(
{
sharedConfig: {
optInNextEditFeature: true,
},
selectedModelsByProfileId: {
local: {
chat: "TEST LLM",
edit: "TEST LLM",
apply: "TEST LLM",
embed: "Transformers.js (Built-In)",
autocomplete: "TEST LLM",
rerank: null,
summarize: null,
},
},
},
null,
2,
),
);
}
await NextEditActions.reload();
@ -77,20 +81,27 @@ describe("Next Edit", () => {
after(async function () {
// this.timeout(DEFAULT_TIMEOUT.XL);
// Update config.json to delete optInNextEditFeature.
const globalContext = await fs.readFile(TestUtils.getGlobalContextFilePath(), "utf8");
const globalContext = await fs.readFile(
TestUtils.getGlobalContextFilePath(),
"utf8",
);
const sharedConfig = JSON.parse(globalContext).sharedConfig;
const sharedConfigWithoutNextEdit = { ...sharedConfig };
delete sharedConfigWithoutNextEdit.optInNextEditFeature;
const globalContextWithNextEditEnabled = {
...JSON.parse(globalContext),
"sharedConfig": sharedConfigWithoutNextEdit
sharedConfig: sharedConfigWithoutNextEdit,
};
await fs.writeFile(TestUtils.getGlobalContextFilePath(), JSON.stringify(globalContextWithNextEditEnabled, null, 2), "utf8");
await fs.writeFile(
TestUtils.getGlobalContextFilePath(),
JSON.stringify(globalContextWithNextEditEnabled, null, 2),
"utf8",
);
await NextEditActions.reload();
}).timeout(DEFAULT_TIMEOUT.XL);
@ -116,5 +127,4 @@ describe("Next Edit", () => {
const rejected = await NextEditActions.rejectNextEditSuggestion(editor);
expect(rejected).to.be.true;
}).timeout(DEFAULT_TIMEOUT.XXL);
});
});

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.65",
"version": "1.1.66",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -47,6 +47,7 @@ const Layout = () => {
const dispatch = useAppDispatch();
const onboardingCard = useOnboardingCard();
const ideMessenger = useContext(IdeMessengerContext);
const currentSessionId = useAppSelector((state) => state.session.id);
const { mainEditor } = useMainEditor();
const dialogMessage = useAppSelector((state) => state.ui.dialogMessage);

View file

@ -0,0 +1,81 @@
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid";
import { TrashIcon } from "@heroicons/react/24/outline";
import { ChatHistoryItem } from "core";
import { useState } from "react";
import { AnimatedEllipsis } from "../";
import { useAppSelector } from "../../redux/hooks";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
import { useDeleteCompaction } from "../../util/compactConversation";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
interface ConversationSummaryProps {
item: ChatHistoryItem;
index: number;
}
export default function ConversationSummary(props: ConversationSummaryProps) {
const [open, setOpen] = useState(false);
const isLoading = useAppSelector(
(state) => state.session.compactionLoading[props.index] || false,
);
const deleteCompaction = useDeleteCompaction();
if (!props.item.conversationSummary && !isLoading) {
return null;
}
// Loading state - much simpler
if (isLoading) {
return (
<div className="mx-1.5 mb-4 mt-2">
<div className="bg-vsc-input-background rounded-md shadow-sm">
<div className="text-description flex items-center justify-start px-3 py-2 text-xs">
<span>Generating conversation summary</span>
<AnimatedEllipsis />
</div>
</div>
</div>
);
}
// Normal state with content
return (
<div className="mx-1.5 mb-4 mt-2">
<div className="bg-vsc-input-background rounded-md shadow-sm">
<div
className="text-description flex cursor-pointer items-center gap-2 px-3 py-2 text-xs transition-colors duration-200 hover:brightness-105"
onClick={() => setOpen(!open)}
>
{open ? (
<ChevronUpIcon className="h-3 w-3" />
) : (
<ChevronDownIcon className="h-3 w-3" />
)}
<span className="flex-1">Conversation Summary</span>
<HeaderButtonWithToolTip
text="Delete summary"
onClick={(e) => {
e.stopPropagation();
deleteCompaction(props.index);
}}
>
<TrashIcon className="text-description-muted h-3 w-3" />
</HeaderButtonWithToolTip>
</div>
{open && (
<>
<div className="border-border border-0 border-t border-solid"></div>
<div className="max-h-[400px] overflow-y-auto px-3 pb-3 pt-2">
<StyledMarkdownPreview
isRenderingInStepContainer
source={props.item.conversationSummary}
itemIndex={props.index}
useParentBackgroundColor
/>
</div>
</>
)}
</div>
</div>
);
}

View file

@ -1,4 +1,5 @@
import {
ArrowsPointingInIcon,
BarsArrowDownIcon,
PencilSquareIcon,
TrashIcon,
@ -7,10 +8,10 @@ import { ChatHistoryItem } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { renderChatMessage } from "core/util/messageContent";
import { useMemo } from "react";
import { useDispatch } from "react-redux";
import { useAppSelector } from "../../redux/hooks";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { useCompactConversation } from "../../util/compactConversation";
import { FeedbackButtons } from "../FeedbackButtons";
import { GenerateRuleDialog } from "../GenerateRuleDialog";
import { CopyIconButton } from "../gui/CopyIconButton";
@ -33,12 +34,26 @@ export default function ResponseActions({
onDelete,
isLast,
}: ResponseActionsProps) {
const dispatch = useDispatch();
const dispatch = useAppDispatch();
const selectedModel = useAppSelector(selectSelectedChatModel);
const contextPercentage = useAppSelector(
(state) => state.session.contextPercentage,
);
const isPruned = useAppSelector((state) => state.session.isPruned);
const ruleGenerationSupported = useMemo(() => {
return selectedModel && modelSupportsTools(selectedModel);
}, [selectedModel]);
const percent = Math.round((contextPercentage ?? 0) * 100);
const buttonColorClass =
isLast && (isPruned || percent > 80)
? "text-warning"
: "text-description-muted";
const showLabel = isLast && (isPruned || percent >= 60);
const compactConversation = useCompactConversation();
const onGenerateRule = () => {
dispatch(setShowDialog(true));
dispatch(setDialogMessage(<GenerateRuleDialog />));
@ -46,6 +61,30 @@ export default function ResponseActions({
return (
<div className="text-description-muted mx-2 flex cursor-default items-center justify-end space-x-1 bg-transparent pb-0 text-xs">
<HeaderButtonWithToolTip
testId={`compact-button-${index}`}
text={
showLabel
? "Summarize conversation to reduce context length"
: "Compact conversation"
}
tabIndex={-1}
onClick={() => compactConversation(index)}
>
<div className="flex items-center space-x-1">
<ArrowsPointingInIcon
className={`h-3.5 w-3.5 ${buttonColorClass || "text-description-muted"}`}
/>
{showLabel && (
<span
className={`text-xs ${buttonColorClass || "text-description-muted"}`}
>
Compact conversation
</span>
)}
</div>
</HeaderButtonWithToolTip>
{isLast && ruleGenerationSupported && (
<HeaderButtonWithToolTip
tabIndex={-1}

View file

@ -6,6 +6,7 @@ import { useAppSelector } from "../../redux/hooks";
import { selectUIConfig } from "../../redux/slices/configSlice";
import { deleteMessage } from "../../redux/slices/sessionSlice";
import StyledMarkdownPreview from "../StyledMarkdownPreview";
import ConversationSummary from "./ConversationSummary";
import Reasoning from "./Reasoning";
import ResponseActions from "./ResponseActions";
import ThinkingIndicator from "./ThinkingIndicator";
@ -14,6 +15,7 @@ interface StepContainerProps {
item: ChatHistoryItem;
index: number;
isLast: boolean;
latestSummaryIndex?: number;
}
export default function StepContainer(props: StepContainerProps) {
@ -23,11 +25,15 @@ export default function StepContainer(props: StepContainerProps) {
const historyItemAfterThis = useAppSelector(
(state) => state.session.history[props.index + 1],
);
const warningMessage = useAppSelector(
(state) => state.session.warningMessage,
);
const uiConfig = useAppSelector(selectUIConfig);
// Calculate dimming and indicator state based on latest summary index
const latestSummaryIndex = props.latestSummaryIndex ?? -1;
const isBeforeLatestSummary =
latestSummaryIndex !== -1 && props.index <= latestSummaryIndex;
const isLatestSummary =
latestSummaryIndex !== -1 && props.index === latestSummaryIndex;
const isNextMsgAssistantOrThinking =
historyItemAfterThis?.message.role === "assistant" ||
historyItemAfterThis?.message.role === "thinking" ||
@ -83,7 +89,9 @@ export default function StepContainer(props: StepContainerProps) {
return (
<div>
<div className="bg-background overflow-hidden p-1 px-1.5">
<div
className={`bg-background p-1 px-1.5 ${isBeforeLatestSummary ? "opacity-35" : ""}`}
>
{uiConfig?.displayRawMarkdown ? (
<pre className="text-2xs max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4">
{renderChatMessage(props.item.message)}
@ -101,9 +109,12 @@ export default function StepContainer(props: StepContainerProps) {
)}
{props.isLast && <ThinkingIndicator historyItem={props.item} />}
</div>
{shouldRenderResponseAction() && (
// We want to occupy space in the DOM regardless of whether the actions are visible to avoid jank on stream complete
<div className={`mt-2 h-7 transition-opacity duration-300 ease-in-out`}>
<div
className={`mt-2 h-7 transition-opacity duration-300 ease-in-out ${isBeforeLatestSummary ? "opacity-35" : ""}`}
>
{!isStreaming && (
<ResponseActions
isTruncated={isTruncated}
@ -116,6 +127,22 @@ export default function StepContainer(props: StepContainerProps) {
)}
</div>
)}
{/* Show compaction indicator for the latest summary */}
{isLatestSummary && (
<div className="mx-1.5 my-5">
<div className="flex items-center">
<div className="border-border flex-1 border-t border-solid"></div>
<span className="text-description mx-3 text-xs">
Previous Conversation Compacted
</span>
<div className="border-border flex-1 border-t border-solid"></div>
</div>
</div>
)}
{/* ConversationSummary is outside the dimmed container so it's always at full opacity */}
<ConversationSummary item={props.item} index={props.index} />
</div>
);
}

View file

@ -265,7 +265,7 @@ export function StepContainerPreToolbar({
return (
<div className="outline-command-border -outline-offset-0.5 rounded-default bg-editor mb-2 mt-2 flex min-w-0 flex-col outline outline-1">
<div
className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "border-command-border border-b" : ""}`}
className={`find-widget-skip bg-editor sticky -top-2 z-10 m-0 flex items-center justify-between gap-3 px-1.5 py-1 ${isExpanded ? "rounded-t-default border-command-border border-b" : "rounded-default"}`}
style={{ fontSize: `${getFontSize() - 2}px` }}
>
<div className="flex max-w-[50%] flex-row items-center">

View file

@ -117,6 +117,11 @@ export default function Details({ interaction }: DetailsProps) {
format={(v: number) => v.toFixed(1)}
></Cell>
</div>
{/* {summary.costBreakdown && (
<pre className="whitespace-pre-wrap px-2 text-sm">
{summary.costBreakdown.breakdown}
</pre>
)} */}
</div>
<div
ref={scrollTop}

View file

@ -2,11 +2,13 @@ import { useState } from "react";
import useLLMLog from "../../hooks/useLLMLog";
import Details from "./Details";
import List from "./List";
import TotalUsage from "./TotalUsage";
export default function Layout() {
const llmLog = useLLMLog();
const [selectedId, setSelectedId] = useState<string | undefined>(undefined);
const [showTotalUsage, setShowTotalUsage] = useState(false);
const interaction = selectedId
? llmLog.interactions.get(selectedId)
@ -16,14 +18,46 @@ export default function Layout() {
<div>Loading...</div>
) : (
<div className="flex h-full w-full">
<List
llmLog={llmLog}
onClickInteraction={(interactionId) => {
setSelectedId(interactionId);
}}
></List>
{interaction && (
<Details key="{selectedId}" interaction={interaction}></Details>
<div className="flex h-full w-full flex-col">
{/* <div className="flex-shrink-0 border-b border-[color:var(--vscode-panel-border)] p-3">
<button
onClick={() => setShowTotalUsage(true)}
className="float-right cursor-pointer border-none bg-transparent text-sm text-[color:var(--vscode-textLink-foreground)] underline hover:text-[color:var(--vscode-textLink-activeForeground)]"
>
View Total Usage Summary
</button>
</div> */}
<div className="flex min-h-0 flex-1 overflow-hidden">
<List
llmLog={llmLog}
onClickInteraction={(interactionId) => {
setSelectedId(interactionId);
}}
></List>
{interaction && (
<Details key="{selectedId}" interaction={interaction}></Details>
)}
</div>
</div>
{/* Full-screen popover for TotalUsage */}
{showTotalUsage && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
<div className="relative h-full w-full max-w-6xl overflow-hidden bg-[color:var(--vscode-panel-background)] shadow-2xl">
{/* Close button */}
<button
onClick={() => setShowTotalUsage(false)}
className="absolute right-4 top-4 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-[color:var(--vscode-button-background)] text-[color:var(--vscode-button-foreground)] transition-colors hover:bg-[color:var(--vscode-button-hoverBackground)]"
>
×
</button>
{/* Content container with scroll */}
<div className="h-full overflow-y-auto p-6">
<TotalUsage llmLog={llmLog} />
</div>
</div>
</div>
)}
</div>
);

View file

@ -0,0 +1,362 @@
import { calculateRequestCost } from "core/llm/utils/calculateRequestCost";
import React, { useMemo, useState } from "react";
import { LLMLog } from "../../hooks/useLLMLog";
import useTotalUsage from "../../hooks/useTotalUsage";
interface TotalUsageProps {
llmLog: LLMLog;
}
const StatCard: React.FC<{ label: string; value: number; color?: string }> = ({
label,
value,
color = "var(--vscode-foreground)",
}) => (
<div className="flex flex-col items-center rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3">
<div className="text-sm text-[color:var(--vscode-descriptionForeground)]">
{label}
</div>
<div className="text-lg font-semibold" style={{ color }}>
{value.toLocaleString()}
</div>
</div>
);
const CostChart: React.FC<{ llmLog: LLMLog }> = ({ llmLog }) => {
const chartData = useMemo(() => {
let cumulativeCost = 0;
const dataPoints: { interaction: number; cost: number }[] = [];
llmLog.order.forEach((id, index) => {
const interaction = llmLog.interactions.get(id);
// Calculate cost for this interaction if we have the necessary data
if (
interaction?.end?.usage &&
interaction.start?.provider &&
interaction.start?.options?.model
) {
const costBreakdown = calculateRequestCost(
interaction.start.provider,
interaction.start.options.model,
interaction.end.usage,
);
if (costBreakdown) {
cumulativeCost += costBreakdown.cost;
}
}
dataPoints.push({ interaction: index + 1, cost: cumulativeCost });
});
return dataPoints;
}, [llmLog.order, llmLog.interactions]);
if (chartData.length === 0 || chartData[chartData.length - 1].cost === 0) {
return null;
}
const maxCost = Math.max(...chartData.map((d) => d.cost));
const maxInteraction = chartData.length;
const chartWidth = 400;
const chartHeight = 200;
const padding = 40;
const xScale = (interaction: number) =>
((interaction - 1) / (maxInteraction - 1)) * (chartWidth - 2 * padding) +
padding;
const yScale = (cost: number) =>
chartHeight - padding - (cost / maxCost) * (chartHeight - 2 * padding);
const pathData = chartData
.map(
(d, i) =>
`${i === 0 ? "M" : "L"} ${xScale(d.interaction)} ${yScale(d.cost)}`,
)
.join(" ");
return (
<div className="mb-4 rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-4">
<h3 className="mb-3 text-sm font-semibold text-[color:var(--vscode-foreground)]">
Cumulative Cost Over Interactions
</h3>
<div className="flex justify-center">
<svg
width={chartWidth}
height={chartHeight}
className="overflow-visible"
>
{/* Grid lines */}
<defs>
<pattern
id="grid"
width="20"
height="20"
patternUnits="userSpaceOnUse"
>
<path
d="M 20 0 L 0 0 0 20"
fill="none"
stroke="var(--vscode-panel-border)"
strokeWidth="0.5"
opacity="0.3"
/>
</pattern>
</defs>
<rect width={chartWidth} height={chartHeight} fill="url(#grid)" />
{/* Chart area background */}
<rect
x={padding}
y={padding}
width={chartWidth - 2 * padding}
height={chartHeight - 2 * padding}
fill="var(--vscode-editor-background)"
stroke="var(--vscode-panel-border)"
strokeWidth="1"
/>
{/* Cost line */}
<path
d={pathData}
fill="none"
stroke="var(--vscode-charts-green)"
strokeWidth="2"
strokeLinecap="round"
/>
{/* Data points */}
{chartData.map((d, i) => (
<circle
key={i}
cx={xScale(d.interaction)}
cy={yScale(d.cost)}
r="3"
fill="var(--vscode-charts-green)"
stroke="var(--vscode-editor-background)"
strokeWidth="1"
/>
))}
{/* Y-axis labels */}
{[0, 0.25, 0.5, 0.75, 1].map((ratio) => {
const cost = maxCost * ratio;
const y = yScale(cost);
return (
<g key={ratio}>
<line
x1={padding - 5}
y1={y}
x2={padding}
y2={y}
stroke="var(--vscode-foreground)"
strokeWidth="1"
/>
<text
x={padding - 8}
y={y + 4}
textAnchor="end"
fontSize="10"
fill="var(--vscode-descriptionForeground)"
>
${cost.toFixed(4)}
</text>
</g>
);
})}
{/* X-axis labels */}
{[0, 0.25, 0.5, 0.75, 1].map((ratio) => {
const interaction = Math.round(1 + ratio * (maxInteraction - 1));
const x = xScale(interaction);
return (
<g key={ratio}>
<line
x1={x}
y1={chartHeight - padding}
x2={x}
y2={chartHeight - padding + 5}
stroke="var(--vscode-foreground)"
strokeWidth="1"
/>
<text
x={x}
y={chartHeight - padding + 18}
textAnchor="middle"
fontSize="10"
fill="var(--vscode-descriptionForeground)"
>
{interaction}
</text>
</g>
);
})}
{/* Axis labels */}
<text
x={chartWidth / 2}
y={chartHeight - 5}
textAnchor="middle"
fontSize="12"
fill="var(--vscode-foreground)"
>
Interaction Number
</text>
<text
x={15}
y={chartHeight / 2}
textAnchor="middle"
fontSize="12"
fill="var(--vscode-foreground)"
transform={`rotate(-90 15 ${chartHeight / 2})`}
>
Cumulative Cost ($)
</text>
</svg>
</div>
</div>
);
};
const TotalUsage: React.FC<TotalUsageProps> = ({ llmLog }) => {
const totalUsage = useTotalUsage(llmLog);
const [showCostBreakdown, setShowCostBreakdown] = useState(false);
return (
<div className="border-b border-[color:var(--vscode-panel-border)] p-4">
<div className="mb-4 flex items-center justify-between">
<h2 className="text-lg font-semibold text-[color:var(--vscode-foreground)]">
Total Usage Summary
</h2>
<div className="flex items-center gap-4">
{totalUsage.totalCost > 0 && (
<button
onClick={() => setShowCostBreakdown(!showCostBreakdown)}
className="cursor-pointer text-lg font-semibold text-[color:var(--vscode-charts-green)] hover:text-[color:var(--vscode-charts-blue)]"
>
${totalUsage.totalCost.toFixed(6)}
</button>
)}
<div className="text-sm text-[color:var(--vscode-descriptionForeground)]">
{totalUsage.totalInteractions} interactions
</div>
</div>
</div>
{showCostBreakdown && totalUsage.costBreakdowns.length > 0 && (
<div className="mb-4 max-h-32 overflow-y-auto rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3">
<h3 className="mb-2 text-sm font-semibold text-[color:var(--vscode-foreground)]">
Cost Breakdown
</h3>
<div className="space-y-2 text-xs">
{totalUsage.costBreakdowns.map((breakdown, index) => (
<div
key={index}
className="border-b border-[color:var(--vscode-panel-border)] pb-2 last:border-b-0"
>
<pre className="whitespace-pre-wrap text-[color:var(--vscode-descriptionForeground)]">
{breakdown.breakdown}
</pre>
</div>
))}
</div>
</div>
)}
<div className="mb-4 grid grid-cols-2 gap-3 md:grid-cols-4">
<StatCard
label="Input Tokens"
value={totalUsage.totalPromptTokens}
color="var(--vscode-charts-blue)"
/>
<StatCard
label="Output Tokens"
value={totalUsage.totalGeneratedTokens}
color="var(--vscode-charts-green)"
/>
<StatCard
label="Thinking Tokens"
value={totalUsage.totalThinkingTokens}
color="var(--vscode-charts-purple)"
/>
<StatCard
label="Cache Read"
value={totalUsage.totalCachedTokens}
color="var(--vscode-charts-orange)"
/>
</div>
{totalUsage.totalCost > 0 && (
<>
<CostChart llmLog={llmLog} />
<div className="mb-4">
<div className="flex flex-col items-center rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3">
<div className="text-sm text-[color:var(--vscode-descriptionForeground)]">
Total Cost
</div>
<div className="text-2xl font-bold text-[color:var(--vscode-charts-green)]">
${totalUsage.totalCost.toFixed(6)}
</div>
<div className="text-xs text-[color:var(--vscode-descriptionForeground)]">
{totalUsage.costBreakdowns.length} cost calculations
</div>
</div>
</div>
</>
)}
{totalUsage.totalCacheWriteTokens > 0 && (
<div className="mb-4 grid grid-cols-1 gap-3 md:grid-cols-2">
<StatCard
label="Cache Write"
value={totalUsage.totalCacheWriteTokens}
color="var(--vscode-charts-red)"
/>
<div className="flex items-center justify-center rounded-lg border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-3">
<div className="text-sm text-[color:var(--vscode-descriptionForeground)]">
Cache Hit Rate:{" "}
{totalUsage.totalPromptTokens > 0
? (
(totalUsage.totalCachedTokens /
totalUsage.totalPromptTokens) *
100
).toFixed(1)
: "0"}
%
</div>
</div>
</div>
)}
<div className="grid grid-cols-3 gap-3 text-sm">
<div className="rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-2 text-center">
<div className="text-[color:var(--vscode-charts-green)]">
{totalUsage.totalSuccessfulInteractions}
</div>
<div className="text-[color:var(--vscode-descriptionForeground)]">
Success
</div>
</div>
<div className="rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-2 text-center">
<div className="text-[color:var(--vscode-charts-red)]">
{totalUsage.totalErrorInteractions}
</div>
<div className="text-[color:var(--vscode-descriptionForeground)]">
Error
</div>
</div>
<div className="rounded border border-[color:var(--vscode-panel-border)] bg-[color:var(--vscode-editor-background)] p-2 text-center">
<div className="text-[color:var(--vscode-charts-yellow)]">
{totalUsage.totalCancelledInteractions}
</div>
<div className="text-[color:var(--vscode-descriptionForeground)]">
Cancelled
</div>
</div>
</div>
</div>
);
};
export default TotalUsage;

View file

@ -0,0 +1,89 @@
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { saveCurrentSession } from "../../redux/thunks/session";
import { useCompactConversation } from "../../util/compactConversation";
import { ToolTip } from "../gui/Tooltip";
const ContextStatus = () => {
const dispatch = useAppDispatch();
const contextPercentage = useAppSelector(
(state) => state.session.contextPercentage,
);
const history = useAppSelector((state) => state.session.history);
const percent = Math.round((contextPercentage ?? 0) * 100);
const isPruned = useAppSelector((state) => state.session.isPruned);
const compactConversation = useCompactConversation();
if (!isPruned && percent < 60) {
return null;
}
const barColorClass = isPruned
? "bg-error"
: percent > 80
? "bg-warning"
: "bg-description";
return (
<div>
<ToolTip
id="context-status"
closeEvents={{
// blur: false,
mouseleave: true,
click: true,
mouseup: false,
}}
clickable
>
<div className="flex flex-col gap-0 text-xs">
<span className="inline-block">
{`${percent}% of context filled`}
</span>
{isPruned && (
<span className="inline-block">
{`Oldest messages are being removed`}
</span>
)}
{history.length > 0 && (
<div className="flex flex-col gap-1 whitespace-pre">
<div>
<span
className="inline-block cursor-pointer underline"
onClick={() => compactConversation(history.length - 1)}
>
Compact conversation
</span>
{"\n"}
<span className="inline-block">or</span> {"\n"}
<span
className="inline-block cursor-pointer underline"
onClick={() => {
dispatch(
saveCurrentSession({
openNewSession: true,
generateTitle: false,
}),
);
}}
>
Start a new session
</span>
</div>
</div>
)}
</div>
</ToolTip>
<div
data-tooltip-id="context-status"
className="border-description-muted relative h-[14px] w-[7px] rounded-[1px] border-[0.5px] border-solid md:h-[10px] md:w-[5px]"
>
<div
className={`transition-height absolute bottom-0 left-0 w-full duration-300 ease-in-out ${barColorClass}`}
style={{ height: `${percent}%` }}
></div>
</div>
</div>
);
};
export default ContextStatus;

View file

@ -10,9 +10,6 @@ import { GradientBorder } from "./GradientBorder";
import { ToolbarOptions } from "./InputToolbar";
import { Lump } from "./Lump";
import { TipTapEditor } from "./TipTapEditor";
import WarningMessageBox from "./WarningMessageBox";
import EditConfigAction from "./WarningMessageBox/Actions/EditConfigAction";
import NewSessionAction from "./WarningMessageBox/Actions/NewSessionAction";
interface ContinueInputBoxProps {
isLastUserInput: boolean;
@ -43,9 +40,6 @@ const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [
function ContinueInputBox(props: ContinueInputBoxProps) {
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const warningMessage = useAppSelector(
(state) => state.session.warningMessage,
);
const availableSlashCommands = useAppSelector(
selectSlashCommandComboBoxInputs,
);
@ -125,19 +119,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
/>
</div>
)}
{props.isLastUserInput &&
warningMessage &&
(warningMessage.category === "exceeded-context-length" ? (
<WarningMessageBox
warningMessage={warningMessage}
actions={[NewSessionAction]}
/>
) : (
<WarningMessageBox
warningMessage={warningMessage}
actions={[EditConfigAction]}
/>
))}
</div>
);
}

View file

@ -0,0 +1,48 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { setInlineErrorMessage } from "../../redux/slices/sessionSlice";
export type InlineErrorMessageType = "out-of-context";
export default function InlineErrorMessage() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const inlineErrorMessage = useAppSelector(
(state) => state.session.inlineErrorMessage,
);
if (inlineErrorMessage === "out-of-context") {
return (
<div
className={`border-border relative m-2 flex flex-col rounded-md border border-solid bg-transparent p-4`}
>
<p className={`thread-message text-error text-center`}>
{`Message exceeds context limit.`}
</p>
<div className="text-description flex flex-row items-center justify-center gap-1.5 px-3">
<div
className="cursor-pointer text-xs hover:underline"
onClick={() => {
ideMessenger.post("config/openProfile", {
profileId: undefined,
});
}}
>
<span className="xs:flex hidden">Open config</span>
<span className="xs:hidden">Config</span>
</div>
|
<span
className="cursor-pointer text-xs hover:underline"
onClick={() => {
dispatch(setInlineErrorMessage(undefined));
}}
>
Hide
</span>
</div>
</div>
);
}
return null;
}

View file

@ -19,6 +19,7 @@ import ModelSelect from "../modelSelection/ModelSelect";
import { ModeSelect } from "../ModeSelect";
import { Button } from "../ui";
import { useFontSize } from "../ui/font";
import ContextStatus from "./ContextStatus";
import HoverItem from "./InputToolbar/HoverItem";
export interface ToolbarOptions {
@ -170,6 +171,7 @@ function InputToolbar(props: InputToolbarProps) {
fontSize: tinyFont,
}}
>
{!isInEdit && <ContextStatus />}
{!props.toolbarOptions?.hideUseCodebase && !isInEdit && (
<div
className={`${toolsSupported ? "md:flex" : "int:flex"} hover:underline" hidden transition-colors duration-200`}
@ -209,7 +211,6 @@ function InputToolbar(props: InputToolbarProps) {
</span>
</HoverItem>
)}
<Button
data-tooltip-id="enter-tooltip"
variant={props.isMainInput ? "primary" : "secondary"}

View file

@ -14,7 +14,7 @@ export function StreamingToolbar() {
onClick={() => void dispatch(cancelStream())}
className="text-2xs cursor-pointer px-1.5 py-0.5 hover:brightness-125"
>
<span className="text-description">Pause</span>
<span className="text-description">Stop</span>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
<span className="text-description-muted ml-1 opacity-75">
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()}⌫

View file

@ -15,6 +15,9 @@ export const SlashCommand = Node.create<SlashCommandOptions>({
addOptions() {
return {
suggestion: {
allow: ({ editor }) =>
// the first character is "/". we want to avoid slash commands when there is a space after it
editor.getText().at(1) !== " ",
char: "/",
pluginKey: new PluginKey(this.name),
startOfLine: true,

View file

@ -1,15 +0,0 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
export default function EditConfigAction() {
const ideMessenger = useContext(IdeMessengerContext);
return (
<span
onClick={() =>
ideMessenger.post("config/openProfile", { profileId: undefined })
}
className="hover:underline"
>
Open configuration file
</span>
);
}

View file

@ -1,10 +0,0 @@
import { useAppDispatch } from "../../../../redux/hooks";
import { newSession } from "../../../../redux/slices/sessionSlice";
export default function NewSessionAction() {
const dispatch = useAppDispatch();
return (
<span onClick={() => dispatch(newSession())} className="hover:underline">
Start a new session
</span>
);
}

View file

@ -1,41 +0,0 @@
import { ReactNode, useEffect, useRef, useState } from "react";
export default function ExpendableBox({ children }: { children: ReactNode }) {
const [isExpended, setIsExpended] = useState(false);
const [showTrigger, setShowTrigger] = useState(true);
const expendableDivRef = useRef<HTMLDivElement>(null);
const toggleExpendable = () => {
setIsExpended((pre) => !pre);
};
useEffect(() => {
if (expendableDivRef.current) {
expendableDivRef.current.style.maxHeight = isExpended ? "600px" : "0px";
}
if (isExpended) {
setShowTrigger(false);
} else {
setTimeout(() => setShowTrigger(true), 200);
}
}, [isExpended]);
return (
<div className="flex flex-col">
<div
onClick={toggleExpendable}
className={`h-[9px] w-[9px] self-end ${showTrigger ? "" : "hidden"} bg-warning my-2 mr-4 rounded-lg`}
></div>
<div
onClick={toggleExpendable}
ref={expendableDivRef}
style={{
transition: "max-height 0.3s ease-in-out",
overflowY: "hidden",
}}
>
{children}
</div>
</div>
);
}

View file

@ -1,55 +0,0 @@
import { WarningMessage } from "core";
import { ReactElement } from "react";
import ExpendableBox from "./ExpendableBox";
function MessageBox({
warningMessage,
actions,
}: {
warningMessage: WarningMessage;
actions?: (() => ReactElement)[];
}) {
const warningMessageTextColor =
warningMessage.level === "fatal" ? "text-error" : "text-warning";
const warningMessageBorderColor =
warningMessage.level === "fatal" ? "border-error" : "border-warning";
return (
<div
className={`relative m-2 flex flex-col rounded-md border border-solid ${warningMessageBorderColor} bg-transparent p-4`}
>
<p className={`thread-message ${warningMessageTextColor}`}>
<b>Warning: </b>
{`${warningMessage.message}`}
</p>
{actions && (
<div>
<p>{`Recommended Action${actions.length > 1 ? "s" : ""}:`}</p>
<ul>
{actions.map((action, ind) => {
return <li key={`warning-action-${ind}`}>{action()}</li>;
})}
</ul>
</div>
)}
</div>
);
}
export default function WarningMessageBox({
warningMessage,
actions,
}: {
warningMessage: WarningMessage;
actions?: (() => ReactElement)[];
}) {
if (warningMessage.category === "exceeded-context-length") {
return (
<ExpendableBox
children={
<MessageBox warningMessage={warningMessage} actions={actions} />
}
/>
);
}
return <MessageBox warningMessage={warningMessage} actions={actions} />;
}

View file

@ -218,7 +218,7 @@ function ModelSelect() {
{modelSelectTitle(selectedModel) || "Select model"}
</span>
<ChevronDownIcon
className="h-2 w-2 flex-shrink-0 hover:brightness-110"
className="hidden h-2 w-2 flex-shrink-0 hover:brightness-110 min-[200px]:flex"
aria-hidden="true"
/>
</ListboxButton>

View file

@ -3,7 +3,7 @@ import ReactDOM from "react-dom/client";
import Layout from "./components/console/Layout";
import "./indexConsole.css";
(async () => {
void (async () => {
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<Layout></Layout>

View file

@ -86,7 +86,8 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
},
"llm/compileChat": {
compiledChatMessages: [],
pruningStatus: "not-pruned",
didPrune: false,
contextPercentage: 0.5,
},
};

View file

@ -1,3 +1,7 @@
import {
calculateRequestCost,
CostBreakdown,
} from "core/llm/utils/calculateRequestCost";
import { useMemo } from "react";
import { LLMInteraction } from "./useLLMLog";
@ -62,6 +66,19 @@ export default function useLLMSummary(interaction: LLMInteraction) {
: undefined;
}
let costBreakdown: CostBreakdown | null = null;
if (
interaction.end?.usage &&
interaction.start?.provider &&
interaction.start?.options?.model
) {
costBreakdown = calculateRequestCost(
interaction.start.provider,
interaction.start.options.model,
interaction.end.usage,
);
}
return {
result,
type,
@ -71,6 +88,7 @@ export default function useLLMSummary(interaction: LLMInteraction) {
promptTokens,
generatedTokens,
thinkingTokens,
costBreakdown,
};
}, [interaction]);
}

View file

@ -0,0 +1,102 @@
import {
calculateRequestCost,
CostBreakdown,
} from "core/llm/utils/calculateRequestCost";
import { useMemo } from "react";
import { LLMLog } from "./useLLMLog";
export interface TotalUsage {
totalPromptTokens: number;
totalGeneratedTokens: number;
totalThinkingTokens: number;
totalCachedTokens: number;
totalCacheWriteTokens: number;
totalInteractions: number;
totalSuccessfulInteractions: number;
totalErrorInteractions: number;
totalCancelledInteractions: number;
totalCost: number;
costBreakdowns: CostBreakdown[];
}
/**
* Hook to calculate total usage across all interactions in the LLM log
*/
export default function useTotalUsage(llmLog: LLMLog): TotalUsage {
return useMemo(() => {
let totalPromptTokens = 0;
let totalGeneratedTokens = 0;
let totalThinkingTokens = 0;
let totalCachedTokens = 0;
let totalCacheWriteTokens = 0;
let totalInteractions = 0;
let totalSuccessfulInteractions = 0;
let totalErrorInteractions = 0;
let totalCancelledInteractions = 0;
let totalCost = 0;
const costBreakdowns: CostBreakdown[] = [];
// Iterate through all interactions
for (const interaction of llmLog.interactions.values()) {
if (interaction.end) {
totalInteractions++;
// Add basic token counts
totalPromptTokens += interaction.end.promptTokens || 0;
totalGeneratedTokens += interaction.end.generatedTokens || 0;
totalThinkingTokens += interaction.end.thinkingTokens || 0;
// Add cache-related tokens from usage if available
if (interaction.end.usage) {
const usage = interaction.end.usage;
totalCachedTokens += usage.promptTokensDetails?.cachedTokens || 0;
totalCacheWriteTokens +=
usage.promptTokensDetails?.cacheWriteTokens || 0;
// Calculate cost if we have the necessary information
if (
interaction.start?.provider &&
interaction.start?.options?.model
) {
const costBreakdown = calculateRequestCost(
interaction.start.provider,
interaction.start.options.model,
usage,
);
if (costBreakdown) {
totalCost += costBreakdown.cost;
costBreakdowns.push(costBreakdown);
}
}
}
// Count interaction outcomes
switch (interaction.end.kind) {
case "success":
totalSuccessfulInteractions++;
break;
case "error":
totalErrorInteractions++;
break;
case "cancel":
totalCancelledInteractions++;
break;
}
}
}
return {
totalPromptTokens,
totalGeneratedTokens,
totalThinkingTokens,
totalCachedTokens,
totalCacheWriteTokens,
totalInteractions,
totalSuccessfulInteractions,
totalErrorInteractions,
totalCancelledInteractions,
totalCost,
costBreakdowns,
};
}, [llmLog]);
}

View file

@ -1,13 +1,14 @@
import {
ArrowTopRightOnSquareIcon,
DocumentArrowUpIcon,
NumberedListIcon,
PaintBrushIcon,
TableCellsIcon,
} from "@heroicons/react/24/outline";
import { useContext } from "react";
import { useNavigate } from "react-router-dom";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch } from "../../redux/hooks";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { setOnboardingCard } from "../../redux/slices/uiSlice";
import { saveCurrentSession } from "../../redux/thunks/session";
import { ROUTES } from "../../util/navigation";
@ -18,6 +19,21 @@ export function HelpCenterSection() {
const navigate = useNavigate();
const dispatch = useAppDispatch();
const currentSession = useAppSelector((state) => state.session);
const handleViewSessionData = async () => {
const sessionData = await ideMessenger.request("history/load", {
id: currentSession.id,
});
if (sessionData.status === "success") {
await ideMessenger.request("showVirtualFile", {
name: `${sessionData.content.title}.json`,
content: JSON.stringify(sessionData.content, null, 2),
});
}
};
return (
<div className="py-5">
<h3 className="mb-4 mt-0 text-xl">Help center</h3>
@ -68,6 +84,15 @@ export function HelpCenterSection() {
onClick={() => navigate("/stats")}
/>
{currentSession.history.length > 0 && !currentSession.isStreaming && (
<MoreHelpRow
title="View current session history"
description="Open the current chat session file for troubleshooting"
Icon={NumberedListIcon}
onClick={handleViewSessionData}
/>
)}
<MoreHelpRow
title="Quickstart"
description="Reopen the quickstart and tutorial file"

View file

@ -3,7 +3,7 @@ import {
ChatBubbleOvalLeftIcon,
} from "@heroicons/react/24/outline";
import { Editor, JSONContent } from "@tiptap/react";
import { InputModifiers } from "core";
import { ChatHistoryItem, InputModifiers } from "core";
import { renderChatMessage } from "core/util/messageContent";
import {
useCallback,
@ -43,11 +43,22 @@ import { streamResponseThunk } from "../../redux/thunks/streamResponse";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
import { ToolCallDiv } from "./ToolCallDiv";
import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage";
import { cancelStream } from "../../redux/thunks/cancelStream";
import { EmptyChatBody } from "./EmptyChatBody";
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
import { useAutoScroll } from "./useAutoScroll";
// Helper function to find the index of the latest conversation summary
function findLatestSummaryIndex(history: ChatHistoryItem[]): number {
for (let i = history.length - 1; i >= 0; i--) {
if (history[i].conversationSummary) {
return i;
}
}
return -1; // No summary found
}
const StepsDiv = styled.div`
position: relative;
background-color: transparent;
@ -113,9 +124,6 @@ export function Chat() {
const jetbrains = useMemo(() => {
return isJetBrains();
}, []);
const warningMessage = useAppSelector(
(state) => state.session.warningMessage,
);
useAutoScroll(stepsDivRef, history);
@ -128,7 +136,6 @@ export function Chat() {
!e.shiftKey
) {
void dispatch(cancelStream());
if (isInEdit) ideMessenger.post("rejectDiff", {});
}
};
window.addEventListener("keydown", listener);
@ -273,19 +280,26 @@ export function Chat() {
toolCallStates,
} = item;
// Calculate once for the entire function
const latestSummaryIndex = findLatestSummaryIndex(history);
const isBeforeLatestSummary =
latestSummaryIndex !== -1 && index < latestSummaryIndex;
if (message.role === "user") {
return (
<ContinueInputBox
onEnter={(editorState, modifiers) =>
sendInput(editorState, modifiers, index)
}
isLastUserInput={isLastUserInput(index)}
isMainInput={false}
editorState={editorState}
contextItems={contextItems}
appliedRules={appliedRules}
inputId={message.id}
/>
<div className={isBeforeLatestSummary ? "opacity-50" : ""}>
<ContinueInputBox
onEnter={(editorState, modifiers) =>
sendInput(editorState, modifiers, index)
}
isLastUserInput={isLastUserInput(index)}
isMainInput={false}
editorState={editorState}
contextItems={contextItems}
appliedRules={appliedRules}
inputId={message.id}
/>
</div>
);
}
@ -314,6 +328,7 @@ export function Chat() {
index={index}
isLast={index === history.length - 1}
item={item}
latestSummaryIndex={latestSummaryIndex}
/>
</TimelineItem>
</div>
@ -330,14 +345,16 @@ export function Chat() {
if (message.role === "thinking") {
return (
<ThinkingBlockPeek
content={renderChatMessage(message)}
redactedThinking={message.redactedThinking}
index={index}
prevItem={index > 0 ? history[index - 1] : null}
inProgress={index === history.length - 1}
signature={message.signature}
/>
<div className={isBeforeLatestSummary ? "opacity-50" : ""}>
<ThinkingBlockPeek
content={renderChatMessage(message)}
redactedThinking={message.redactedThinking}
index={index}
prevItem={index > 0 ? history[index - 1] : null}
inProgress={index === history.length - 1}
signature={message.signature}
/>
</div>
);
}
@ -356,6 +373,7 @@ export function Chat() {
index={index}
isLast={index === history.length - 1}
item={item}
latestSummaryIndex={latestSummaryIndex}
/>
</TimelineItem>
</div>
@ -391,6 +409,7 @@ export function Chat() {
>
{renderChatHistoryItem(item, index)}
</ErrorBoundary>
{index === history.length - 1 && <InlineErrorMessage />}
</div>
))}
</StepsDiv>
@ -412,21 +431,19 @@ export function Chat() {
<div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2">
<div className="xs:inline hidden">
{history.length === 0 && lastSessionId && !isInEdit && (
<div className="xs:inline hidden">
<NewSessionButton
onClick={async () => {
await dispatch(
loadLastSession({
saveCurrentSession: true,
}),
);
}}
className="flex items-center gap-2"
>
<ArrowLeftIcon className="h-3 w-3" />
<span className="text-xs">Last Session</span>
</NewSessionButton>
</div>
<NewSessionButton
onClick={async () => {
await dispatch(
loadLastSession({
saveCurrentSession: true,
}),
);
}}
className="flex items-center gap-2"
>
<ArrowLeftIcon className="h-3 w-3" />
<span className="text-xs">Last Session</span>
</NewSessionButton>
)}
</div>
</div>

View file

@ -75,6 +75,7 @@ describe("sessionSlice streamUpdate", () => {
},
newestToolbarPreviewForInput: {},
isSessionMetadataLoading: false,
compactionLoading: {},
});
describe("Basic Chat Message", () => {

View file

@ -23,7 +23,6 @@ import {
Tool,
ToolCallDelta,
ToolCallState,
WarningMessage,
} from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import { NEW_SESSION_TITLE } from "core/util/constants";
@ -34,6 +33,7 @@ import {
import { findUriInDirs, getUriPathBasename } from "core/util/uri";
import { findLastIndex } from "lodash";
import { v4 as uuidv4 } from "uuid";
import { type InlineErrorMessageType } from "../../components/mainInput/InlineErrorMessage";
import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/utils";
import { addToolCallDeltaToState } from "../../util/toolCallState";
import { RootState } from "../store";
@ -224,7 +224,10 @@ type SessionState = {
};
newestToolbarPreviewForInput: Record<string, string>;
hasReasoningEnabled?: boolean;
warningMessage?: WarningMessage;
isPruned?: boolean;
contextPercentage?: number;
inlineErrorMessage?: InlineErrorMessageType;
compactionLoading: Record<number, boolean>; // Track compaction loading by message index
};
const initialState: SessionState = {
@ -244,6 +247,7 @@ const initialState: SessionState = {
},
lastSessionId: undefined,
newestToolbarPreviewForInput: {},
compactionLoading: {},
};
export const sessionSlice = createSlice({
@ -287,6 +291,7 @@ export const sessionSlice = createSlice({
if (state.history.length < 2) {
return;
}
const lastUserOrToolIdx = findLastIndex(
state.history,
(item) => item.message.role === "tool" || item.message.role === "user",
@ -313,7 +318,14 @@ export const sessionSlice = createSlice({
}
if (validAssistantMessageIdx === -1) {
state.history = state.history.slice(0, lastUserOrToolIdx + 1);
const lastMsg = state.history[lastUserOrToolIdx];
const lastRole = lastMsg.message.role as "user" | "tool";
if (lastRole === "user") {
state.mainEditorContentTrigger = lastMsg.editorState;
state.history = state.history.slice(0, lastUserOrToolIdx);
} else {
state.history = state.history.slice(0, lastUserOrToolIdx + 1);
}
} else {
state.history = state.history.slice(0, validAssistantMessageIdx + 1);
}
@ -421,12 +433,27 @@ export const sessionSlice = createSlice({
},
contextItems: [],
});
state.inlineErrorMessage = undefined;
state.isPruned = false;
state.contextPercentage = undefined;
}
},
deleteMessage: (state, action: PayloadAction<number>) => {
// Deletes the current assistant message and the previous user message
state.history.splice(action.payload - 1, 2);
state.warningMessage = undefined;
state.inlineErrorMessage = undefined;
state.isPruned = false;
state.contextPercentage = undefined;
},
deleteCompaction: (state, action: PayloadAction<number>) => {
// Removes the conversation summary from the specified message
const historyItem = state.history[action.payload];
if (historyItem?.conversationSummary) {
state.history[action.payload] = {
...historyItem,
conversationSummary: undefined,
};
}
},
updateHistoryItemAtIndex: (
state,
@ -637,6 +664,10 @@ export const sessionSlice = createSlice({
state.isStreaming = false;
state.symbols = {};
state.inlineErrorMessage = undefined;
state.isPruned = false;
state.contextPercentage = undefined;
if (payload) {
state.history = payload.history as any;
state.title = payload.title;
@ -892,11 +923,28 @@ export const sessionSlice = createSlice({
state.newestToolbarPreviewForInput[payload.inputId] =
payload.contextItemId;
},
setWarningMessage: (
setCompactionLoading: (
state,
action: PayloadAction<WarningMessage | undefined>,
action: PayloadAction<{ index: number; loading: boolean }>,
) => {
state.warningMessage = action.payload;
const { index, loading } = action.payload;
if (loading) {
state.compactionLoading[index] = true;
} else {
delete state.compactionLoading[index];
}
},
setInlineErrorMessage: (
state,
action: PayloadAction<SessionState["inlineErrorMessage"]>,
) => {
state.inlineErrorMessage = action.payload;
},
setIsPruned: (state, action: PayloadAction<boolean>) => {
state.isPruned = action.payload;
},
setContextPercentage: (state, action: PayloadAction<number>) => {
state.contextPercentage = action.payload;
},
},
selectors: {
@ -962,6 +1010,7 @@ export const {
clearDanglingMessages,
setMainEditorContentTrigger,
deleteMessage,
deleteCompaction,
setIsGatheringContext,
resetNextCodeBlockToApplyIndex,
updateApplyState,
@ -981,7 +1030,10 @@ export const {
setNewestToolbarPreviewForInput,
setIsInEdit,
setHasReasoningEnabled,
setWarningMessage,
setInlineErrorMessage,
setIsPruned,
setContextPercentage,
setCompactionLoading,
} = sessionSlice.actions;
export const { selectIsGatheringContext } = sessionSlice.selectors;

View file

@ -11,9 +11,11 @@ import {
addPromptCompletionPair,
setActive,
setAppliedRulesAtIndex,
setContextPercentage,
setInactive,
setInlineErrorMessage,
setIsPruned,
setToolGenerated,
setWarningMessage,
streamUpdate,
} from "../slices/sessionSlice";
import { AppThunkDispatch, RootState, ThunkApiType } from "../store";
@ -184,42 +186,29 @@ export const streamNormalInput = createAsyncThunk<
);
dispatch(setActive());
// Remove the warning message before each compileChat call
dispatch(setWarningMessage(undefined));
dispatch(setInlineErrorMessage(undefined));
const precompiledRes = await extra.ideMessenger.request("llm/compileChat", {
messages,
options: completionOptions,
});
if (precompiledRes.status === "error") {
throw new Error(precompiledRes.error);
}
const { compiledChatMessages, pruningStatus } = precompiledRes.content;
switch (pruningStatus) {
case "pruned":
dispatch(
setWarningMessage({
message: `Chat history exceeds model's context length (${state.config.config.selectedModelByRole.chat?.contextLength} tokens). Old messages will not be included.`,
level: "warning",
category: "exceeded-context-length",
}),
);
break;
case "deleted-last-input":
dispatch(
setWarningMessage({
message:
"The provided context items are too large. Please trim the context item to fit the model's context length or increase the model's context length by editing the configuration.",
level: "fatal",
category: "deleted-last-input",
}),
);
if (precompiledRes.error.includes("Not enough context")) {
dispatch(setInlineErrorMessage("out-of-context"));
dispatch(setInactive());
return;
} else {
throw new Error(precompiledRes.error);
}
}
const { compiledChatMessages, didPrune, contextPercentage } =
precompiledRes.content;
dispatch(setIsPruned(didPrune));
dispatch(setContextPercentage(contextPercentage));
// Send request and stream response
const streamAborter = state.session.streamAborter;
const gen = extra.ideMessenger.llmStreamChat(

View file

@ -40,7 +40,21 @@ export function constructMessages(
appliedRules: RuleWithSource[];
appliedRuleIndex: number;
} {
const historyCopy = [...history];
// Find the most recent conversation summary and filter history accordingly
let summaryContent = "";
let filteredHistory = history;
for (let i = history.length - 1; i >= 0; i--) {
const summary = history[i].conversationSummary;
if (summary) {
summaryContent = summary;
// Only include messages that come AFTER the message with the summary
filteredHistory = history.slice(i + 1);
break;
}
}
const historyCopy = [...filteredHistory];
const msgs: MessageWithContextItems[] = [];
let appliedRuleIndex = -1;
@ -160,12 +174,20 @@ export function constructMessages(
rulePolicies,
});
if (systemMessage.trim()) {
// Append conversation summary to system message if it exists
let finalSystemMessage = systemMessage;
if (summaryContent) {
finalSystemMessage = systemMessage
? `${systemMessage}\n\nPrevious conversation summary:\n\n ${summaryContent}`
: `Previous conversation summary:\n\n ${summaryContent}`;
}
if (finalSystemMessage.trim()) {
msgs.unshift({
ctxItems: [],
message: {
role: "system",
content: systemMessage,
content: finalSystemMessage,
},
});
}

View file

@ -0,0 +1,58 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import {
setCompactionLoading,
deleteCompaction,
} from "../redux/slices/sessionSlice";
import { loadSession, saveCurrentSession } from "../redux/thunks/session";
export const useCompactConversation = () => {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const currentSessionId = useAppSelector((state) => state.session.id);
return async (index: number) => {
if (!currentSessionId) {
return;
}
try {
// Set loading state
dispatch(setCompactionLoading({ index, loading: true }));
await ideMessenger.request("conversation/compact", {
index,
sessionId: currentSessionId,
});
// Reload the current session to refresh the conversation state
dispatch(
loadSession({
sessionId: currentSessionId,
saveCurrentSession: false,
}),
);
} catch (error) {
console.error("Error compacting conversation:", error);
} finally {
// Clear loading state
dispatch(setCompactionLoading({ index, loading: false }));
}
};
};
export const useDeleteCompaction = () => {
const dispatch = useAppDispatch();
return (index: number) => {
// Update local state and save to persistence
dispatch(deleteCompaction(index));
dispatch(
saveCurrentSession({
openNewSession: false,
generateTitle: false,
}),
);
};
};

2
package-lock.json generated
View file

@ -1,5 +1,5 @@
{
"name": "continue",
"name": "wt-openai-adapters-tests",
"lockfileVersion": 3,
"requires": true,
"packages": {

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,91 @@
import { PackageIdentifier } from "../interfaces/slugs.js";
import { parseMarkdownRuleOrAssistantUnrolled } from "./unroll.js";
describe("parseMarkdownRuleOrAssistantUnrolled tests", () => {
it("parses valid YAML content as AssistantUnrolled", () => {
const mockId: PackageIdentifier = {
uriType: "file",
filePath: "./foo/bar.yaml",
};
const yamlContent = `
name: Test Assistant
version: 1.0.0
models:
- name: model
model: modelname
provider: ollama
`;
const result = parseMarkdownRuleOrAssistantUnrolled(yamlContent, mockId);
expect(result).toHaveProperty("name", "Test Assistant");
expect(result).toHaveProperty("version", "1.0.0");
expect(result.models?.length).toBe(1);
expect(result.models?.[0]).toHaveProperty("name", "model");
});
it("parses markdown rule content as AssistantUnrolled", () => {
const mockId: PackageIdentifier = {
uriType: "file",
filePath: "./foo/bar.md",
};
const markdownContent = `
---
name: rulename
description: my rule description
pattern: "**"
---
This is the rule
`;
const result = parseMarkdownRuleOrAssistantUnrolled(
markdownContent,
mockId,
);
expect(result).toHaveProperty("name");
expect(result).toHaveProperty("version");
expect(Array.isArray(result.rules)).toBe(true);
expect(result.rules).toBeDefined();
expect(result.rules!.length).toBe(1);
const rule = result.rules![0];
expect(rule).toHaveProperty("name", "rulename");
expect(rule).toHaveProperty("description", "my rule description");
expect(rule).toHaveProperty("globs", "./foo/**/*");
expect(rule).toHaveProperty("rule", "This is the rule");
});
it("throws error for invalid content in yaml file", () => {
const mockId: PackageIdentifier = {
uriType: "file",
filePath: "./foo/bar.yaml",
};
const invalidContent = `
name: Test Assistant
version: 1.0.0
model: # should be models
- name: model
model: modelname
provider: ollama
`;
expect(() =>
parseMarkdownRuleOrAssistantUnrolled(invalidContent, mockId),
).toThrow();
});
it("Every non-YAML file is a rule", () => {
const mockId: PackageIdentifier = {
uriType: "file",
filePath: "./foo/bar",
};
const dubiousContent = `This is not \nproper #YAML#`;
const result = parseMarkdownRuleOrAssistantUnrolled(dubiousContent, mockId);
expect(result).toHaveProperty("name");
expect(result).toHaveProperty("version");
expect(Array.isArray(result.rules)).toBe(true);
expect(result.rules).toBeDefined();
expect(result.rules!.length).toBe(1);
const rule = result.rules![0];
expect(rule).toHaveProperty("name", "foo/bar");
expect(rule).toHaveProperty("globs", "./foo/**/*");
expect(rule).toHaveProperty("rule", dubiousContent);
});
});

View file

@ -286,9 +286,7 @@ export async function unrollAssistantFromContent(
options.platformClient,
options.alwaysUseProxy,
);
const renderedYaml = renderTemplateData(templatedYaml, {
secrets,
});
const renderedYaml = renderTemplateData(templatedYaml, { secrets });
// Parse again and replace models with proxy versions where secrets weren't rendered
const finalConfig = useProxyForUnrenderedSecrets(
@ -298,11 +296,7 @@ export async function unrollAssistantFromContent(
options.onPremProxyUrl,
);
return {
config: finalConfig,
errors,
configLoadInterrupted,
};
return { config: finalConfig, errors, configLoadInterrupted };
}
export async function unrollBlocks(
@ -366,10 +360,7 @@ export async function unrollBlocks(
return {
index,
block: null,
error: {
fatal: false,
message: msg,
},
error: { fatal: false, message: msg },
};
}
} else {
@ -461,11 +452,7 @@ export async function unrollBlocks(
registry,
);
return {
blockType,
resolvedBlock,
error: null,
};
return { blockType, resolvedBlock, error: null };
} catch (err) {
let msg = "";
if (injectBlock.uriType === "file") {
@ -481,10 +468,7 @@ export async function unrollBlocks(
return {
blockType: null,
resolvedBlock: null,
error: {
fatal: false,
message: msg,
},
error: { fatal: false, message: msg },
};
}
});
@ -581,57 +565,46 @@ export async function resolveBlock(
return parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id);
}
function parseMarkdownRuleOrAssistantUnrolled(
export function parseMarkdownRuleOrAssistantUnrolled(
content: string,
id: PackageIdentifier,
): AssistantUnrolled {
// Try to parse as YAML first, then as markdown rule if that fails
let parsedYaml: AssistantUnrolled;
try {
parsedYaml = parseBlock(content);
} catch (yamlError) {
// If YAML parsing fails, try parsing as markdown rule
try {
const rule = markdownToRule(content, id);
// Convert the rule object to the expected format
parsedYaml = {
name: rule.name,
version: "1.0.0",
rules: [rule],
};
} catch (markdownError) {
// If both fail, throw the original YAML error
throw yamlError;
}
}
return parsedYaml;
return parseYamlOrMarkdownRule<AssistantUnrolled>(content, id, parseBlock);
}
function parseMarkdownRuleOrConfigYaml(
content: string,
id: PackageIdentifier,
): ConfigYaml {
// Try to parse as YAML first, then as markdown rule if that fails
let parsedYaml: ConfigYaml;
return parseYamlOrMarkdownRule<ConfigYaml>(content, id, parseConfigYaml);
}
function parseYamlOrMarkdownRule<T>(
content: string,
id: PackageIdentifier,
parseYamlFn: (content: string) => T,
): T {
let parsedYaml: T;
try {
parsedYaml = parseConfigYaml(content);
// Try to parse as YAML first, then as markdown rule if that fails
parsedYaml = parseYamlFn(content);
} catch (yamlError) {
if (
id.uriType === "file" &&
[".yaml", ".yml"].some((ext) => id.filePath.endsWith(ext))
) {
throw yamlError;
}
// If YAML parsing fails, try parsing as markdown rule
try {
const rule = markdownToRule(content, id);
// Convert the rule object to the expected format
parsedYaml = {
name: rule.name,
version: "1.0.0",
rules: [rule],
};
parsedYaml = { name: rule.name, version: "1.0.0", rules: [rule] } as T;
} catch (markdownError) {
// If both fail, throw the original YAML error
throw yamlError;
}
}
return parsedYaml;
}

View file

@ -71,7 +71,10 @@ export function createOpenAIClient({
);
}
if (!("apiKeyLocation" in modelConfig) && !("envSecretLocations" in modelConfig)) {
if (
!("apiKeyLocation" in modelConfig) &&
!("envSecretLocations" in modelConfig)
) {
throw new Error(
`Model ${modelName} does not have an apiKeyLocation or envSecretLocations defined`,
);

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.45",
"version": "1.0.46",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
"test": "vitest",
"build": "tsc"
},
"author": "Nate Sesti and Ty Dunn",
@ -25,11 +25,19 @@
"zod": "^3.24.2"
},
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/commit-analyzer": "^13.0.1",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^11.0.3",
"@semantic-release/npm": "^12.0.2",
"@semantic-release/release-notes-generator": "^14.0.3",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.14",
"@types/json-schema": "^7.0.15",
"cross-env": "^7.0.3",
"semantic-release": "^24.2.7",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2"
"ts-node": "^10.9.2",
"vitest": "^1.6.1"
}
}

View file

@ -8,12 +8,22 @@ import {
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
CompletionUsage,
} from "openai/resources/index";
import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
import { AnthropicConfig } from "../types.js";
import { chatChunk, chatChunkFromDelta, customFetch } from "../util.js";
import {
chatChunk,
chatChunkFromDelta,
customFetch,
usageChatChunk,
} from "../util.js";
import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
import { safeParseArgs } from "../util/parseArgs.js";
import {
CACHING_STRATEGIES,
CachingStrategyName,
} from "./AnthropicCachingStrategies.js";
import {
BaseLlmApi,
CreateRerankResponse,
@ -24,7 +34,11 @@ import {
export class AnthropicApi implements BaseLlmApi {
apiBase: string = "https://api.anthropic.com/v1/";
constructor(protected config: AnthropicConfig) {
constructor(
protected config: AnthropicConfig & {
cachingStrategy?: CachingStrategyName;
},
) {
this.apiBase = config.apiBase ?? this.apiBase;
if (!this.apiBase.endsWith("/")) {
this.apiBase += "/";
@ -32,6 +46,16 @@ export class AnthropicApi implements BaseLlmApi {
}
private _convertBody(oaiBody: ChatCompletionCreateParams) {
// Step 1: Convert to clean Anthropic body (no caching)
const cleanBody = this._convertToCleanAnthropicBody(oaiBody);
// Step 2: Apply caching strategy
const cachingStrategy =
CACHING_STRATEGIES[this.config.cachingStrategy ?? "systemAndTools"];
return cachingStrategy(cleanBody);
}
private _convertToCleanAnthropicBody(oaiBody: ChatCompletionCreateParams) {
let stop = undefined;
if (oaiBody.stop && Array.isArray(oaiBody.stop)) {
stop = oaiBody.stop.filter((x) => x.trim() !== "");
@ -52,7 +76,6 @@ export class AnthropicApi implements BaseLlmApi {
{
type: "text",
text: systemMessage,
cache_control: { type: "ephemeral" },
},
]
: systemMessage,
@ -155,6 +178,7 @@ export class AnthropicApi implements BaseLlmApi {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"anthropic-beta": "prompt-caching-2024-07-31",
"x-api-key": this.config.apiKey,
},
body: JSON.stringify(this._convertBody(body)),
@ -177,6 +201,9 @@ export class AnthropicApi implements BaseLlmApi {
completion.usage.input_tokens + completion.usage.output_tokens,
completion_tokens: completion.usage.output_tokens,
prompt_tokens: completion.usage.input_tokens,
prompt_tokens_details: {
cached_tokens: completion.usage.cache_read_input_tokens || 0,
},
},
choices: [
{
@ -205,6 +232,7 @@ export class AnthropicApi implements BaseLlmApi {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"anthropic-beta": "prompt-caching-2024-07-31",
"x-api-key": this.config.apiKey,
},
body: JSON.stringify(this._convertBody(body)),
@ -214,6 +242,12 @@ export class AnthropicApi implements BaseLlmApi {
let lastToolUseId: string | undefined;
let lastToolUseName: string | undefined;
const usage: CompletionUsage = {
completion_tokens: 0,
prompt_tokens: 0,
total_tokens: 0,
};
for await (const value of streamSse(response as any)) {
// https://docs.anthropic.com/en/api/messages-streaming#event-types
switch (value.type) {
@ -223,6 +257,15 @@ export class AnthropicApi implements BaseLlmApi {
lastToolUseName = value.content_block.name;
}
break;
case "message_start":
usage.prompt_tokens = value.message.usage.input_tokens;
usage.prompt_tokens_details = {
cached_tokens: value.message.usage.cache_read_input_tokens || 0,
};
break;
case "message_delta":
usage.completion_tokens = value.usage.output_tokens;
break;
case "content_block_delta":
// https://docs.anthropic.com/en/api/messages-streaming#delta-types
switch (value.delta.type) {
@ -263,6 +306,14 @@ export class AnthropicApi implements BaseLlmApi {
break;
}
}
yield usageChatChunk({
model: body.model,
usage: {
...usage,
total_tokens: usage.completion_tokens + usage.prompt_tokens,
},
});
}
async completionNonStream(
body: CompletionCreateParamsNonStreaming,

View file

@ -0,0 +1,369 @@
import {
CACHING_STRATEGIES,
CachingStrategy,
CachingStrategyName,
getAvailableStrategies,
getStrategyDescription,
} from "./AnthropicCachingStrategies.js";
describe("AnthropicCachingStrategies", () => {
describe("noCachingStrategy", () => {
it("should return the body unchanged", () => {
const body = { system: "test", messages: [] };
const result = CACHING_STRATEGIES.none(body);
expect(result).toBe(body);
});
it("should not modify complex objects", () => {
const body = {
system: [{ text: "test" }],
tools: [{ name: "test" }],
messages: [{ content: "test" }],
};
const result = CACHING_STRATEGIES.none(body);
expect(result).toBe(body);
});
});
describe("systemOnlyStrategy", () => {
it("should add cache_control to system messages array", () => {
const body = {
system: [{ text: "system message 1" }, { text: "system message 2" }],
messages: [{ content: "user message" }],
};
const result = CACHING_STRATEGIES.systemOnly(body);
expect(result.system).toEqual([
{ text: "system message 1", cache_control: { type: "ephemeral" } },
{ text: "system message 2", cache_control: { type: "ephemeral" } },
]);
expect(result.messages).toEqual(body.messages);
});
it("should return body unchanged if system is not an array", () => {
const body = {
system: "string system message",
messages: [{ content: "user message" }],
};
const result = CACHING_STRATEGIES.systemOnly(body);
expect(result).toEqual(body);
});
it("should return body unchanged if system is undefined", () => {
const body = {
messages: [{ content: "user message" }],
};
const result = CACHING_STRATEGIES.systemOnly(body);
expect(result).toEqual(body);
});
});
describe("systemAndToolsStrategy", () => {
it("should add cache_control to both system and tools", () => {
const body = {
system: [{ text: "system message" }],
tools: [{ name: "tool1" }, { name: "tool2" }],
messages: [{ content: "user message" }],
};
const result = CACHING_STRATEGIES.systemAndTools(body);
expect(result.system).toEqual([
{ text: "system message", cache_control: { type: "ephemeral" } },
]);
expect(result.tools).toEqual([
{ name: "tool1" },
{ name: "tool2", cache_control: { type: "ephemeral" } },
]);
expect(result.messages).toEqual(body.messages);
});
it("should handle missing system messages", () => {
const body = {
tools: [{ name: "tool1" }],
messages: [{ content: "user message" }],
};
const result = CACHING_STRATEGIES.systemAndTools(body);
expect(result.tools).toEqual([
{ name: "tool1", cache_control: { type: "ephemeral" } },
]);
expect(result.messages).toEqual(body.messages);
});
it("should handle missing tools", () => {
const body = {
system: [{ text: "system message" }],
messages: [{ content: "user message" }],
};
const result = CACHING_STRATEGIES.systemAndTools(body);
expect(result.system).toEqual([
{ text: "system message", cache_control: { type: "ephemeral" } },
]);
expect(result.messages).toEqual(body.messages);
});
it("should handle non-array system and tools", () => {
const body = {
system: "string system",
tools: "string tools",
messages: [{ content: "user message" }],
};
const result = CACHING_STRATEGIES.systemAndTools(body);
expect(result).toEqual(body);
});
});
describe("optimizedStrategy", () => {
it("should cache system messages and tools", () => {
const body = {
system: [{ text: "system message" }],
tools: [{ name: "tool1" }],
messages: [{ content: "short message" }],
};
const result = CACHING_STRATEGIES.optimized(body);
expect(result.system).toEqual([
{ text: "system message", cache_control: { type: "ephemeral" } },
]);
expect(result.tools).toEqual([
{ name: "tool1", cache_control: { type: "ephemeral" } },
]);
});
it("should cache large string messages (>500 tokens)", () => {
const largeContent = "a".repeat(2100); // ~525 tokens
const body = {
messages: [{ content: largeContent }],
};
const result = CACHING_STRATEGIES.optimized(body);
expect(result.messages).toEqual([
{
content: [
{
type: "text",
text: largeContent,
cache_control: { type: "ephemeral" },
},
],
},
]);
});
it("should not cache small string messages (<500 tokens)", () => {
const smallContent = "a".repeat(100); // ~25 tokens
const body = {
messages: [{ content: smallContent }],
};
const result = CACHING_STRATEGIES.optimized(body);
expect(result.messages).toEqual([{ content: smallContent }]);
});
it("should cache large text items in array content", () => {
const largeText = "a".repeat(2100); // ~525 tokens
const smallText = "a".repeat(100); // ~25 tokens
const body = {
messages: [
{
content: [
{ type: "text", text: largeText },
{ type: "text", text: smallText },
{ type: "image", data: "image_data" },
],
},
],
};
const result = CACHING_STRATEGIES.optimized(body);
expect(result.messages).toEqual([
{
content: [
{
type: "text",
text: largeText,
cache_control: { type: "ephemeral" },
},
{ type: "text", text: smallText },
{ type: "image", data: "image_data" },
],
},
]);
});
it("should handle complex message structure", () => {
const body = {
system: [{ text: "system" }],
tools: [{ name: "tool" }],
messages: [
{ content: "small content" },
{ content: "a".repeat(2100) }, // large content
{
content: [
{ type: "text", text: "a".repeat(2100) }, // large text
{ type: "image", data: "image" },
],
},
],
};
const result = CACHING_STRATEGIES.optimized(body);
expect(result.system).toEqual([
{ text: "system", cache_control: { type: "ephemeral" } },
]);
expect(result.tools).toEqual([
{ name: "tool", cache_control: { type: "ephemeral" } },
]);
expect(result.messages[0]).toEqual({ content: "small content" });
expect(result.messages[1]).toEqual({
content: [
{
type: "text",
text: "a".repeat(2100),
cache_control: { type: "ephemeral" },
},
],
});
expect(result.messages[2].content[0]).toEqual({
type: "text",
text: "a".repeat(2100),
cache_control: { type: "ephemeral" },
});
});
it("should handle empty or missing messages", () => {
const body = {
system: [{ text: "system" }],
};
const result = CACHING_STRATEGIES.optimized(body);
expect(result.system).toEqual([
{ text: "system", cache_control: { type: "ephemeral" } },
]);
expect(result.messages).toBeUndefined();
});
it("should handle non-array messages", () => {
const body = {
system: [{ text: "system" }],
messages: "not an array",
};
const result = CACHING_STRATEGIES.optimized(body);
expect(result.system).toEqual([
{ text: "system", cache_control: { type: "ephemeral" } },
]);
expect(result.messages).toBe("not an array");
});
});
describe("estimateTokenCount", () => {
it("should estimate token count correctly", () => {
// Test through the optimized strategy's behavior
const smallContent = "a".repeat(100); // ~25 tokens
const largeContent = "a".repeat(2100); // ~525 tokens
const bodySmall = { messages: [{ content: smallContent }] };
const bodyLarge = { messages: [{ content: largeContent }] };
const resultSmall = CACHING_STRATEGIES.optimized(bodySmall);
const resultLarge = CACHING_STRATEGIES.optimized(bodyLarge);
// Small content should not be cached (remains string)
expect(resultSmall.messages[0].content).toBe(smallContent);
// Large content should be cached (converted to array)
expect(Array.isArray(resultLarge.messages[0].content)).toBe(true);
});
});
describe("getAvailableStrategies", () => {
it("should return all strategy names", () => {
const strategies = getAvailableStrategies();
expect(strategies).toEqual([
"none",
"systemOnly",
"systemAndTools",
"optimized",
]);
});
});
describe("getStrategyDescription", () => {
it("should return correct descriptions for all strategies", () => {
expect(getStrategyDescription("none")).toBe(
"No caching - baseline for comparison",
);
expect(getStrategyDescription("systemOnly")).toBe(
"Cache only system messages (current implementation)",
);
expect(getStrategyDescription("systemAndTools")).toBe(
"Cache system messages and tool definitions (high impact)",
);
expect(getStrategyDescription("optimized")).toBe(
"Intelligent caching - system, tools, and large content (best performance)",
);
});
});
describe("CACHING_STRATEGIES", () => {
it("should contain all expected strategies", () => {
expect(Object.keys(CACHING_STRATEGIES)).toEqual([
"none",
"systemOnly",
"systemAndTools",
"optimized",
]);
});
it("should have all strategies as functions", () => {
Object.values(CACHING_STRATEGIES).forEach((strategy) => {
expect(typeof strategy).toBe("function");
});
});
});
describe("CachingStrategy type", () => {
it("should accept valid caching strategy functions", () => {
const customStrategy: CachingStrategy = (body) => ({
...body,
custom: true,
});
const input = { test: "value" };
const result = customStrategy(input);
expect(result).toEqual({ test: "value", custom: true });
});
});
describe("CachingStrategyName type", () => {
it("should work with valid strategy names", () => {
const strategyNames: CachingStrategyName[] = [
"none",
"systemOnly",
"systemAndTools",
"optimized",
];
strategyNames.forEach((name) => {
expect(typeof CACHING_STRATEGIES[name]).toBe("function");
});
});
});
});

View file

@ -0,0 +1,147 @@
// Caching strategy type - transforms a clean Anthropic body by adding cache_control
export type CachingStrategy = (anthropicBody: any) => any;
// Utility function to estimate token count
const estimateTokenCount = (text: string): number => Math.ceil(text.length / 4);
// Strategy 1: No Caching (Baseline)
const noCachingStrategy: CachingStrategy = (body) => body;
// Strategy 2: System Messages Only (Current Implementation)
const systemOnlyStrategy: CachingStrategy = (body) => {
if (body.system && Array.isArray(body.system)) {
return {
...body,
system: body.system.map((item: any) => ({
...item,
cache_control: { type: "ephemeral" },
})),
};
}
return body;
};
// Strategy 3: System and Tools (High Impact)
const systemAndToolsStrategy: CachingStrategy = (body) => {
const result = { ...body };
// Cache system messages
if (result.system && Array.isArray(result.system)) {
result.system = result.system.map((item: any) => ({
...item,
cache_control: { type: "ephemeral" },
}));
}
// Cache tool definitions
if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) {
result.tools = result.tools.map((tool: any, index: number) => {
if (index === result.tools.length - 1) {
return {
...tool,
cache_control: { type: "ephemeral" },
};
}
return tool;
});
}
return result;
};
// Strategy 4: Optimized (Intelligent Caching)
const optimizedStrategy: CachingStrategy = (body) => {
const result = { ...body };
// Always cache system messages
if (result.system && Array.isArray(result.system)) {
result.system = result.system.map((item: any) => ({
...item,
cache_control: { type: "ephemeral" },
}));
}
// Cache tool definitions
if (result.tools && Array.isArray(result.tools) && result.tools.length > 0) {
result.tools = result.tools.map((tool: any, index: number) => {
if (index === result.tools.length - 1) {
return {
...tool,
cache_control: { type: "ephemeral" },
};
}
return tool;
});
}
// Cache large messages (>500 tokens)
if (result.messages && Array.isArray(result.messages)) {
result.messages = result.messages.map((message: any) => {
if (message.content && typeof message.content === "string") {
const tokens = estimateTokenCount(message.content);
if (tokens > 500) {
return {
...message,
content: [
{
type: "text",
text: message.content,
cache_control: { type: "ephemeral" },
},
],
};
}
} else if (message.content && Array.isArray(message.content)) {
const updatedContent = message.content.map((item: any) => {
if (item.type === "text" && item.text) {
const tokens = estimateTokenCount(item.text);
if (tokens > 500) {
return {
...item,
cache_control: { type: "ephemeral" },
};
}
}
return item;
});
return {
...message,
content: updatedContent,
};
}
return message;
});
}
return result;
};
// Available caching strategies
export const CACHING_STRATEGIES = {
none: noCachingStrategy,
systemOnly: systemOnlyStrategy,
systemAndTools: systemAndToolsStrategy,
optimized: optimizedStrategy,
} as const;
export type CachingStrategyName = keyof typeof CACHING_STRATEGIES;
// Helper function to get available strategies
export const getAvailableStrategies = () => {
return Object.keys(CACHING_STRATEGIES) as CachingStrategyName[];
};
// Helper function to get strategy description
export const getStrategyDescription = (
strategy: CachingStrategyName,
): string => {
const descriptions = {
none: "No caching - baseline for comparison",
systemOnly: "Cache only system messages (current implementation)",
systemAndTools: "Cache system messages and tool definitions (high impact)",
optimized:
"Intelligent caching - system, tools, and large content (best performance)",
};
return descriptions[strategy];
};

View file

@ -60,7 +60,7 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined {
return new LlamastackApi(config);
case "continue-proxy":
return new ContinueProxyApi(config);
case "x-ai":
case "xAI":
return openAICompatible("https://api.x.ai/v1/", config);
case "voyage":
return openAICompatible("https://api.voyageai.com/v1/", config);

View file

@ -0,0 +1,321 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { BaseLlmApi } from "../apis/base.js";
import { LLMConfig } from "../types.js";
import { constructLlmApi } from "../index.js";
interface AdapterTestCase {
config: LLMConfig;
methodToTest: keyof BaseLlmApi;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeAdapterMethod(
api: BaseLlmApi,
methodToTest: keyof BaseLlmApi,
params: any[],
) {
if (typeof (api as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the adapter instance.`,
);
}
const result = await (api as any)[methodToTest](...params);
// If it's a generator/async iterator, consume it to trigger the HTTP request
if (result?.next) {
for await (const _ of result) {
// Just consume the generator to trigger the request
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
export async function runAdapterTest(testCase: AdapterTestCase) {
const {
config,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
// Mock fetch globally before constructing the API
vi.stubGlobal("fetch", mockFetch);
// For non-OpenAI adapters, mock the fetch package
const fetchPackage = await import("@continuedev/fetch");
if (fetchPackage.fetchwithRequestOptions) {
vi.mocked(fetchPackage.fetchwithRequestOptions).mockImplementation(
mockFetch as any,
);
}
const api = constructLlmApi(config);
if (!api) {
throw new Error(`Failed to construct API for provider: ${config.provider}`);
}
// For OpenAI adapters, we need to replace the fetch on the OpenAI client
if ((api as any).openai) {
(api as any).openai.fetch = mockFetch;
}
await executeAdapterMethod(api, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
export interface AdapterTestConfig {
providerName: string;
config: LLMConfig;
expectedApiBase: string;
customHeaders?: Record<string, string>;
customBodyOptions?: any;
}
export const createAdapterTests = (testConfig: AdapterTestConfig) => {
describe(testConfig.providerName, () => {
afterEach(() => {
vi.clearAllMocks();
vi.unstubAllGlobals();
});
test("should construct API correctly", () => {
const api = constructLlmApi(testConfig.config);
expect(api).toBeDefined();
});
test("chatCompletionNonStream should send a valid request", async () => {
await runAdapterTest({
config: testConfig.config,
methodToTest: "chatCompletionNonStream",
params: [
{
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
},
new AbortController().signal,
],
expectedRequest: {
url: `${testConfig.expectedApiBase}chat/completions`,
method: "POST",
headers: {
...testConfig.customHeaders,
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
...testConfig.customBodyOptions,
},
},
mockResponse: {
id: "test-id",
object: "chat.completion",
created: 1234567890,
model: "gpt-4",
choices: [
{
index: 0,
message: {
role: "assistant",
content: "Hello! How can I help you today?",
},
finish_reason: "stop",
},
],
usage: {
prompt_tokens: 10,
completion_tokens: 15,
total_tokens: 25,
},
},
});
});
test("chatCompletionStream should send a valid request", async () => {
await runAdapterTest({
config: testConfig.config,
methodToTest: "chatCompletionStream",
params: [
{
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
},
new AbortController().signal,
],
expectedRequest: {
url: `${testConfig.expectedApiBase}chat/completions`,
method: "POST",
headers: {
...testConfig.customHeaders,
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
...testConfig.customBodyOptions,
},
},
mockStream: [
{
id: "test-id",
object: "chat.completion.chunk",
created: 1234567890,
model: "gpt-4",
choices: [
{
index: 0,
delta: { content: "Hello" },
finish_reason: null,
},
],
},
{
id: "test-id",
object: "chat.completion.chunk",
created: 1234567890,
model: "gpt-4",
choices: [
{
index: 0,
delta: { content: " world" },
finish_reason: null,
},
],
},
],
});
});
test("embed should send a valid request", async () => {
await runAdapterTest({
config: testConfig.config,
methodToTest: "embed",
params: [
{
model: "text-embedding-ada-002",
input: ["Hello", "World"],
},
],
expectedRequest: {
url: `${testConfig.expectedApiBase}embeddings`,
method: "POST",
headers: {
...testConfig.customHeaders,
},
body: {
model: "text-embedding-ada-002",
input: ["Hello", "World"],
encoding_format: "base64",
...testConfig.customBodyOptions,
},
},
mockResponse: {
object: "list",
data: [
{
object: "embedding",
embedding: [0.1, 0.2, 0.3],
index: 0,
},
{
object: "embedding",
embedding: [0.4, 0.5, 0.6],
index: 1,
},
],
model: "text-embedding-ada-002",
usage: {
prompt_tokens: 6,
total_tokens: 6,
},
},
});
});
});
};

View file

@ -0,0 +1,201 @@
import { describe, test, vi, expect, afterEach } from "vitest";
import { runAdapterTest } from "./adapter-test-utils.js";
// Mock the fetch package
vi.mock("@continuedev/fetch", async () => {
const actual = await vi.importActual("@continuedev/fetch");
return {
...actual,
fetchwithRequestOptions: vi.fn(),
};
});
describe("Anthropic Adapter Tests", () => {
afterEach(() => {
vi.clearAllMocks();
vi.unstubAllGlobals();
});
test("should construct API correctly", async () => {
const { constructLlmApi } = await import("../index.js");
const api = constructLlmApi({
provider: "anthropic",
apiKey: "test-api-key",
});
expect(api).toBeDefined();
});
test("chatCompletionNonStream should send a valid request", async () => {
await runAdapterTest({
config: {
provider: "anthropic",
apiKey: "test-api-key",
apiBase: "https://api.anthropic.com/v1/",
},
methodToTest: "chatCompletionNonStream",
params: [
{
model: "claude-3-5-sonnet-20241022",
messages: [{ role: "user", content: "hello" }],
},
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
messages: [{ role: "user", content: "hello" }],
system: undefined,
model: "claude-3-5-sonnet-20241022",
max_tokens: 4096,
stream: undefined,
},
},
mockResponse: {
id: "msg_test",
type: "message",
role: "assistant",
content: [
{
type: "text",
text: "Hello! How can I help you today?",
},
],
model: "claude-3-5-sonnet-20241022",
stop_reason: "end_turn",
stop_sequence: null,
usage: {
input_tokens: 10,
output_tokens: 15,
},
},
});
});
test("chatCompletionStream should send a valid request", async () => {
await runAdapterTest({
config: {
provider: "anthropic",
apiKey: "test-api-key",
apiBase: "https://api.anthropic.com/v1/",
},
methodToTest: "chatCompletionStream",
params: [
{
model: "claude-3-5-sonnet-20241022",
messages: [{ role: "user", content: "hello" }],
stream: true,
},
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
messages: [{ role: "user", content: "hello" }],
system: undefined,
model: "claude-3-5-sonnet-20241022",
max_tokens: 4096,
stream: true,
},
},
mockStream: [
{
type: "content_block_delta",
delta: {
type: "text_delta",
text: "Hello",
},
},
{
type: "content_block_delta",
delta: {
type: "text_delta",
text: " world",
},
},
],
});
});
test("chatCompletionStream with system message should convert correctly", async () => {
await runAdapterTest({
config: {
provider: "anthropic",
apiKey: "test-api-key",
apiBase: "https://api.anthropic.com/v1/",
},
methodToTest: "chatCompletionStream",
params: [
{
model: "claude-3-5-sonnet-20241022",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "hello" },
],
stream: true,
},
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
messages: [{ role: "user", content: "hello" }],
system: [
{
type: "text",
text: "You are a helpful assistant.",
cache_control: { type: "ephemeral" },
},
],
model: "claude-3-5-sonnet-20241022",
max_tokens: 4096,
stream: true,
},
},
mockStream: [
{
type: "content_block_delta",
delta: {
type: "text_delta",
text: "Hello",
},
},
],
});
});
test("embed should throw not implemented error", async () => {
const { constructLlmApi } = await import("../index.js");
const api = constructLlmApi({
provider: "anthropic",
apiKey: "test-api-key",
});
await expect(
api!.embed({
model: "text-embedding-ada-002",
input: ["Hello", "World"],
}),
).rejects.toThrow("Method not implemented.");
});
});

View file

@ -4,12 +4,13 @@ import { DEEPSEEK_API_BASE } from "../apis/DeepSeek.js";
import { INCEPTION_API_BASE } from "../apis/Inception.js";
import { OpenAIApi } from "../apis/OpenAI.js";
import { constructLlmApi } from "../index.js";
import { getLlmApi, testChat, testEmbed } from "./util.js";
import { getLlmApi, testChat, testEmbed, testFim, testRerank } from "./util.js";
dotenv.config();
export interface TestConfigOptions {
skipTools: boolean;
expectUsage?: boolean;
}
function testConfig(_config: ModelConfig & { options?: TestConfigOptions }) {
@ -34,8 +35,12 @@ function testConfig(_config: ModelConfig & { options?: TestConfigOptions }) {
testEmbed(api, model);
}
if (config.roles?.includes("embed")) {
testEmbed(api, model);
if (config.roles?.includes("rerank")) {
testRerank(api, model);
}
if (config.roles?.includes("autocomplete")) {
testFim(api, model);
}
}
@ -51,6 +56,10 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
model: "claude-3-5-haiku-latest",
apiKey: process.env.ANTHROPIC_API_KEY!,
roles: ["chat"],
options: {
skipTools: false,
expectUsage: true,
},
},
{
provider: "gemini",
@ -58,19 +67,19 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
apiKey: process.env.GEMINI_API_KEY!,
roles: ["chat"],
},
{
provider: "mistral",
model: "codestral-latest",
apiKey: process.env.MISTRAL_API_KEY!,
apiBase: "https://api.mistral.ai/v1",
roles: ["autocomplete"],
},
{
provider: "deepseek",
model: "deepseek-coder",
apiKey: process.env.DEEPSEEK_API_KEY!,
roles: ["autocomplete"],
},
// {
// provider: "mistral",
// model: "codestral-latest",
// apiKey: process.env.MISTRAL_API_KEY!,
// apiBase: "https://api.mistral.ai/v1",
// roles: ["autocomplete"],
// },
// {
// provider: "deepseek",
// model: "deepseek-coder",
// apiKey: process.env.DEEPSEEK_API_KEY!,
// roles: ["autocomplete"],
// },
{
provider: "openai",
model: "text-embedding-3-small",
@ -112,28 +121,26 @@ const TESTS: Omit<ModelConfig & { options?: TestConfigOptions }, "name">[] = [
model: "gpt-4.1",
apiBase: "https://continue-openai.openai.azure.com",
apiKey: process.env.AZURE_OPENAI_GPT41_API_KEY,
roles: ["chat"],
env: {
deployment: "gpt-4.1",
apiVersion: "2024-02-15-preview",
apiType: "azure-openai",
},
roles: ["chat"],
},
{
provider: "azure",
model: "mistral-small-2503",
apiBase: "https://nate-0276-resource.services.ai.azure.com/models",
apiKey: process.env.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY,
roles: ["chat"],
options: { skipTools: true },
},
];
TESTS.forEach((config) => {
describe(`${config.provider}/${config.model}`, () => {
testConfig({ name: config.model, ...config });
if (process.env.IGNORE_API_KEY_TESTS === "true") {
test("Skipping API key tests", () => {
console.log("Skipping API key tests due to IGNORE_API_KEY_TESTS being set");
});
});
} else {
TESTS.forEach((config) => {
describe(`${config.provider}/${config.model}`, () => {
testConfig({ name: config.model, ...config });
});
});
}
describe("Configuration", () => {
it("should configure DeepSeek OpenAI client with correct apiBase and apiKey", () => {

View file

@ -0,0 +1,28 @@
import { describe, vi } from "vitest";
import { createAdapterTests } from "./adapter-test-utils.js";
// Mock the fetch package (not needed for OpenAI but required by the shared test utils)
vi.mock("@continuedev/fetch", async () => {
const actual = await vi.importActual("@continuedev/fetch");
return {
...actual,
fetchwithRequestOptions: vi.fn(),
};
});
describe("OpenAI Adapter Tests", () => {
createAdapterTests({
providerName: "openai",
config: {
provider: "openai",
apiKey: "test-api-key",
apiBase: "https://api.openai.com/v1/",
},
expectedApiBase: "https://api.openai.com/v1/",
customHeaders: {
authorization: "Bearer test-api-key",
"content-type": "application/json",
accept: "application/json",
},
});
});

View file

@ -1,3 +1,4 @@
import { CompletionUsage } from "openai/resources/completions.mjs";
import { BaseLlmApi, constructLlmApi } from "../index.js";
import { LLMConfig } from "../types.js";
import { TestConfigOptions } from "./main.test.js";
@ -88,12 +89,27 @@ export function testChat(
new AbortController().signal,
);
let completion = "";
let usage: CompletionUsage | undefined = undefined;
for await (const result of stream) {
completion += result.choices[0].delta.content ?? "";
completion += result.choices[0]?.delta.content ?? "";
expect(result.choices.length).toBeGreaterThan(0);
if (result.usage) {
usage = result.usage;
} else {
// At the end we expect a final message without choices that shares usage
expect(result.choices.length).toBeGreaterThan(0);
}
}
expect(completion.length).toBeGreaterThan(0);
if (options?.expectUsage === true) {
expect(usage).toBeDefined();
expect(usage!.completion_tokens).toBeGreaterThan(0);
expect(usage!.prompt_tokens).toBeGreaterThan(0);
expect(usage!.total_tokens).toEqual(
usage!.prompt_tokens + usage!.completion_tokens,
);
}
});
test("should successfully stream multi-part chat with empty text", async () => {
@ -122,6 +138,10 @@ export function testChat(
);
let completion = "";
for await (const result of stream) {
// Skip usage chunks that have empty choices array
if (result.choices.length === 0) {
continue;
}
completion += result.choices[0].delta.content ?? "";
expect(result.choices.length).toBeGreaterThan(0);
@ -246,6 +266,10 @@ export function testChat(
},
new AbortController().signal,
)) {
// Skip usage chunks that have empty choices array
if (chunk.choices.length === 0) {
continue;
}
const toolCall = chunk.choices[0].delta.tool_calls?.[0];
if (!toolCall) {
continue;
@ -317,6 +341,10 @@ export function testChat(
},
new AbortController().signal,
)) {
// Skip usage chunks that have empty choices array
if (chunk.choices.length === 0) {
continue;
}
response += chunk.choices[0].delta.content ?? "";
}

View file

@ -53,7 +53,7 @@ export const OpenAIConfigSchema = BasePlusConfig.extend({
z.literal("sambanova"),
z.literal("text-gen-webui"),
z.literal("vllm"),
z.literal("x-ai"),
z.literal("xAI"),
z.literal("scaleway"),
z.literal("ncompass"),
z.literal("relace"),

View file

@ -38,6 +38,21 @@ export function chatChunk(options: {
};
}
export function usageChatChunk(options: {
model: string;
id?: string | null;
usage?: CompletionUsage;
}): ChatCompletionChunk {
return {
choices: [],
usage: options.usage,
created: Date.now(),
id: options.id ?? "",
model: options.model,
object: "chat.completion.chunk",
};
}
export function chatChunkFromDelta(options: {
delta: ChatCompletionChunk.Choice["delta"];
model: string;

View file

@ -0,0 +1,15 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "node",
globals: true,
testTimeout: 10000,
include: ["src/**/*.test.{ts,tsx}", "src/**/*.vitest.{ts,tsx}"],
},
resolve: {
alias: {
"(.+)\\.js": "$1",
},
},
});

View file

@ -21,13 +21,7 @@ export default function createReleaseConfig(packageName) {
"@semantic-release/release-notes-generator",
"@semantic-release/changelog",
"@semantic-release/npm",
[
"@semantic-release/git",
{
assets: ["CHANGELOG.md", "package.json"],
message: `chore(release): @continuedev/${packageName}@\${nextRelease.version} [skip ci]`,
},
],
// Removed @semantic-release/git plugin to avoid pushing to main
"@semantic-release/github",
],
};