prune both tool calls

This commit is contained in:
Dallin Romney 2025-03-26 21:09:47 -07:00
parent c12bc10b8d
commit debeca96d2
6 changed files with 43 additions and 28 deletions

View file

@ -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<void> { }
async close(): Promise<void> {}
async encode(text: string): Promise<number[]> {
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,
};

View file

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

View file

@ -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 = {

View file

@ -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) {
<StopButton
className="text-gray-400"
onClick={() => {
dispatch(setInactive());
dispatch(clearLastEmptyResponse());
dispatch(cancelStream());
}}
>
{getMetaKeyLabel()} ⌫ Cancel

View file

@ -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) {

View file

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