fix: compaction and more refactoring
This commit is contained in:
parent
09c4e183e5
commit
f68015f6de
17 changed files with 373 additions and 250 deletions
|
|
@ -1,7 +1,6 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import chalk from "chalk";
|
||||
import type { ChatHistoryItem, Session } from "core/index.js";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import * as readlineSync from "readline-sync";
|
||||
|
||||
import { getDisplayableAsciiArt } from "../asciiArt.js";
|
||||
|
|
@ -14,10 +13,6 @@ import { processCommandFlags } from "../flags/flagProcessor.js";
|
|||
import { safeStdout } from "../init.js";
|
||||
import { configureLogger } from "../logger.js";
|
||||
import * as logging from "../logging.js";
|
||||
import {
|
||||
convertFromUnifiedHistory,
|
||||
convertToUnifiedHistory,
|
||||
} from "../messageConversion.js";
|
||||
import { sentryService } from "../sentry.js";
|
||||
import { initializeServices } from "../services/index.js";
|
||||
import { serviceContainer } from "../services/ServiceContainer.js";
|
||||
|
|
@ -166,7 +161,7 @@ async function handleManualCompaction(
|
|||
|
||||
// Helper function to handle auto-compaction for headless mode
|
||||
async function handleAutoCompaction(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
chatHistory: ChatHistoryItem[],
|
||||
model: ModelConfig,
|
||||
llmApi: any,
|
||||
isHeadless: boolean,
|
||||
|
|
@ -273,10 +268,9 @@ async function processMessage(
|
|||
telemetryService.logUserPrompt(userInput.length, userInput);
|
||||
|
||||
// Check if auto-compacting is needed BEFORE adding user message
|
||||
const chatHistoryForTokenCheck = convertFromUnifiedHistory(chatHistory);
|
||||
if (shouldAutoCompact(chatHistoryForTokenCheck, model)) {
|
||||
if (shouldAutoCompact(chatHistory, model)) {
|
||||
const newIndex = await handleAutoCompaction(
|
||||
chatHistoryForTokenCheck,
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
isHeadless,
|
||||
|
|
@ -286,7 +280,7 @@ async function processMessage(
|
|||
compactionIndex = newIndex;
|
||||
// Replace chatHistory with compacted version
|
||||
chatHistory.length = 0;
|
||||
chatHistory.push(...convertToUnifiedHistory(chatHistoryForTokenCheck));
|
||||
chatHistory.push(...chatHistory);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import { describe, expect, it, vi } from "vitest";
|
|||
|
||||
import {
|
||||
compactChatHistory,
|
||||
COMPACTION_MARKER,
|
||||
findCompactionIndex,
|
||||
getHistoryForLLM,
|
||||
} from "./compaction.js";
|
||||
|
|
@ -34,11 +33,14 @@ describe("compaction", () => {
|
|||
{ role: "assistant", content: "Hi there" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
content: `\nThis is a summary`,
|
||||
},
|
||||
{ role: "user", content: "Another message" },
|
||||
]);
|
||||
|
||||
// Add conversationSummary to mark this as a compaction message
|
||||
history[3].conversationSummary = "This is a summary";
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBe(3);
|
||||
});
|
||||
|
|
@ -57,11 +59,15 @@ describe("compaction", () => {
|
|||
it("should return first compaction marker when multiple exist", () => {
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: "System message" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nFirst summary` },
|
||||
{ role: "assistant", content: `\nFirst summary` },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSecond summary` },
|
||||
{ role: "assistant", content: `\nSecond summary` },
|
||||
]);
|
||||
|
||||
// Add conversationSummary to mark these as compaction messages
|
||||
history[1].conversationSummary = "First summary";
|
||||
history[3].conversationSummary = "Second summary";
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBe(1);
|
||||
});
|
||||
|
|
@ -77,11 +83,12 @@ describe("compaction", () => {
|
|||
{ role: "system", content: "System message" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: `Some text ${COMPACTION_MARKER} in the middle`,
|
||||
content: `Some text in the middle`,
|
||||
},
|
||||
{ role: "user", content: "Hello" },
|
||||
]);
|
||||
|
||||
// Don't add conversationSummary - this should not be found
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBeNull();
|
||||
});
|
||||
|
|
@ -104,9 +111,10 @@ describe("compaction", () => {
|
|||
{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\\nValid compaction`,
|
||||
content: `\\nValid compaction`,
|
||||
},
|
||||
contextItems: [],
|
||||
conversationSummary: "Valid compaction",
|
||||
},
|
||||
];
|
||||
|
||||
|
|
@ -114,13 +122,16 @@ describe("compaction", () => {
|
|||
expect(index).toBe(3);
|
||||
});
|
||||
|
||||
it("should only match assistant role messages", () => {
|
||||
it("should only match messages with conversationSummary", () => {
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "system", content: `${COMPACTION_MARKER}\nSystem compaction?` },
|
||||
{ role: "user", content: `${COMPACTION_MARKER}\nUser compaction?` },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nReal compaction` },
|
||||
{ role: "system", content: `\nSystem compaction?` },
|
||||
{ role: "user", content: `\nUser compaction?` },
|
||||
{ role: "assistant", content: `\nReal compaction` },
|
||||
]);
|
||||
|
||||
// Only add conversationSummary to the assistant message
|
||||
history[2].conversationSummary = "Real compaction";
|
||||
|
||||
const index = findCompactionIndex(history);
|
||||
expect(index).toBe(2);
|
||||
});
|
||||
|
|
@ -145,7 +156,7 @@ describe("compaction", () => {
|
|||
{ role: "assistant", content: "Hi there" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
content: `\nThis is a summary`,
|
||||
},
|
||||
{ role: "user", content: "Another message" },
|
||||
]);
|
||||
|
|
@ -159,7 +170,7 @@ describe("compaction", () => {
|
|||
{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
content: `\nThis is a summary`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
|
|
@ -174,7 +185,7 @@ describe("compaction", () => {
|
|||
const history = convertToUnifiedHistory([
|
||||
{
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nThis is a summary`,
|
||||
content: `\nThis is a summary`,
|
||||
},
|
||||
{ role: "user", content: "Another message" },
|
||||
]);
|
||||
|
|
@ -228,7 +239,7 @@ describe("compaction", () => {
|
|||
it("should handle history without system message but with compaction", () => {
|
||||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "First message" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "assistant", content: `\nSummary` },
|
||||
{ role: "user", content: "New message" },
|
||||
]);
|
||||
|
||||
|
|
@ -237,7 +248,7 @@ describe("compaction", () => {
|
|||
{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nSummary`,
|
||||
content: `\nSummary`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
|
|
@ -252,7 +263,7 @@ describe("compaction", () => {
|
|||
const history = convertToUnifiedHistory([
|
||||
{ role: "user", content: "First user message" },
|
||||
{ role: "system", content: "System message in wrong position" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "assistant", content: `\nSummary` },
|
||||
{ role: "user", content: "New message" },
|
||||
]);
|
||||
|
||||
|
|
@ -262,7 +273,7 @@ describe("compaction", () => {
|
|||
{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nSummary`,
|
||||
content: `\nSummary`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
|
|
@ -278,7 +289,7 @@ describe("compaction", () => {
|
|||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "Old 1" },
|
||||
{ role: "assistant", content: "Old 2" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "assistant", content: `\nSummary` },
|
||||
{ role: "user", content: "New 1" },
|
||||
{ role: "assistant", content: "New 2" },
|
||||
{ role: "user", content: "New 3" },
|
||||
|
|
@ -293,7 +304,7 @@ describe("compaction", () => {
|
|||
{
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\nSummary`,
|
||||
content: `\nSummary`,
|
||||
},
|
||||
contextItems: [],
|
||||
},
|
||||
|
|
@ -345,7 +356,7 @@ describe("compaction", () => {
|
|||
expect(result.compactedHistory[1]).toEqual({
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\n${mockContent}`,
|
||||
content: mockContent,
|
||||
},
|
||||
contextItems: [],
|
||||
conversationSummary: mockContent,
|
||||
|
|
@ -425,7 +436,7 @@ describe("compaction", () => {
|
|||
content: "You are a helpful assistant",
|
||||
});
|
||||
expect(result.compactedHistory[1].message.content).toContain(
|
||||
COMPACTION_MARKER,
|
||||
"Summary of system setup",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -447,9 +458,7 @@ describe("compaction", () => {
|
|||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
expect(result.compactionContent).toBe("");
|
||||
expect(result.compactedHistory[0].message.content).toBe(
|
||||
`${COMPACTION_MARKER}\n`,
|
||||
);
|
||||
expect(result.compactedHistory[0].message.content).toBe("");
|
||||
});
|
||||
|
||||
it("should correctly construct prompt for compaction", async () => {
|
||||
|
|
@ -622,14 +631,14 @@ describe("compaction", () => {
|
|||
history: convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "user", content: "User 1" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "assistant", content: `\nSummary` },
|
||||
]),
|
||||
compactionIndex: 2,
|
||||
},
|
||||
{
|
||||
history: convertToUnifiedHistory([
|
||||
{ role: "system", content: "System" },
|
||||
{ role: "assistant", content: `${COMPACTION_MARKER}\nSummary` },
|
||||
{ role: "assistant", content: `\nSummary` },
|
||||
]),
|
||||
compactionIndex: 1,
|
||||
},
|
||||
|
|
@ -686,7 +695,7 @@ describe("compaction", () => {
|
|||
});
|
||||
|
||||
describe("invariant tests", () => {
|
||||
it("compactionIndex should always point to a message with COMPACTION_MARKER", async () => {
|
||||
it("compactionIndex should always point to a message with conversationSummary", async () => {
|
||||
const mockStreamResponse = vi.mocked(streamChatResponse);
|
||||
|
||||
mockStreamResponse.mockImplementation(
|
||||
|
|
@ -712,14 +721,11 @@ describe("compaction", () => {
|
|||
for (const history of histories) {
|
||||
const result = await compactChatHistory(history, mockModel, mockLlmApi);
|
||||
|
||||
// The message at compactionIndex should contain the marker
|
||||
// The message at compactionIndex should have a conversationSummary
|
||||
const compactionMessage =
|
||||
result.compactedHistory[result.compactionIndex];
|
||||
expect(compactionMessage.message.role).toBe("assistant");
|
||||
expect(
|
||||
typeof compactionMessage.message.content === "string" &&
|
||||
compactionMessage.message.content.startsWith(COMPACTION_MARKER),
|
||||
).toBe(true);
|
||||
expect(compactionMessage.conversationSummary).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { ModelConfig } from "@continuedev/config-yaml";
|
|||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
|
||||
import { convertFromUnifiedHistory } from "./messageConversion.js";
|
||||
import { streamChatResponse } from "./streamChatResponse.js";
|
||||
import { StreamCallbacks } from "./streamChatResponse.types.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
|
|
@ -11,8 +10,6 @@ import {
|
|||
getModelContextLimit,
|
||||
} from "./util/tokenizer.js";
|
||||
|
||||
export const COMPACTION_MARKER = "[COMPACTED HISTORY]";
|
||||
|
||||
export interface CompactionResult {
|
||||
compactedHistory: ChatHistoryItem[];
|
||||
compactionIndex: number;
|
||||
|
|
@ -44,7 +41,7 @@ export async function compactChatHistory(
|
|||
message: {
|
||||
role: "user" as const,
|
||||
content:
|
||||
"Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain.",
|
||||
"Please provide a concise summary of our conversation so far, capturing the key context, decisions made, and current state. Format this as a single comprehensive message that preserves all important information needed to continue our work. You do not need to recap the system message, as this will remain. Make sure it is clear what the current stream of work was at the very end prior to compaction so that you can continue exactly where you left off without missing any information.",
|
||||
},
|
||||
contextItems: [],
|
||||
};
|
||||
|
|
@ -52,22 +49,20 @@ export async function compactChatHistory(
|
|||
// Check if the history with compaction prompt is too long, prune if necessary
|
||||
let historyToUse = chatHistory;
|
||||
let historyForCompaction = [...historyToUse, compactionPrompt];
|
||||
let historyForCompactionLegacy =
|
||||
convertFromUnifiedHistory(historyForCompaction);
|
||||
|
||||
const contextLimit = getModelContextLimit(model);
|
||||
const maxTokens = model.defaultCompletionOptions?.maxTokens || 0;
|
||||
const maxTokens = model.defaultCompletionOptions?.maxTokens;
|
||||
const reservedForOutput =
|
||||
maxTokens > 0 ? maxTokens : Math.ceil(contextLimit * 0.35);
|
||||
maxTokens === undefined ? Math.ceil(contextLimit * 0.35) : maxTokens;
|
||||
const availableForInput = contextLimit - reservedForOutput;
|
||||
|
||||
// Check if we need to prune to fit within context
|
||||
while (
|
||||
countChatHistoryTokens(historyForCompactionLegacy) > availableForInput &&
|
||||
countChatHistoryTokens(historyForCompaction) > availableForInput &&
|
||||
historyToUse.length > 0
|
||||
) {
|
||||
logger.debug("Compaction history too long, pruning last message", {
|
||||
tokenCount: countChatHistoryTokens(historyForCompactionLegacy),
|
||||
tokenCount: countChatHistoryTokens(historyForCompaction),
|
||||
availableForInput,
|
||||
historyLength: historyToUse.length,
|
||||
});
|
||||
|
|
@ -83,8 +78,6 @@ export async function compactChatHistory(
|
|||
|
||||
historyToUse = prunedHistory;
|
||||
historyForCompaction = [...historyToUse, compactionPrompt];
|
||||
historyForCompactionLegacy =
|
||||
convertFromUnifiedHistory(historyForCompaction);
|
||||
}
|
||||
|
||||
// Stream the compaction response
|
||||
|
|
@ -114,35 +107,23 @@ export async function compactChatHistory(
|
|||
const systemMessage = chatHistory.find(
|
||||
(item) => item.message.role === "system",
|
||||
);
|
||||
const compactedMessage: ChatHistoryItem = {
|
||||
const compactionMessage: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: `${COMPACTION_MARKER}\n${compactionContent}`,
|
||||
content: compactionContent,
|
||||
},
|
||||
contextItems: [],
|
||||
conversationSummary: compactionContent,
|
||||
};
|
||||
|
||||
// Set new chat history with only system message and compaction
|
||||
const compactedHistory = systemMessage
|
||||
? [systemMessage, compactedMessage]
|
||||
: [compactedMessage];
|
||||
|
||||
// Mark the compaction in the unified format
|
||||
const compactionIndex = compactedHistory.length - 1;
|
||||
if (compactedHistory[compactionIndex]) {
|
||||
compactedHistory[compactionIndex].conversationSummary = compactionContent;
|
||||
}
|
||||
|
||||
logger.debug("Chat history compacted", {
|
||||
originalLength: chatHistory.length,
|
||||
compactedLength: compactedHistory.length,
|
||||
compactionIndex,
|
||||
});
|
||||
const compactedHistory: ChatHistoryItem[] = systemMessage
|
||||
? [systemMessage, compactionMessage]
|
||||
: [compactionMessage];
|
||||
|
||||
return {
|
||||
compactedHistory,
|
||||
compactionIndex,
|
||||
compactionContent,
|
||||
compactionIndex: systemMessage ? 1 : 0,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error("Compaction failed", error);
|
||||
|
|
@ -160,10 +141,7 @@ export function findCompactionIndex(
|
|||
chatHistory: ChatHistoryItem[],
|
||||
): number | null {
|
||||
const compactedIndex = chatHistory.findIndex(
|
||||
(item) =>
|
||||
item.message.role === "assistant" &&
|
||||
typeof item.message.content === "string" &&
|
||||
item.message.content.startsWith(COMPACTION_MARKER),
|
||||
(item) => item.conversationSummary !== undefined,
|
||||
);
|
||||
return compactedIndex === -1 ? null : compactedIndex;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,11 +20,20 @@ vi.mock("os", () => ({
|
|||
default: {
|
||||
homedir: vi.fn(() => "/home/test"),
|
||||
},
|
||||
homedir: vi.fn(() => "/home/test"),
|
||||
}));
|
||||
vi.mock("fs");
|
||||
vi.mock("uuid", () => ({
|
||||
v4: vi.fn(() => "test-uuid-123"),
|
||||
}));
|
||||
vi.mock("./util/logger.js", () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock("../../core/util/history.js", () => ({
|
||||
default: {
|
||||
save: vi.fn(),
|
||||
|
|
@ -200,9 +209,9 @@ describe("SessionManager", () => {
|
|||
const savedData = JSON.parse(
|
||||
(mockFs.writeFileSync as any).mock.calls[0][1],
|
||||
);
|
||||
expect(savedData.history).toHaveLength(2);
|
||||
expect(savedData.history[0].message.role).toBe("system");
|
||||
expect(savedData.history[1].message.role).toBe("user");
|
||||
// After modification, system messages are filtered out
|
||||
expect(savedData.history).toHaveLength(1);
|
||||
expect(savedData.history[0].message.role).toBe("user");
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { convertToUnifiedHistory } from "./messageConversion.js";
|
||||
|
|
@ -58,11 +58,11 @@ describe("handleAutoCompaction", () => {
|
|||
} as any;
|
||||
|
||||
const mockLlmApi = {} as any;
|
||||
const mockChatHistory: ChatCompletionMessageParam[] = [
|
||||
const mockChatHistory: ChatHistoryItem[] = convertToUnifiedHistory([
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there!" },
|
||||
];
|
||||
]);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
|
@ -82,6 +82,7 @@ describe("handleAutoCompaction", () => {
|
|||
expect(result).toEqual({
|
||||
chatHistory: mockChatHistory,
|
||||
compactionIndex: null,
|
||||
wasCompacted: false,
|
||||
});
|
||||
|
||||
expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel);
|
||||
|
|
@ -131,7 +132,7 @@ describe("handleAutoCompaction", () => {
|
|||
expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel);
|
||||
expect(getAutoCompactMessage).toHaveBeenCalledWith(mockModel);
|
||||
expect(compactChatHistory).toHaveBeenCalledWith(
|
||||
convertToUnifiedHistory(mockChatHistory),
|
||||
mockChatHistory,
|
||||
mockModel,
|
||||
mockLlmApi,
|
||||
expect.any(Object),
|
||||
|
|
@ -148,14 +149,9 @@ describe("handleAutoCompaction", () => {
|
|||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
chatHistory: [
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{
|
||||
role: "assistant",
|
||||
content: "[COMPACTED HISTORY]\nConversation summary...",
|
||||
},
|
||||
],
|
||||
chatHistory: mockCompactionResult.compactedHistory,
|
||||
compactionIndex: mockCompactionResult.compactionIndex,
|
||||
wasCompacted: true,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -194,9 +190,11 @@ describe("handleAutoCompaction", () => {
|
|||
);
|
||||
|
||||
// Should return original history on error
|
||||
expect(result.wasCompacted).toBe(false);
|
||||
expect(result).toEqual({
|
||||
chatHistory: mockChatHistory,
|
||||
compactionIndex: null,
|
||||
wasCompacted: false,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -242,6 +240,7 @@ describe("handleAutoCompaction", () => {
|
|||
expect(result).toEqual({
|
||||
chatHistory: mockChatHistory,
|
||||
compactionIndex: null,
|
||||
wasCompacted: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,14 +1,9 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import React from "react";
|
||||
|
||||
import { compactChatHistory } from "./compaction.js";
|
||||
import {
|
||||
convertFromUnifiedHistory,
|
||||
convertToUnifiedHistory,
|
||||
} from "./messageConversion.js";
|
||||
import { updateSessionHistory } from "./session.js";
|
||||
import { formatError } from "./util/formatError.js";
|
||||
import { logger } from "./util/logger.js";
|
||||
|
|
@ -21,9 +16,7 @@ interface AutoCompactionCallbacks {
|
|||
|
||||
// For TUI mode
|
||||
setMessages?: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
setChatHistory?: React.Dispatch<
|
||||
React.SetStateAction<ChatCompletionMessageParam[]>
|
||||
>;
|
||||
setChatHistory?: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
|
||||
setCompactionIndex?: React.Dispatch<React.SetStateAction<number | null>>;
|
||||
|
||||
// For headless mode - no callbacks needed, just return values
|
||||
|
|
@ -126,18 +119,19 @@ function handleCompactionError(
|
|||
* @returns Updated chat history and compaction index, or original if no compaction needed
|
||||
*/
|
||||
export async function handleAutoCompaction(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
chatHistory: ChatHistoryItem[],
|
||||
model: ModelConfig,
|
||||
llmApi: BaseLlmApi,
|
||||
options: AutoCompactionOptions = {},
|
||||
): Promise<{
|
||||
chatHistory: ChatCompletionMessageParam[];
|
||||
chatHistory: ChatHistoryItem[];
|
||||
compactionIndex: number | null;
|
||||
wasCompacted: boolean;
|
||||
}> {
|
||||
const { isHeadless = false, callbacks } = options;
|
||||
|
||||
if (!model || !shouldAutoCompact(chatHistory, model)) {
|
||||
return { chatHistory, compactionIndex: null };
|
||||
return { chatHistory, compactionIndex: null, wasCompacted: false };
|
||||
}
|
||||
|
||||
logger.info(
|
||||
|
|
@ -148,12 +142,9 @@ export async function handleAutoCompaction(
|
|||
notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks);
|
||||
|
||||
try {
|
||||
// Convert to unified format for compaction
|
||||
const unifiedHistory = convertToUnifiedHistory(chatHistory);
|
||||
|
||||
// Compact the history
|
||||
const result = await compactChatHistory(
|
||||
unifiedHistory,
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
isHeadless
|
||||
|
|
@ -170,20 +161,16 @@ export async function handleAutoCompaction(
|
|||
// Handle success notification
|
||||
handleCompactionSuccess(result, isHeadless, callbacks);
|
||||
|
||||
// Convert back to legacy format for return
|
||||
const compactedLegacyHistory = convertFromUnifiedHistory(
|
||||
result.compactedHistory,
|
||||
);
|
||||
|
||||
return {
|
||||
chatHistory: compactedLegacyHistory,
|
||||
chatHistory: result.compactedHistory,
|
||||
compactionIndex: result.compactionIndex,
|
||||
wasCompacted: true,
|
||||
};
|
||||
} catch (error: any) {
|
||||
// Handle error notification
|
||||
handleCompactionError(error, isHeadless, callbacks);
|
||||
|
||||
// Continue without compaction on error
|
||||
return { chatHistory, compactionIndex: null };
|
||||
return { chatHistory, compactionIndex: null, wasCompacted: false };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import type {
|
||||
ChatCompletionChunk,
|
||||
ChatCompletionMessageParam,
|
||||
} from "openai/resources/chat/completions.mjs";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import type { ChatCompletionChunk } from "openai/resources/chat/completions.mjs";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { toolPermissionManager } from "./permissions/permissionManager.js";
|
||||
|
|
@ -25,7 +23,7 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
let mockAbortController: AbortController;
|
||||
let mockModel: ModelConfig;
|
||||
let chunks: ChatCompletionChunk[];
|
||||
let chatHistory: ChatCompletionMessageParam[];
|
||||
let chatHistory: ChatHistoryItem[];
|
||||
|
||||
// Helper to create a content chunk
|
||||
function contentChunk(content: string): ChatCompletionChunk {
|
||||
|
|
@ -112,7 +110,12 @@ describe("processStreamingResponse - content preservation", () => {
|
|||
beforeEach(() => {
|
||||
// Reset chunks for each test
|
||||
chunks = [];
|
||||
chatHistory = [{ role: "user", content: "Test prompt" }];
|
||||
chatHistory = [
|
||||
{
|
||||
message: { role: "user", content: "Test prompt" },
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
|
||||
// Create a mock LLM API that returns our predefined chunks
|
||||
mockLlmApi = {
|
||||
|
|
|
|||
|
|
@ -1,14 +1,13 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { BaseLlmApi } from "@continuedev/openai-adapters";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import type { ChatHistoryItem, ToolStatus } from "core/index.js";
|
||||
import * as dotenv from "dotenv";
|
||||
import type {
|
||||
ChatCompletionMessageParam,
|
||||
ChatCompletionMessageToolCall,
|
||||
ChatCompletionTool,
|
||||
} from "openai/resources.mjs";
|
||||
import type { ChatCompletionTool } from "openai/resources.mjs";
|
||||
|
||||
import { convertFromUnifiedHistory } from "./messageConversion.js";
|
||||
import {
|
||||
convertFromUnifiedHistory,
|
||||
createHistoryItem,
|
||||
} from "./messageConversion.js";
|
||||
import { filterExcludedTools } from "./permissions/index.js";
|
||||
import {
|
||||
getServiceSync,
|
||||
|
|
@ -72,41 +71,68 @@ function handleContentDisplay(
|
|||
|
||||
async function handleToolCalls(
|
||||
toolCalls: ToolCall[],
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
chatHistory: ChatHistoryItem[],
|
||||
content: string,
|
||||
callbacks: StreamCallbacks | undefined,
|
||||
isHeadless: boolean,
|
||||
): Promise<boolean> {
|
||||
if (toolCalls.length === 0) {
|
||||
if (content) {
|
||||
chatHistory.push({ role: "assistant", content });
|
||||
chatHistory.push(
|
||||
createHistoryItem({
|
||||
role: "assistant",
|
||||
content,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const toolCallsForHistory: ChatCompletionMessageToolCall[] = toolCalls.map(
|
||||
(tc) => ({
|
||||
// Create tool call states for the ChatHistoryItem
|
||||
const toolCallStates = toolCalls.map((tc) => ({
|
||||
toolCallId: tc.id,
|
||||
toolCall: {
|
||||
id: tc.id,
|
||||
type: "function",
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tc.name,
|
||||
arguments: JSON.stringify(tc.arguments),
|
||||
},
|
||||
}),
|
||||
);
|
||||
},
|
||||
status: "generated" as ToolStatus,
|
||||
parsedArgs: tc.arguments,
|
||||
}));
|
||||
|
||||
chatHistory.push({
|
||||
role: "assistant",
|
||||
content: content || null,
|
||||
tool_calls: toolCallsForHistory,
|
||||
});
|
||||
// Create assistant message with tool calls
|
||||
const assistantMessage = {
|
||||
role: "assistant" as const,
|
||||
content: content || "",
|
||||
toolCalls: toolCalls.map((tc) => ({
|
||||
id: tc.id,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: tc.name,
|
||||
arguments: JSON.stringify(tc.arguments),
|
||||
},
|
||||
})),
|
||||
};
|
||||
|
||||
chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates));
|
||||
|
||||
// First preprocess the tool calls
|
||||
const { preprocessedCalls, errorChatEntries } =
|
||||
await preprocessStreamedToolCalls(toolCalls, callbacks);
|
||||
|
||||
// Add any preprocessing errors to chat history
|
||||
chatHistory.push(...errorChatEntries);
|
||||
// Convert error entries from OpenAI format to ChatHistoryItem format
|
||||
errorChatEntries.forEach((errorEntry) => {
|
||||
chatHistory.push(
|
||||
createHistoryItem({
|
||||
role: "assistant",
|
||||
content: errorEntry.content || "",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// Execute the valid preprocessed tool calls
|
||||
const { chatHistoryEntries: toolResults, hasRejection } =
|
||||
|
|
@ -119,7 +145,35 @@ async function handleToolCalls(
|
|||
return true; // Signal early return needed
|
||||
}
|
||||
|
||||
chatHistory.push(...toolResults);
|
||||
// Convert tool results from OpenAI format to ChatHistoryItem format
|
||||
// and add them to the chat history
|
||||
toolResults.forEach((toolResult) => {
|
||||
// Find the corresponding tool call state to update
|
||||
const lastAssistantIndex = chatHistory.findLastIndex(
|
||||
(item) => item.message.role === "assistant" && item.toolCallStates,
|
||||
);
|
||||
|
||||
if (
|
||||
lastAssistantIndex >= 0 &&
|
||||
chatHistory[lastAssistantIndex].toolCallStates
|
||||
) {
|
||||
const toolState = chatHistory[lastAssistantIndex].toolCallStates.find(
|
||||
(ts) => ts.toolCallId === toolResult.tool_call_id,
|
||||
);
|
||||
|
||||
if (toolState) {
|
||||
toolState.status = hasRejection ? "canceled" : "done";
|
||||
toolState.output = [
|
||||
{
|
||||
content: typeof toolResult.content === "string" ? toolResult.content : "",
|
||||
name: `Tool Result`,
|
||||
description: "Tool execution result",
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -272,7 +326,7 @@ function processChunk(options: ProcessChunkOptions): {
|
|||
}
|
||||
|
||||
interface ProcessStreamingResponseOptions {
|
||||
chatHistory: ChatCompletionMessageParam[];
|
||||
chatHistory: ChatHistoryItem[];
|
||||
model: ModelConfig;
|
||||
llmApi: BaseLlmApi;
|
||||
abortController: AbortController;
|
||||
|
|
@ -299,6 +353,7 @@ export async function processStreamingResponse(
|
|||
isHeadless,
|
||||
tools,
|
||||
} = options;
|
||||
const openaiChatHistory = convertFromUnifiedHistory(chatHistory);
|
||||
const requestStartTime = Date.now();
|
||||
|
||||
const streamFactory = async (retryAbortSignal: AbortSignal) => {
|
||||
|
|
@ -311,7 +366,7 @@ export async function processStreamingResponse(
|
|||
llmApi,
|
||||
{
|
||||
model: model.model,
|
||||
messages: chatHistory,
|
||||
messages: openaiChatHistory,
|
||||
stream: true,
|
||||
tools,
|
||||
...getDefaultCompletionOptions(model.defaultCompletionOptions),
|
||||
|
|
@ -451,9 +506,6 @@ export async function streamChatResponse(
|
|||
abortController: AbortController,
|
||||
callbacks?: StreamCallbacks,
|
||||
) {
|
||||
// Convert to OpenAI format for processing
|
||||
const openaiHistory = convertFromUnifiedHistory(chatHistory);
|
||||
|
||||
logger.debug("streamChatResponse called", {
|
||||
model,
|
||||
historyLength: chatHistory.length,
|
||||
|
|
@ -482,7 +534,7 @@ export async function streamChatResponse(
|
|||
// Get response from LLM
|
||||
const { content, toolCalls, shouldContinue } =
|
||||
await processStreamingResponse({
|
||||
chatHistory: openaiHistory,
|
||||
chatHistory,
|
||||
model,
|
||||
llmApi,
|
||||
abortController,
|
||||
|
|
@ -507,7 +559,7 @@ export async function streamChatResponse(
|
|||
// Handle tool calls and check for early return
|
||||
const shouldReturn = await handleToolCalls(
|
||||
toolCalls,
|
||||
openaiHistory,
|
||||
chatHistory,
|
||||
content,
|
||||
callbacks,
|
||||
isHeadless,
|
||||
|
|
@ -519,8 +571,8 @@ export async function streamChatResponse(
|
|||
|
||||
// Check for auto-compaction after tool execution
|
||||
if (shouldContinue) {
|
||||
const { chatHistory: updatedChatHistory, compactionIndex } =
|
||||
await handleAutoCompaction(openaiHistory, model, llmApi, {
|
||||
const { wasCompacted, chatHistory: updatedChatHistory } =
|
||||
await handleAutoCompaction(chatHistory, model, llmApi, {
|
||||
isHeadless,
|
||||
callbacks: {
|
||||
onSystemMessage: callbacks?.onSystemMessage,
|
||||
|
|
@ -529,9 +581,8 @@ export async function streamChatResponse(
|
|||
});
|
||||
|
||||
// Only update chat history if compaction actually occurred
|
||||
if (compactionIndex !== null && updatedChatHistory !== openaiHistory) {
|
||||
openaiHistory.length = 0;
|
||||
openaiHistory.push(...updatedChatHistory);
|
||||
if (wasCompacted) {
|
||||
chatHistory = [...updatedChatHistory];
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -543,7 +594,7 @@ export async function streamChatResponse(
|
|||
|
||||
logger.debug("streamChatResponse complete", {
|
||||
totalResponseLength: fullResponse.length,
|
||||
totalMessages: openaiHistory.length,
|
||||
totalMessages: chatHistory.length,
|
||||
});
|
||||
|
||||
// For headless mode, we return only the final response
|
||||
|
|
|
|||
|
|
@ -38,20 +38,20 @@ export const readFileTool: Tool = {
|
|||
filepath = filepath.slice(2);
|
||||
}
|
||||
|
||||
if (!fs.existsSync(args.filepath)) {
|
||||
return `Error: File does not exist: ${args.filepath}`;
|
||||
if (!fs.existsSync(filepath)) {
|
||||
return `Error: File does not exist: ${filepath}`;
|
||||
}
|
||||
const content = fs.readFileSync(args.filepath, "utf-8");
|
||||
const content = fs.readFileSync(filepath, "utf-8");
|
||||
// Mark this file as read for the edit tool
|
||||
markFileAsRead(args.filepath);
|
||||
markFileAsRead(filepath);
|
||||
|
||||
const lines = content.split("\n");
|
||||
if (lines.length > 5000) {
|
||||
const truncatedContent = lines.slice(0, 5000).join("\n");
|
||||
return `Content of ${args.filepath} (truncated to first 5000 lines of ${lines.length} total):\n${truncatedContent}`;
|
||||
return `Content of ${filepath} (truncated to first 5000 lines of ${lines.length} total):\n${truncatedContent}`;
|
||||
}
|
||||
|
||||
return `Content of ${args.filepath}:\n${content}`;
|
||||
return `Content of ${filepath}:\n${content}`;
|
||||
} catch (error) {
|
||||
return `Error reading file: ${
|
||||
error instanceof Error ? error.message : String(error)
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import React, {
|
|||
} from "react";
|
||||
|
||||
import { useServices } from "../hooks/useService.js";
|
||||
import { convertFromUnifiedHistory } from "../messageConversion.js";
|
||||
import {
|
||||
ApiClientServiceState,
|
||||
AuthServiceState,
|
||||
|
|
@ -220,14 +219,10 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
}, [resetChatHistory]);
|
||||
|
||||
// Memoize the chat history conversion to avoid expensive recalculation on every render
|
||||
const convertedChatHistory = useMemo(
|
||||
() => convertFromUnifiedHistory(chatHistory),
|
||||
[chatHistory],
|
||||
);
|
||||
|
||||
// Calculate context percentage
|
||||
const contextData = useContextPercentage({
|
||||
chatHistory: convertedChatHistory,
|
||||
chatHistory,
|
||||
model: services.model?.model || undefined,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
|
|||
frame = lastFrame();
|
||||
|
||||
// c) Make sure the string "[plan]" is on the screen
|
||||
expect(frame!).toContain("[plan]");
|
||||
expect(frame!).toContain("plan]");
|
||||
|
||||
// d) Successfully send a message without error
|
||||
const testMessage = "Can you help me analyze this code?";
|
||||
|
|
@ -59,7 +59,7 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
|
|||
expect(frame!.length).toBeGreaterThan(0);
|
||||
|
||||
// Should still be in plan mode after sending message
|
||||
expect(frame!).toContain("[plan]");
|
||||
expect(frame!).toContain("plan]");
|
||||
|
||||
// Should still show the input prompt
|
||||
expect(frame!).toContain("Ask anything");
|
||||
|
|
@ -74,31 +74,31 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
|
|||
try {
|
||||
// Start in normal mode
|
||||
let frame = lastFrame();
|
||||
expect(frame!).not.toContain("[plan]");
|
||||
expect(frame!).not.toContain("[auto]");
|
||||
expect(frame!).not.toContain("plan]");
|
||||
expect(frame!).not.toContain("auto]");
|
||||
|
||||
// Switch to plan mode
|
||||
stdin.write("\x1b[Z");
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
frame = lastFrame();
|
||||
expect(frame!).toContain("[plan]");
|
||||
expect(frame!).toContain("plan]");
|
||||
|
||||
// Switch to auto mode
|
||||
stdin.write("\x1b[Z");
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
frame = lastFrame();
|
||||
expect(frame!).toContain("[auto]");
|
||||
expect(frame!).not.toContain("[plan]");
|
||||
expect(frame!).toContain("auto]");
|
||||
expect(frame!).not.toContain("plan]");
|
||||
|
||||
// Switch back to normal mode
|
||||
stdin.write("\x1b[Z");
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
frame = lastFrame();
|
||||
expect(frame!).not.toContain("[plan]");
|
||||
expect(frame!).not.toContain("[auto]");
|
||||
expect(frame!).not.toContain("plan]");
|
||||
expect(frame!).not.toContain("auto]");
|
||||
} finally {
|
||||
unmount();
|
||||
}
|
||||
|
|
@ -113,7 +113,7 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
|
|||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
let frame = lastFrame();
|
||||
expect(frame!).toContain("[plan]");
|
||||
expect(frame!).toContain("plan]");
|
||||
|
||||
// Send a message while in plan mode
|
||||
stdin.write("Test message");
|
||||
|
|
@ -129,8 +129,8 @@ describe("TUIChat - Plan Mode Bug Reproduction", () => {
|
|||
frame = lastFrame();
|
||||
|
||||
// This should work - if it fails, we've reproduced the "can't switch back" bug
|
||||
expect(frame!).toContain("[auto]");
|
||||
expect(frame!).not.toContain("[plan]");
|
||||
expect(frame!).toContain("auto]");
|
||||
expect(frame!).not.toContain("plan]");
|
||||
} finally {
|
||||
unmount();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,24 +20,24 @@ describe("ModeIndicator", () => {
|
|||
|
||||
it("should display plan mode with blue color", () => {
|
||||
const { lastFrame } = render(<ModeIndicator mode="plan" />);
|
||||
expect(lastFrame()).toContain("[plan]");
|
||||
expect(lastFrame()).toContain("plan]");
|
||||
});
|
||||
|
||||
it("should display auto mode with green color", () => {
|
||||
const { lastFrame } = render(<ModeIndicator mode="auto" />);
|
||||
expect(lastFrame()).toContain("[auto]");
|
||||
expect(lastFrame()).toContain("auto]");
|
||||
});
|
||||
|
||||
it("should use current mode from service when no mode prop provided", () => {
|
||||
modeService.switchMode("plan");
|
||||
const { lastFrame } = render(<ModeIndicator />);
|
||||
expect(lastFrame()).toContain("[plan]");
|
||||
expect(lastFrame()).toContain("plan]");
|
||||
});
|
||||
|
||||
it("should prioritize mode prop over service mode", () => {
|
||||
modeService.switchMode("plan");
|
||||
const { lastFrame } = render(<ModeIndicator mode="auto" />);
|
||||
expect(lastFrame()).toContain("[auto]");
|
||||
expect(lastFrame()).toContain("auto]");
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -51,12 +51,12 @@ describe("ModeIndicator", () => {
|
|||
// Switch to plan
|
||||
modeService.switchMode("plan");
|
||||
rerender(<ModeIndicator />);
|
||||
expect(lastFrame()).toContain("[plan]");
|
||||
expect(lastFrame()).toContain("plan]");
|
||||
|
||||
// Switch to auto
|
||||
modeService.switchMode("auto");
|
||||
rerender(<ModeIndicator />);
|
||||
expect(lastFrame()).toContain("[auto]");
|
||||
expect(lastFrame()).toContain("auto]");
|
||||
|
||||
// Switch back to normal
|
||||
modeService.switchMode("normal");
|
||||
|
|
|
|||
|
|
@ -74,11 +74,10 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
|
|||
}, [chatHistory]);
|
||||
|
||||
// Split chat history into stable and pending items
|
||||
// Take the last 2 items as "pending" (can be updated dynamically)
|
||||
// Only put items in pending if they contain tool calls with "calling" status
|
||||
// Everything else goes into static content
|
||||
const { staticItems, pendingItems } = React.useMemo(() => {
|
||||
const items: React.ReactElement[] = [];
|
||||
const PENDING_ITEMS_COUNT = 2;
|
||||
|
||||
// Add intro message as first item if it should be shown
|
||||
if (showIntroMessage) {
|
||||
|
|
@ -92,13 +91,34 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
|
|||
);
|
||||
}
|
||||
|
||||
// Determine split point for stable vs pending items
|
||||
const stableCount = Math.max(
|
||||
0,
|
||||
filteredChatHistory.length - PENDING_ITEMS_COUNT,
|
||||
);
|
||||
const stableHistory = filteredChatHistory.slice(0, stableCount);
|
||||
const pendingHistory = filteredChatHistory.slice(stableCount);
|
||||
// Helper function to check if an item has pending tool calls
|
||||
const hasPendingToolCalls = (item: ChatHistoryItem): boolean => {
|
||||
return !!(
|
||||
item.toolCallStates &&
|
||||
item.toolCallStates.some(
|
||||
(toolState) =>
|
||||
toolState.status === "calling" ||
|
||||
toolState.status === "generating" ||
|
||||
toolState.status === "generated",
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
// Find the first message with pending tool calls from the end
|
||||
let pendingStartIndex = filteredChatHistory.length;
|
||||
for (let i = filteredChatHistory.length - 1; i >= 0; i--) {
|
||||
if (hasPendingToolCalls(filteredChatHistory[i])) {
|
||||
pendingStartIndex = i;
|
||||
// If there's a message after this one, include it too as it might be related
|
||||
if (i + 1 < filteredChatHistory.length) {
|
||||
// Keep the pending start index as is, so we include the next message
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const stableHistory = filteredChatHistory.slice(0, pendingStartIndex);
|
||||
const pendingHistory = filteredChatHistory.slice(pendingStartIndex);
|
||||
|
||||
// Add stable messages to static items
|
||||
stableHistory.forEach((item, index) => {
|
||||
|
|
@ -107,7 +127,7 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
|
|||
|
||||
// Pending items will be rendered dynamically outside Static
|
||||
const pendingElements = pendingHistory.map((item, index) =>
|
||||
renderMessage(item, stableCount + index),
|
||||
renderMessage(item, pendingStartIndex + index),
|
||||
);
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import { v4 as uuidv4 } from "uuid";
|
|||
|
||||
import { initializeChatHistory } from "../../commands/chat.js";
|
||||
import { compactChatHistory } from "../../compaction.js";
|
||||
import { convertFromUnifiedHistory } from "../../messageConversion.js";
|
||||
import { loadSession, updateSessionHistory } from "../../session.js";
|
||||
import { posthogService } from "../../telemetry/posthogService.js";
|
||||
import { telemetryService } from "../../telemetry/telemetryService.js";
|
||||
|
|
@ -323,9 +322,8 @@ export async function handleAutoCompaction({
|
|||
}> {
|
||||
try {
|
||||
// Check if auto-compaction is needed
|
||||
// Convert to legacy format for token counting
|
||||
const legacyHistory = convertFromUnifiedHistory(chatHistory);
|
||||
if (!model || !shouldAutoCompact(legacyHistory, model)) {
|
||||
// Check if auto-compaction is needed using ChatHistoryItem directly
|
||||
if (!model || !shouldAutoCompact(chatHistory, model)) {
|
||||
return {
|
||||
currentChatHistory: chatHistory,
|
||||
currentCompactionIndex: _compactionIndex,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import {
|
||||
|
|
@ -8,7 +8,7 @@ import {
|
|||
} from "../../util/tokenizer.js";
|
||||
|
||||
interface UseContextPercentageProps {
|
||||
chatHistory: ChatCompletionMessageParam[];
|
||||
chatHistory: ChatHistoryItem[];
|
||||
model?: ModelConfig;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { logger } from "./logger.js";
|
||||
import {
|
||||
AUTO_COMPACT_THRESHOLD,
|
||||
calculateContextUsagePercentage,
|
||||
countChatHistoryItemTokens,
|
||||
countChatHistoryTokens,
|
||||
countMessageTokens,
|
||||
getModelContextLimit,
|
||||
|
|
@ -56,49 +57,79 @@ describe("tokenizer", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("countMessageTokens", () => {
|
||||
describe("countChatHistoryItemTokens", () => {
|
||||
it("should count tokens for string content", () => {
|
||||
const message: ChatCompletionMessageParam = {
|
||||
role: "user",
|
||||
content: "Hello world", // 11 chars -> ~3 tokens + 2 for role = 5
|
||||
const historyItem: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "user",
|
||||
content: "Hello world", // 11 chars -> ~3 tokens + 2 for role = 5
|
||||
},
|
||||
contextItems: [],
|
||||
};
|
||||
|
||||
const tokenCount = countMessageTokens(message);
|
||||
const tokenCount = countChatHistoryItemTokens(historyItem);
|
||||
expect(tokenCount).toBeGreaterThan(0);
|
||||
expect(tokenCount).toBe(5); // 3 content tokens + 2 role tokens
|
||||
});
|
||||
|
||||
it("should count tokens for array content", () => {
|
||||
const message: ChatCompletionMessageParam = {
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "Hello" }, // 5 chars -> ~2 tokens
|
||||
{ type: "image_url", image_url: { url: "test.jpg" } }, // +85 tokens
|
||||
],
|
||||
const historyItem: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "Hello" }, // 5 chars -> ~2 tokens
|
||||
{ type: "imageUrl", imageUrl: { url: "test.jpg" } }, // +85 tokens
|
||||
],
|
||||
},
|
||||
contextItems: [],
|
||||
};
|
||||
|
||||
const tokenCount = countMessageTokens(message);
|
||||
const tokenCount = countChatHistoryItemTokens(historyItem);
|
||||
expect(tokenCount).toBe(89); // 2 + 85 + 2 role tokens
|
||||
});
|
||||
|
||||
it("should count tokens for tool calls", () => {
|
||||
const message: ChatCompletionMessageParam = {
|
||||
role: "assistant",
|
||||
content: "I'll help you",
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call_1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_function", // ~3 tokens + 10 overhead
|
||||
arguments: '{"param": "value"}', // ~5 tokens
|
||||
const historyItem: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: "I'll help you",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "call_1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_function", // ~3 tokens + 10 overhead
|
||||
arguments: '{"param": "value"}', // ~5 tokens
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
contextItems: [],
|
||||
};
|
||||
|
||||
const tokenCount = countChatHistoryItemTokens(historyItem);
|
||||
expect(tokenCount).toBeGreaterThan(20);
|
||||
});
|
||||
|
||||
it("should count tokens for context items", () => {
|
||||
const historyItem: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "user",
|
||||
content: "Hello", // 5 chars -> ~2 tokens
|
||||
},
|
||||
contextItems: [
|
||||
{
|
||||
id: { providerTitle: "test", itemId: "1" },
|
||||
content: "Context content", // 15 chars -> ~4 tokens
|
||||
name: "Test context", // 12 chars -> ~3 tokens
|
||||
description: "Test description",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const tokenCount = countMessageTokens(message);
|
||||
expect(tokenCount).toBeGreaterThan(20);
|
||||
const tokenCount = countChatHistoryItemTokens(historyItem);
|
||||
// 2 (content) + 2 (role) + 4 (context content) + 3 (context name) + 5 (context overhead) = 16
|
||||
expect(tokenCount).toBe(16);
|
||||
});
|
||||
|
||||
it("should handle errors gracefully", () => {
|
||||
|
|
@ -108,12 +139,36 @@ describe("tokenizer", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("countMessageTokens (legacy)", () => {
|
||||
it("should call countChatHistoryItemTokens", () => {
|
||||
const historyItem: ChatHistoryItem = {
|
||||
message: {
|
||||
role: "user",
|
||||
content: "Hello world",
|
||||
},
|
||||
contextItems: [],
|
||||
};
|
||||
|
||||
const tokenCount = countMessageTokens(historyItem);
|
||||
expect(tokenCount).toBe(5); // Same as countChatHistoryItemTokens
|
||||
});
|
||||
});
|
||||
|
||||
describe("countChatHistoryTokens", () => {
|
||||
it("should count tokens for multiple messages", () => {
|
||||
const chatHistory: ChatCompletionMessageParam[] = [
|
||||
{ role: "system", content: "You are helpful" },
|
||||
{ role: "user", content: "Hello" },
|
||||
{ role: "assistant", content: "Hi there" },
|
||||
const chatHistory: ChatHistoryItem[] = [
|
||||
{
|
||||
message: { role: "system", content: "You are helpful" },
|
||||
contextItems: [],
|
||||
},
|
||||
{
|
||||
message: { role: "user", content: "Hello" },
|
||||
contextItems: [],
|
||||
},
|
||||
{
|
||||
message: { role: "assistant", content: "Hi there" },
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
|
||||
const tokenCount = countChatHistoryTokens(chatHistory);
|
||||
|
|
@ -159,12 +214,15 @@ describe("tokenizer", () => {
|
|||
},
|
||||
});
|
||||
|
||||
const createChatHistory = (
|
||||
tokenCount: number,
|
||||
): ChatCompletionMessageParam[] => {
|
||||
const createChatHistory = (tokenCount: number): ChatHistoryItem[] => {
|
||||
// Create a message that will result in approximately the desired token count
|
||||
const content = "x".repeat(tokenCount * 4); // 4 chars per token
|
||||
return [{ role: "user", content }];
|
||||
return [
|
||||
{
|
||||
message: { role: "user", content },
|
||||
contextItems: [],
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
it("should compact when input tokens exceed threshold with maxTokens", () => {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import type { ChatHistoryItem } from "core/index.js";
|
||||
import { encode } from "gpt-tokenizer";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
|
||||
import { logger } from "./logger.js";
|
||||
|
||||
|
|
@ -23,16 +23,18 @@ export function getModelContextLimit(model: ModelConfig): number {
|
|||
}
|
||||
|
||||
/**
|
||||
* Estimate the token count for a single message
|
||||
* @param message The message to count tokens for
|
||||
* Estimate the token count for a single ChatHistoryItem
|
||||
* @param historyItem The ChatHistoryItem to count tokens for
|
||||
* @returns The estimated token count
|
||||
*/
|
||||
export function countMessageTokens(
|
||||
message: ChatCompletionMessageParam,
|
||||
export function countChatHistoryItemTokens(
|
||||
historyItem: ChatHistoryItem,
|
||||
): number {
|
||||
try {
|
||||
let tokenCount = 0;
|
||||
|
||||
const message = historyItem.message;
|
||||
|
||||
// Count tokens in content
|
||||
if (typeof message.content === "string") {
|
||||
tokenCount += encode(message.content).length;
|
||||
|
|
@ -44,7 +46,7 @@ export function countMessageTokens(
|
|||
}
|
||||
// Images and other content types have their own token costs
|
||||
// but we'll use a rough estimate for now
|
||||
if (part.type === "image_url") {
|
||||
if (part.type === "imageUrl") {
|
||||
tokenCount += 85; // Rough estimate for image tokens
|
||||
}
|
||||
}
|
||||
|
|
@ -54,12 +56,15 @@ export function countMessageTokens(
|
|||
tokenCount += 2;
|
||||
|
||||
// Add tokens for tool calls if present
|
||||
if ("tool_calls" in message && message.tool_calls) {
|
||||
for (const toolCall of message.tool_calls) {
|
||||
if ("toolCalls" in message && message.toolCalls) {
|
||||
for (const toolCall of message.toolCalls) {
|
||||
if (!toolCall.function) {
|
||||
continue;
|
||||
}
|
||||
// Function name and structure overhead
|
||||
tokenCount += encode(toolCall.function.name).length + 10;
|
||||
tokenCount += encode(toolCall.function.name ?? "").length + 10;
|
||||
// Arguments
|
||||
tokenCount += encode(toolCall.function.arguments).length;
|
||||
tokenCount += encode(toolCall.function.arguments ?? "").length;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -68,30 +73,50 @@ export function countMessageTokens(
|
|||
tokenCount += 5; // Tool message structure overhead
|
||||
}
|
||||
|
||||
// Add tokens for context items
|
||||
for (const contextItem of historyItem.contextItems) {
|
||||
tokenCount += encode(contextItem.content).length;
|
||||
tokenCount += encode(contextItem.name).length;
|
||||
tokenCount += 5; // Context item structure overhead
|
||||
}
|
||||
|
||||
return tokenCount;
|
||||
} catch (error) {
|
||||
logger.error("Error counting tokens for message", error);
|
||||
logger.error("Error counting tokens for history item", error);
|
||||
// Return a rough estimate based on character count
|
||||
const message = historyItem.message;
|
||||
const content =
|
||||
typeof message.content === "string"
|
||||
? message.content
|
||||
: JSON.stringify(message.content);
|
||||
return Math.ceil(content.length / 4); // Rough estimate: 4 chars per token
|
||||
// Add rough estimate for context items
|
||||
const contextContent = historyItem.contextItems
|
||||
.map((item) => item.content + item.name)
|
||||
.join("");
|
||||
return Math.ceil((content.length + contextContent.length) / 4); // Rough estimate: 4 chars per token
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the token count for a single message (legacy compatibility)
|
||||
* @param message The message to count tokens for
|
||||
* @returns The estimated token count
|
||||
* @deprecated Use countChatHistoryItemTokens instead
|
||||
*/
|
||||
export function countMessageTokens(message: ChatHistoryItem): number {
|
||||
return countChatHistoryItemTokens(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the total token count for a chat history
|
||||
* @param chatHistory The chat history to count tokens for
|
||||
* @returns The estimated total token count
|
||||
*/
|
||||
export function countChatHistoryTokens(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
): number {
|
||||
export function countChatHistoryTokens(chatHistory: ChatHistoryItem[]): number {
|
||||
let totalTokens = 0;
|
||||
|
||||
for (const message of chatHistory) {
|
||||
totalTokens += countMessageTokens(message);
|
||||
for (const historyItem of chatHistory) {
|
||||
totalTokens += countChatHistoryItemTokens(historyItem);
|
||||
}
|
||||
|
||||
// Add some overhead for message structure (roughly 3 tokens per message)
|
||||
|
|
@ -121,7 +146,7 @@ export function calculateContextUsagePercentage(
|
|||
* @returns Whether auto-compacting should be triggered
|
||||
*/
|
||||
export function shouldAutoCompact(
|
||||
chatHistory: ChatCompletionMessageParam[],
|
||||
chatHistory: ChatHistoryItem[],
|
||||
model: ModelConfig,
|
||||
): boolean {
|
||||
const inputTokens = countChatHistoryTokens(chatHistory);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue