🎨 setup proper types for image support
This commit is contained in:
parent
b1a9f51b11
commit
cbfb1314eb
20 changed files with 197 additions and 74 deletions
|
|
@ -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);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
12
core/index.d.ts
vendored
12
core/index.d.ts
vendored
|
|
@ -59,6 +59,8 @@ export interface ILLM extends LLMOptions {
|
|||
): Promise<ChatMessage>;
|
||||
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<boolean>) => 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<string> {
|
||||
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<ChatMessage> {
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
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<boolean>((hasNextTokenResolve, hasNextTokenReject) => {
|
||||
socketInfo.internal.hasNextTokenPromiseResolve = hasNextTokenResolve;
|
||||
socketInfo.internal.hasNextTokenPromiseReject = hasNextTokenReject;
|
||||
});
|
||||
return new Promise<boolean>(
|
||||
(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;
|
||||
export default Flowise;
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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<ChatMessage> {
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -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<ChatMessage> {
|
||||
const resp = await this.complete(messages[0]?.content || "", options);
|
||||
const resp = await this.complete(
|
||||
stripImages(messages[0]?.content || ""),
|
||||
options
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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++) {
|
||||
|
|
|
|||
|
|
@ -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()}
|
||||
>
|
||||
<StyledMarkdownPreview
|
||||
source={props.item.message.content}
|
||||
source={stripImages(props.item.message.content)}
|
||||
showCodeBorder={true}
|
||||
/>
|
||||
</ContentDiv>
|
||||
|
|
|
|||
|
|
@ -54,7 +54,6 @@ interface ContinueInputBoxProps {
|
|||
onEnter: (editorState: JSONContent) => void;
|
||||
|
||||
editorState?: JSONContent;
|
||||
content?: string;
|
||||
contextItems?: ContextItemWithId[];
|
||||
}
|
||||
|
||||
|
|
@ -98,7 +97,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
|
|||
>
|
||||
<TipTapEditor
|
||||
editorState={props.editorState}
|
||||
content={props.content}
|
||||
onEnter={props.onEnter}
|
||||
isMainInput={props.isMainInput}
|
||||
availableContextProviders={availableContextProviders}
|
||||
|
|
|
|||
|
|
@ -68,7 +68,6 @@ interface TipTapEditorProps {
|
|||
onEnter: (editorState: JSONContent) => 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
|
||||
|
||||
|
|
|
|||
|
|
@ -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 = {
|
||||
|
|
|
|||
|
|
@ -401,7 +401,6 @@ function GUI(props: GUIProps) {
|
|||
isLastUserInput={isLastUserInput(index)}
|
||||
isMainInput={false}
|
||||
editorState={item.editorState}
|
||||
content={item.message.content}
|
||||
contextItems={item.contextItems}
|
||||
></ContinueInputBox>
|
||||
) : (
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue