From cbfb1314eb80a2a8ad9d16086467e533cd2f3012 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 19 Jan 2024 17:59:37 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20setup=20proper=20types=20for=20i?= =?UTF-8?q?mage=20support?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/commands/index.ts | 5 +- core/commands/slash/commit.ts | 3 +- core/commands/slash/draftIssue.ts | 3 +- core/commands/slash/edit.ts | 3 +- core/commands/slash/stackOverflow.ts | 4 +- core/commands/slash/verticalEdit.ts | 3 +- core/index.d.ts | 12 ++- core/llm/countTokens.ts | 56 +++++++++-- core/llm/index.ts | 24 +++++ core/llm/llms/Flowise.ts | 95 ++++++++++++------- core/llm/llms/Gemini.ts | 3 +- core/llm/llms/GooglePalm.ts | 3 +- core/llm/llms/OpenAI.ts | 29 ++++-- core/llm/llms/Replicate.ts | 6 +- core/llm/templates/chat.ts | 5 +- gui/src/components/gui/StepContainer.tsx | 3 +- .../components/mainInput/ContinueInputBox.tsx | 2 - gui/src/components/mainInput/TipTapEditor.tsx | 3 +- gui/src/hooks/useHistory.tsx | 8 +- gui/src/pages/gui.tsx | 1 - 20 files changed, 197 insertions(+), 74 deletions(-) diff --git a/core/commands/index.ts b/core/commands/index.ts index a547aa2ff..f686f9273 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,4 +1,5 @@ import { CustomCommand, SlashCommand, SlashCommandDescription } from ".."; +import { stripImages } from "../llm/countTokens"; import SlashCommands from "./slash"; export function slashFromCustomCommand( @@ -14,7 +15,7 @@ export function slashFromCustomCommand( for (let i = messages.length - 1; i >= 0; i--) { if ( messages[i].role === "user" && - messages[i].content.startsWith(`/${customCommand.name}`) + stripImages(messages[i].content).startsWith(`/${customCommand.name}`) ) { messages[i] = { ...messages[i], content: promptUserInput }; break; @@ -22,7 +23,7 @@ export function slashFromCustomCommand( } for await (const chunk of llm.streamChat(messages)) { - yield chunk.content; + yield stripImages(chunk.content); } }, }; diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index 55f5f92e4..34775fae1 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -1,4 +1,5 @@ import { SlashCommand } from "../.."; +import { stripImages } from "../../llm/countTokens"; const CommitMessageCommand: SlashCommand = { name: "commit", @@ -9,7 +10,7 @@ const CommitMessageCommand: SlashCommand = { for await (const chunk of llm.streamChat([ { role: "user", content: prompt }, ])) { - yield chunk.content; + yield stripImages(chunk.content); } }, }; diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 347e0e975..9f7b573ed 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -1,4 +1,5 @@ import { ChatMessage, SlashCommand } from "../.."; +import { stripImages } from "../../llm/countTokens"; import { removeQuotesAndEscapes } from "../../util"; const PROMPT = ( @@ -43,7 +44,7 @@ const DraftIssueCommand: SlashCommand = { for await (const chunk of llm.streamChat(messages)) { body += chunk.content; - yield chunk.content; + yield stripImages(chunk.content); } const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent( diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index b6ef08f83..5f7201d20 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -1,4 +1,5 @@ import { ContextItemWithId, ILLM, SlashCommand } from "../.."; +import { stripImages } from "../../llm/countTokens"; import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../../util"; import { RangeInFileWithContents, @@ -457,7 +458,7 @@ const EditSlashCommand: SlashCommand = { 4096 ), })) { - yield chunk.content; + yield stripImages(chunk.content); } } diff --git a/core/commands/slash/stackOverflow.ts b/core/commands/slash/stackOverflow.ts index 8c9e64ba5..4d263cdff 100644 --- a/core/commands/slash/stackOverflow.ts +++ b/core/commands/slash/stackOverflow.ts @@ -1,5 +1,5 @@ import { ChatMessageRole, SlashCommand } from "../.."; -import { pruneStringFromBottom } from "../../llm/countTokens"; +import { pruneStringFromBottom, stripImages } from "../../llm/countTokens"; const SERVER_URL = "https://proxy-server-l6vsfbzhba-uw.a.run.app"; const PROMPT = ( @@ -114,7 +114,7 @@ const StackOverflowSlashCommand: SlashCommand = { })), { role: "user", content: PROMPT(input) }, ])) { - yield chunk.content; + yield stripImages(chunk.content); } }, }; diff --git a/core/commands/slash/verticalEdit.ts b/core/commands/slash/verticalEdit.ts index 8a86e790b..7cd0ba4d9 100644 --- a/core/commands/slash/verticalEdit.ts +++ b/core/commands/slash/verticalEdit.ts @@ -1,6 +1,7 @@ import { ContextItemWithId, DiffLine, ILLM, SlashCommand } from "../.."; import { streamDiff } from "../../diff/streamDiff"; import { LineStream, streamLines } from "../../diff/util"; +import { stripImages } from "../../llm/countTokens"; import { gptEditPrompt } from "../../llm/templates/edit"; import { dedentAndGetCommonWhitespace, @@ -81,7 +82,7 @@ function constructPrompt( }); return typeof rendered === "string" ? rendered - : rendered[rendered.length - 1].content; + : stripImages(rendered[rendered.length - 1].content); } async function* addIndentation( diff --git a/core/index.d.ts b/core/index.d.ts index 59f82c4b6..3162adbde 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -59,6 +59,8 @@ export interface ILLM extends LLMOptions { ): Promise; countTokens(text: string): number; + + supportsImages(): boolean; } export interface ContextProviderDescription { @@ -139,9 +141,17 @@ export interface CompletionOptions extends BaseCompletionOptions { export type ChatMessageRole = "user" | "assistant" | "system"; +export interface MessagePart { + type: "text" | "imageUrl"; + text?: string; + imageUrl?: { url: string }; +} + +export type MessageContent = string | MessagePart[]; + export interface ChatMessage { role: ChatMessageRole; - content: string; + content: MessageContent; } export interface ContextItemId { diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 7e043d9a7..6617a4e4c 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,5 +1,5 @@ import { encodingForModel as _encodingForModel, Tiktoken } from "js-tiktoken"; -import { ChatMessage } from ".."; +import { ChatMessage, MessageContent, MessagePart } from ".."; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants"; let encoding: Tiktoken | null = null; @@ -13,9 +13,25 @@ function encodingForModel(modelName: string): Tiktoken { return encoding; } -function countTokens(content: string, modelName: string): number { +function countImageTokens(content: MessagePart): number { + if (content.type === "imageUrl") { + return 85; + } else { + throw new Error("Non-image content type"); + } +} + +function countTokens(content: MessageContent, modelName: string): number { const encoding = encodingForModel(modelName); - return encoding.encode(content, "all", []).length; + if (Array.isArray(content)) { + return content.reduce((acc, part) => { + return acc + part.type === "imageUrl" + ? countImageTokens(part) + : encoding.encode(part.text || "", "all", []).length; + }, 0); + } else { + return encoding.encode(content, "all", []).length; + } } function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { @@ -34,6 +50,17 @@ function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { return flattened; } +export function stripImages(content: MessageContent): string { + if (Array.isArray(content)) { + return content + .filter((part) => part.type === "text") + .map((part) => part.text) + .join(""); + } else { + return content; + } +} + function countChatMessageTokens( modelName: string, chatMessage: ChatMessage @@ -97,8 +124,12 @@ function pruneRawPromptFromBottom( return pruneStringFromBottom(modelName, maxTokens, prompt); } -function summarize(message: string): string { - return message.substring(0, 100) + "..."; +function summarize(message: MessageContent): string { + if (Array.isArray(message)) { + return stripImages(message).substring(0, 100) + "..."; + } else { + return message.substring(0, 100) + "..."; + } } function pruneChatHistory( @@ -129,7 +160,7 @@ function pruneChatHistory( for (let i = 0; i < longerThanOneThird.length; i++) { // Prune line-by-line from the top const message = longerThanOneThird[i]; - let lines = message.content.split("\n"); + let lines = stripImages(message.content).split("\n"); let tokensRemoved = 0; while ( tokensRemoved < distanceFromThird[i] && @@ -190,7 +221,7 @@ function pruneChatHistory( message.content = pruneRawPromptFromTop( modelName, contextLength, - message.content, + stripImages(message.content), tokensForCompletion ); totalTokens = contextLength; @@ -204,6 +235,7 @@ function compileChatMessages( msgs: ChatMessage[] | undefined = undefined, contextLength: number, maxTokens: number, + supportsImages: boolean, prompt: string | undefined = undefined, functions: any[] | undefined = undefined, systemMessage: string | undefined = undefined @@ -241,6 +273,16 @@ function compileChatMessages( ); } + // If images not supported, convert MessagePart[] to string + if (!supportsImages) { + for (const msg of msgsCopy) { + if ("content" in msg && Array.isArray(msg.content)) { + const content = stripImages(msg.content); + msg.content = content; + } + } + } + const history = pruneChatHistory( modelName, msgsCopy, diff --git a/core/llm/index.ts b/core/llm/index.ts index eefaec334..73c3c5600 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -55,6 +55,25 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [ "ollama", ]; +const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = ["openai", "ollama"]; + +export function modelSupportsImages( + provider: ModelProvider, + model: string +): boolean { + if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) { + return false; + } + if (model.includes("llava")) { + return true; + } + if (["gpt-4-vision-preview"].includes(model)) { + return true; + } + + return false; +} + function autodetectTemplateType(model: string): TemplateType | undefined { const lower = model.toLowerCase(); @@ -204,6 +223,10 @@ export abstract class BaseLLM implements ILLM { return (this.constructor as typeof BaseLLM).providerName; } + supportsImages(): boolean { + return modelSupportsImages(this.providerName, this.model); + } + uniqueId: string; model: string; @@ -297,6 +320,7 @@ export abstract class BaseLLM implements ILLM { messages, contextLength, options.maxTokens || DEFAULT_MAX_TOKENS, + this.supportsImages(), undefined, functions, this.systemMessage diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index 16748866a..1d2cc777c 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -1,4 +1,4 @@ -import socketIOClient, { Socket } from 'socket.io-client'; +import socketIOClient, { Socket } from "socket.io-client"; import { BaseLLM } from ".."; import { ChatMessage, @@ -6,6 +6,7 @@ import { LLMOptions, ModelProvider, } from "../.."; +import { stripImages } from "../countTokens"; interface IFlowiseApiOptions { /** Sampling temperature to use */ @@ -39,7 +40,7 @@ interface IFlowiseSocketManager { hasNextTokenPromiseResolve: (value: boolean | PromiseLike) => void; hasNextTokenPromiseReject: (reason?: any) => void; messageHistory: string[]; - } + }; error?: Error; getCurrentMessage: () => string; } @@ -61,8 +62,8 @@ class Flowise extends BaseLLM { apiBase: "http://localhost:3000", }; static FlowiseMessageType = { - User: 'userMessage', - Assistant: 'apiMessage' + User: "userMessage", + Assistant: "apiMessage", }; protected additionalFlowiseConfiguration: IFlowiseKeyValueProperty[] = []; @@ -73,7 +74,8 @@ class Flowise extends BaseLLM { super(options); this.timeout = options.timeout ?? 5000; this.additionalHeaders = options.additionalHeaders ?? []; - this.additionalFlowiseConfiguration = options.additionalFlowiseConfiguration ?? []; + this.additionalFlowiseConfiguration = + options.additionalFlowiseConfiguration ?? []; } private _getChatUrl(): string { @@ -86,11 +88,11 @@ class Flowise extends BaseLLM { private _getHeaders(): HeadersInit | undefined { const headers: HeadersInit = { - "Content-Type": "application/json" + "Content-Type": "application/json", }; if (this.apiKey) { - headers['Authorization'] = `Bearer ${this.apiKey}`; + headers["Authorization"] = `Bearer ${this.apiKey}`; } for (const additionalHeader of this.additionalHeaders) { @@ -118,44 +120,53 @@ class Flowise extends BaseLLM { protected async *_streamComplete( prompt: string, - options: CompletionOptions, + options: CompletionOptions ): AsyncGenerator { const message: ChatMessage = { role: "user", content: prompt }; for await (const chunk of this._streamChat([message], options)) { - yield chunk.content; + yield stripImages(chunk.content); } } - protected async *_streamChat(messages: ChatMessage[], options: CompletionOptions): AsyncGenerator { + protected async *_streamChat( + messages: ChatMessage[], + options: CompletionOptions + ): AsyncGenerator { const requestBody = this._getRequestBody(messages, options); const { socket, socketInfo } = await this._initializeSocket(); const request = this.fetch(this._getChatUrl(), { method: "POST", headers: this._getHeaders(), - body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }) - }).then(res => res.json()); + body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), + }).then((res) => res.json()); while (await socketInfo.hasNextToken()) { - yield { role: 'assistant', content: socketInfo.getCurrentMessage() }; + yield { role: "assistant", content: socketInfo.getCurrentMessage() }; } if (socketInfo.error) { socket.disconnect(); try { - yield { role: 'assistant', content: (await request).text }; + yield { role: "assistant", content: (await request).text }; } catch (error: any) { - yield { role: 'assistant', content: (error as Error).message ?? error }; + yield { role: "assistant", content: (error as Error).message ?? error }; } } socket.disconnect(); } - protected _getRequestBody(messages: ChatMessage[], options: CompletionOptions): any { + protected _getRequestBody( + messages: ChatMessage[], + options: CompletionOptions + ): any { const lastMessage = messages[messages.length - 1]; const history = messages - .filter(m => m !== lastMessage) - .map(m => ({ - type: m.role === 'user' ? Flowise.FlowiseMessageType.User : Flowise.FlowiseMessageType.Assistant, - message: m.content + .filter((m) => m !== lastMessage) + .map((m) => ({ + type: + m.role === "user" + ? Flowise.FlowiseMessageType.User + : Flowise.FlowiseMessageType.Assistant, + message: m.content, })); const requestBody = { question: lastMessage.content, @@ -165,54 +176,66 @@ class Flowise extends BaseLLM { return requestBody; } - protected _initializeSocket(): Promise<{ socket: Socket, socketInfo: IFlowiseSocketManager }> { + protected _initializeSocket(): Promise<{ + socket: Socket; + socketInfo: IFlowiseSocketManager; + }> { return new Promise((res, rej) => { const socket = socketIOClient(this._getSocketUrl()); const socketInfo: IFlowiseSocketManager = { isConnected: false, hasNextToken: () => Promise.resolve(false), - internal: { hasNextTokenPromiseResolve: () => { }, hasNextTokenPromiseReject: () => { }, messageHistory: [] }, - getCurrentMessage: () => '' + internal: { + hasNextTokenPromiseResolve: () => {}, + hasNextTokenPromiseReject: () => {}, + messageHistory: [], + }, + getCurrentMessage: () => "", }; - socketInfo.getCurrentMessage = () => socketInfo.internal.messageHistory.shift() ?? '' + socketInfo.getCurrentMessage = () => + socketInfo.internal.messageHistory.shift() ?? ""; socketInfo.hasNextToken = () => { - return new Promise((hasNextTokenResolve, hasNextTokenReject) => { - socketInfo.internal.hasNextTokenPromiseResolve = hasNextTokenResolve; - socketInfo.internal.hasNextTokenPromiseReject = hasNextTokenReject; - }); + return new Promise( + (hasNextTokenResolve, hasNextTokenReject) => { + socketInfo.internal.hasNextTokenPromiseResolve = + hasNextTokenResolve; + socketInfo.internal.hasNextTokenPromiseReject = hasNextTokenReject; + } + ); }; const resetTimeout = () => { clearTimeout(socketInfo.internal.timeout); socketInfo.internal.timeout = setTimeout(() => { - socketInfo.error = new Error('Timeout occurred'); + socketInfo.error = new Error("Timeout occurred"); socketInfo.internal.hasNextTokenPromiseResolve(false); rej(`Timeout trying to connect to socket: ${this._getSocketUrl()}`); }, this.timeout); }; resetTimeout(); - socket.on('connect', () => { + socket.on("connect", () => { socketInfo.isConnected = true; resetTimeout(); res({ socket, socketInfo }); }); - socket.on('token', (token) => { + socket.on("token", (token) => { if (socketInfo.isConnected) { socketInfo.internal.messageHistory.push(token); resetTimeout(); socketInfo.internal.hasNextTokenPromiseResolve(true); } }); - socket.on('error', (error) => { + socket.on("error", (error) => { clearTimeout(socketInfo.internal.timeout); socketInfo.error = error; socketInfo.internal.hasNextTokenPromiseResolve(false); rej(`Error trying to connect to socket: ${this._getSocketUrl()}`); }); - socket.on('end', () => { + socket.on("end", () => { clearTimeout(socketInfo.internal.timeout); - socketInfo.hasNextToken = () => Promise.resolve(Boolean(socketInfo.internal.messageHistory.length)); + socketInfo.hasNextToken = () => + Promise.resolve(Boolean(socketInfo.internal.messageHistory.length)); }); - socket.on('disconnect', () => { + socket.on("disconnect", () => { socketInfo.isConnected = false; clearTimeout(socketInfo.internal.timeout); socketInfo.internal.hasNextTokenPromiseResolve(false); @@ -221,4 +244,4 @@ class Flowise extends BaseLLM { } } -export default Flowise; \ No newline at end of file +export default Flowise; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index b426ae7ed..eb503f7a4 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -5,6 +5,7 @@ import { LLMOptions, ModelProvider, } from "../.."; +import { stripImages } from "../countTokens"; class Gemini extends BaseLLM { static providerName: ModelProvider = "gemini"; @@ -22,7 +23,7 @@ class Gemini extends BaseLLM { [{ role: "user", content: prompt }], options )) { - yield chunk.content; + yield stripImages(chunk.content); } } diff --git a/core/llm/llms/GooglePalm.ts b/core/llm/llms/GooglePalm.ts index c80088805..93a81943e 100644 --- a/core/llm/llms/GooglePalm.ts +++ b/core/llm/llms/GooglePalm.ts @@ -5,6 +5,7 @@ import { LLMOptions, ModelProvider, } from "../.."; +import { stripImages } from "../countTokens"; import { streamResponse } from "../stream"; class GooglePalm extends BaseLLM { @@ -22,7 +23,7 @@ class GooglePalm extends BaseLLM { [{ content: prompt, role: "user" }], options )) { - yield message.content; + yield stripImages(message.content); } } diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 6ea7ecc99..875eec9f0 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -1,4 +1,3 @@ -import { ChatCompletionCreateParamsBase } from "openai/resources/chat/completions"; import { BaseLLM } from ".."; import { ChatMessage, @@ -6,6 +5,7 @@ import { LLMOptions, ModelProvider, } from "../.."; +import { stripImages } from "../countTokens"; import { streamSse } from "../stream"; const NON_CHAT_MODELS = [ @@ -27,12 +27,23 @@ class OpenAI extends BaseLLM { apiBase: "https://api.openai.com", }; - protected _convertArgs( - options: any, - messages: ChatMessage[] - ): ChatCompletionCreateParamsBase { - const finalOptions: ChatCompletionCreateParamsBase = { - messages, + protected _convertMessage(message: ChatMessage) { + if (typeof message.content === "string") { + return message; + } + + const parts = message.content.map((part) => { + return { type: part.type, text: part.text, image_url: part.imageUrl }; + }); + return { + ...message, + content: parts, + }; + } + + protected _convertArgs(options: any, messages: ChatMessage[]) { + const finalOptions = { + messages: messages.map(this._convertMessage), model: options.model, max_tokens: options.maxTokens, temperature: options.temperature, @@ -87,7 +98,7 @@ class OpenAI extends BaseLLM { [{ role: "user", content: prompt }], options )) { - yield chunk.content; + yield stripImages(chunk.content); } } @@ -152,7 +163,7 @@ class OpenAI extends BaseLLM { ): AsyncGenerator { if (NON_CHAT_MODELS.includes(options.model)) { for await (const content of this._legacystreamComplete( - messages[messages.length - 1]?.content || "", + stripImages(messages[messages.length - 1]?.content || ""), options )) { yield { diff --git a/core/llm/llms/Replicate.ts b/core/llm/llms/Replicate.ts index 8ec1b8300..76c63e881 100644 --- a/core/llm/llms/Replicate.ts +++ b/core/llm/llms/Replicate.ts @@ -6,6 +6,7 @@ import { LLMOptions, ModelProvider, } from "../.."; +import { stripImages } from "../countTokens"; class Replicate extends BaseLLM { private static MODEL_IDS: { @@ -72,7 +73,10 @@ class Replicate extends BaseLLM { messages: ChatMessage[], options: CompletionOptions ): AsyncGenerator { - const resp = await this.complete(messages[0]?.content || "", options); + const resp = await this.complete( + stripImages(messages[0]?.content || ""), + options + ); } } diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index b36cadd06..d360bad18 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -1,4 +1,5 @@ import { ChatMessage } from "../.."; +import { stripImages } from "../countTokens"; function llama2TemplateMessages(msgs: ChatMessage[]): string { if (msgs.length === 0) { @@ -14,7 +15,7 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string { let prompt = ""; let hasSystem = msgs[0].role === "system"; - if (hasSystem && msgs[0].content.trim() === "") { + if (hasSystem && stripImages(msgs[0].content).trim() === "") { hasSystem = false; msgs = msgs.slice(1); } @@ -123,7 +124,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string { prompt += "You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n"; if (msgs[0].role === "system") { - system = msgs.shift()!.content; + system = stripImages(msgs.shift()!.content); } for (let i = 0; i < msgs.length; i++) { diff --git a/gui/src/components/gui/StepContainer.tsx b/gui/src/components/gui/StepContainer.tsx index 86e9a3868..f978c5055 100644 --- a/gui/src/components/gui/StepContainer.tsx +++ b/gui/src/components/gui/StepContainer.tsx @@ -3,6 +3,7 @@ import { HandThumbUpIcon, } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; +import { stripImages } from "core/llm/countTokens"; import { useState } from "react"; import { useSelector } from "react-redux"; import styled from "styled-components"; @@ -91,7 +92,7 @@ function StepContainer(props: StepContainerProps) { fontSize={getFontSize()} > diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index d5cee5935..629d48e63 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -54,7 +54,6 @@ interface ContinueInputBoxProps { onEnter: (editorState: JSONContent) => void; editorState?: JSONContent; - content?: string; contextItems?: ContextItemWithId[]; } @@ -98,7 +97,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { > void; editorState?: JSONContent; - content?: string; } function TipTapEditor(props: TipTapEditorProps) { @@ -218,7 +217,7 @@ function TipTapEditor(props: TipTapEditorProps) { style: "font-size: 14px;", }, }, - content: props.editorState || props.content || "", + content: props.editorState || "", onUpdate: ({ editor, transaction }) => { // If /edit is typed and no context items are selected, select the first diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 7ba2f21b3..f19f4b736 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -1,6 +1,7 @@ import { Dispatch } from "@reduxjs/toolkit"; import { PersistedSessionInfo, SessionInfo } from "core"; import { ideRequest } from "core/ide/messaging"; +import { stripImages } from "core/llm/countTokens"; import { useSelector } from "react-redux"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { newSession } from "../redux/slices/stateSlice"; @@ -31,7 +32,10 @@ function useHistory(dispatch: Dispatch) { dispatch(newSession()); await new Promise((resolve) => setTimeout(resolve, 10)); - let title = truncateText(stateCopy.history[0].message.content, 50); + let title = truncateText( + stripImages(stateCopy.history[0].message.content), + 50 + ); if (!disableSessionTitles) { let { content } = await defaultModel.chat( [ @@ -44,7 +48,7 @@ function useHistory(dispatch: Dispatch) { ], { maxTokens: 20 } ); - title = content; + title = stripImages(content); } const sessionInfo: PersistedSessionInfo = { diff --git a/gui/src/pages/gui.tsx b/gui/src/pages/gui.tsx index 8cef369fe..feac7245c 100644 --- a/gui/src/pages/gui.tsx +++ b/gui/src/pages/gui.tsx @@ -401,7 +401,6 @@ function GUI(props: GUIProps) { isLastUserInput={isLastUserInput(index)} isMainInput={false} editorState={item.editorState} - content={item.message.content} contextItems={item.contextItems} > ) : (