From debeca96d244b9bf90e995d7797be8f95c7521d3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 26 Mar 2025 21:09:47 -0700 Subject: [PATCH] prune both tool calls --- core/llm/countTokens.ts | 29 +++++++++++++------ core/llm/index.ts | 15 +++++----- core/llm/llms/Anthropic.ts | 6 ++++ .../components/mainInput/Lump/LumpToolbar.tsx | 8 ++--- gui/src/redux/thunks/streamNormalInput.ts | 10 +++++-- packages/openai-adapters/src/apis/OpenAI.ts | 3 +- 6 files changed, 43 insertions(+), 28 deletions(-) diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index a05889c52..16ac82100 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -27,9 +27,9 @@ class LlamaEncoding implements Encoding { } class NonWorkerAsyncEncoder implements AsyncEncoder { - constructor(private readonly encoding: Encoding) { } + constructor(private readonly encoding: Encoding) {} - async close(): Promise { } + async close(): Promise {} async encode(text: string): Promise { return this.encoding.encode(text); @@ -313,8 +313,21 @@ function pruneChatHistory( // 4. Remove entire messages in the last 5, except last 1 while (totalTokens > contextLength && chatHistory.length > 1) { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); + // If tool call/response detected prune both (can't have response with no call) + // TODO prune lines from tool response before pruning both messages + if ( + chatHistory.length > 2 && + messageHasToolCalls(chatHistory[0]) && + chatHistory[1].role === "tool" + ) { + const firstMessage = chatHistory.shift()!; + const secondMessage = chatHistory.shift()!; + totalTokens -= countTokens(firstMessage.content, modelName); + totalTokens -= countTokens(secondMessage.content, modelName); + } else { + const message = chatHistory.shift()!; + totalTokens -= countTokens(message.content, modelName); + } } // 5. Truncate last message @@ -328,7 +341,6 @@ function pruneChatHistory( ); totalTokens = contextLength; } - return chatHistory; } @@ -384,8 +396,8 @@ function compileChatMessages( ): ChatMessage[] { let msgsCopy = msgs ? msgs - .map((msg) => ({ ...msg })) - .filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system") + .map((msg) => ({ ...msg })) + .filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system") : []; msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); @@ -470,6 +482,5 @@ export { pruneLinesFromTop, pruneRawPromptFromTop, pruneStringFromBottom, - pruneStringFromTop + pruneStringFromTop, }; - diff --git a/core/llm/index.ts b/core/llm/index.ts index dda2e7a87..d4c53b895 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -195,11 +195,11 @@ export abstract class BaseLLM implements ILLM { options.completionOptions?.maxTokens ?? (llmInfo?.maxCompletionTokens ? Math.min( - llmInfo.maxCompletionTokens, - // Even if the model has a large maxTokens, we don't want to use that every time, - // because it takes away from the context length - this.contextLength / 4, - ) + llmInfo.maxCompletionTokens, + // Even if the model has a large maxTokens, we don't want to use that every time, + // because it takes away from the context length + this.contextLength / 4, + ) : DEFAULT_MAX_TOKENS), }; this.requestOptions = options.requestOptions; @@ -840,7 +840,6 @@ export abstract class BaseLLM implements ILLM { signal, completionOptions, )) { - if (chunk.role === "assistant") { completion += chunk.content; yield chunk; @@ -948,7 +947,7 @@ export abstract class BaseLLM implements ILLM { ); } - protected async * _streamComplete( + protected async *_streamComplete( prompt: string, signal: AbortSignal, options: CompletionOptions, @@ -956,7 +955,7 @@ export abstract class BaseLLM implements ILLM { throw new Error("Not implemented"); } - protected async * _streamChat( + protected async *_streamChat( messages: ChatMessage[], signal: AbortSignal, options: CompletionOptions, diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index b9e51fd28..6d1628f2a 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -1,6 +1,7 @@ import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; +import { LlmApiRequestType } from "../openaiTypeConverters.js"; import { streamSse } from "../stream.js"; class Anthropic extends BaseLLM { @@ -15,6 +16,11 @@ class Anthropic extends BaseLLM { apiBase: "https://api.anthropic.com/v1/", }; + protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [ + "streamChat", + "chat", + ]; + public convertArgs(options: CompletionOptions) { // should be public for use within VertexAI const finalOptions = { diff --git a/gui/src/components/mainInput/Lump/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar.tsx index cca7885d3..e93746726 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar.tsx @@ -2,10 +2,7 @@ import { useContext } from "react"; import styled from "styled-components"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { - clearLastEmptyResponse, - setInactive, -} from "../../../redux/slices/sessionSlice"; +import { cancelStream } from "../../../redux/thunks/cancelStream"; import { getFontSize, getMetaKeyLabel } from "../../../util"; import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; @@ -54,8 +51,7 @@ export function LumpToolbar(props: TopToolbarProps) { { - dispatch(setInactive()); - dispatch(clearLastEmptyResponse()); + dispatch(cancelStream()); }} > {getMetaKeyLabel()} ⌫ Cancel diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 41d7a9587..509a03f7b 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -37,7 +37,7 @@ export const streamNormalInput = createAsyncThunk< if (!defaultModel) { throw new Error("Default model not defined"); } - + // debugger; const includeTools = useTools && modelSupportsTools(defaultModel); // Send request @@ -76,7 +76,7 @@ export const streamNormalInput = createAsyncThunk< dispatch(addPromptCompletionPair([next.value])); try { - if (state.session.mode === "chat") { + if (state.session.mode === "chat" || state.session.mode === "agent") { extra.ideMessenger.post("devdata/log", { name: "chatInteraction", data: { @@ -103,7 +103,11 @@ export const streamNormalInput = createAsyncThunk< console.error("Failed to send dev data interaction log", e); } } - + // await new Promise((resolve) => + // setTimeout(() => { + // resolve(undefined); + // }, 200), + // ); // If it's a tool call that is automatically accepted, we should call it const toolCallState = selectCurrentToolCall(getState()); if (toolCallState) { diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index 358f52dca..45e9bc293 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -1,5 +1,4 @@ import { streamSse } from "@continuedev/fetch"; -import fetch from "node-fetch"; import { OpenAI } from "openai/index"; import { ChatCompletion, @@ -14,7 +13,7 @@ import { } from "openai/resources/index"; import { z } from "zod"; import { OpenAIConfigSchema } from "../types.js"; -import { customFetch, maybeCustomFetch } from "../util.js"; +import { customFetch } from "../util.js"; import { BaseLlmApi, CreateRerankResponse,