Skip to content

feat: implement csv upload #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
May 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/bright-turkeys-melt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"create-llama": patch
---

Add CSV upload
6 changes: 6 additions & 0 deletions helpers/env-variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,12 @@ const getEngineEnvs = (): EnvVar[] => {
"The number of similar embeddings to return when retrieving documents.",
value: "3",
},
{
name: "STREAM_TIMEOUT",
description:
"The time in milliseconds to wait for the stream to return a response.",
value: "60000",
},
];
};

Expand Down
3 changes: 3 additions & 0 deletions templates/components/ui/html/chat/chat-input.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"use client";

import { Message } from "./chat-messages";

export interface ChatInputProps {
/** The current value of the input */
input?: string;
Expand All @@ -13,6 +15,7 @@ export interface ChatInputProps {
handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
isLoading: boolean;
multiModal?: boolean;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@thucpn Still multimodal props?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah sorry, I forget removing in html template. Let me fix it in this enhance PR:
#105

messages: Message[];
}

export default function ChatInput(props: ChatInputProps) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,23 @@
import { Message, StreamData, streamToResponse } from "ai";
import { Request, Response } from "express";
import { ChatMessage, MessageContent, Settings } from "llamaindex";
import { ChatMessage, Settings } from "llamaindex";
import { createChatEngine } from "./engine/chat";
import { LlamaIndexStream } from "./llamaindex-stream";
import { createCallbackManager } from "./stream-helper";

const convertMessageContent = (
textMessage: string,
imageUrl: string | undefined,
): MessageContent => {
if (!imageUrl) return textMessage;
return [
{
type: "text",
text: textMessage,
},
{
type: "image_url",
image_url: {
url: imageUrl,
},
},
];
};
import {
DataParserOptions,
LlamaIndexStream,
convertMessageContent,
} from "./llamaindex-stream";
import { createCallbackManager, createStreamTimeout } from "./stream-helper";

export const chat = async (req: Request, res: Response) => {
// Init Vercel AI StreamData and timeout
const vercelStreamData = new StreamData();
const streamTimeout = createStreamTimeout(vercelStreamData);
try {
const { messages, data }: { messages: Message[]; data: any } = req.body;
const {
messages,
data,
}: { messages: Message[]; data: DataParserOptions | undefined } = req.body;
const userMessage = messages.pop();
if (!messages || !userMessage || userMessage.role !== "user") {
return res.status(400).json({
Expand All @@ -38,13 +29,7 @@ export const chat = async (req: Request, res: Response) => {
const chatEngine = await createChatEngine();

// Convert message content from Vercel/AI format to LlamaIndex/OpenAI format
const userMessageContent = convertMessageContent(
userMessage.content,
data?.imageUrl,
);

// Init Vercel AI StreamData
const vercelStreamData = new StreamData();
const userMessageContent = convertMessageContent(userMessage.content, data);

// Setup callbacks
const callbackManager = createCallbackManager(vercelStreamData);
Expand All @@ -61,7 +46,8 @@ export const chat = async (req: Request, res: Response) => {
// Return a stream, which can be consumed by the Vercel/AI client
const stream = LlamaIndexStream(response, vercelStreamData, {
parserOptions: {
image_url: data?.imageUrl,
imageUrl: data?.imageUrl,
uploadedCsv: data?.uploadedCsv,
},
});

Expand All @@ -71,5 +57,7 @@ export const chat = async (req: Request, res: Response) => {
return res.status(500).json({
detail: (error as Error).message,
});
} finally {
clearTimeout(streamTimeout);
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,78 @@ import {
type AIStreamCallbacksAndOptions,
} from "ai";
import {
MessageContent,
Metadata,
NodeWithScore,
Response,
ToolCallLLMMessageOptions,
} from "llamaindex";

import { AgentStreamChatResponse } from "llamaindex/agent/base";
import { appendImageData, appendSourceData } from "./stream-helper";
import {
UploadedCsv,
appendCsvData,
appendImageData,
appendSourceData,
} from "./stream-helper";

type LlamaIndexResponse =
| AgentStreamChatResponse<ToolCallLLMMessageOptions>
| Response;

type ParserOptions = {
image_url?: string;
export type DataParserOptions = {
imageUrl?: string;
uploadedCsv?: UploadedCsv;
};

export const convertMessageContent = (
textMessage: string,
additionalData?: DataParserOptions,
): MessageContent => {
if (!additionalData) return textMessage;
const content: MessageContent = [
{
type: "text",
text: textMessage,
},
];
if (additionalData?.imageUrl) {
content.push({
type: "image_url",
image_url: {
url: additionalData?.imageUrl,
},
});
}

if (additionalData?.uploadedCsv) {
const csvContent =
"Use the following CSV data:\n" +
"```csv\n" +
additionalData.uploadedCsv.content +
"\n```";
Comment on lines +55 to +58
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use template literals for better performance and readability in CSV content handling.

- "Use the following CSV data:\n" +
- "```csv\n" +
- additionalData.uploadedCsv.content +
- "\n```";
+ `Use the following CSV data:\n\`\`\`csv\n${additionalData.uploadedCsv.content}\n\`\`\``

content.push({
type: "text",
text: `${csvContent}\n\n${textMessage}`,
});
}

return content;
};

function createParser(
res: AsyncIterable<LlamaIndexResponse>,
data: StreamData,
opts?: ParserOptions,
opts?: DataParserOptions,
) {
const it = res[Symbol.asyncIterator]();
const trimStartOfStream = trimStartOfStreamHelper();

let sourceNodes: NodeWithScore<Metadata>[] | undefined;
return new ReadableStream<string>({
start() {
appendImageData(data, opts?.image_url);
appendImageData(data, opts?.imageUrl);
appendCsvData(data, opts?.uploadedCsv);
},
async pull(controller): Promise<void> {
const { value, done } = await it.next();
Expand Down Expand Up @@ -72,7 +115,7 @@ export function LlamaIndexStream(
data: StreamData,
opts?: {
callbacks?: AIStreamCallbacksAndOptions;
parserOptions?: ParserOptions;
parserOptions?: DataParserOptions;
},
): ReadableStream<Uint8Array> {
return createParser(response, data, opts?.parserOptions)
Expand Down
23 changes: 23 additions & 0 deletions templates/types/streaming/express/src/controllers/stream-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ export function appendToolData(
});
}

export function createStreamTimeout(stream: StreamData) {
const timeout = Number(process.env.STREAM_TIMEOUT ?? 1000 * 60 * 5); // default to 5 minutes
const t = setTimeout(() => {
appendEventData(stream, `Stream timed out after ${timeout / 1000} seconds`);
stream.close();
}, timeout);
return t;
}
Comment on lines +85 to +92
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Define the default timeout value as a constant for better readability and maintainability.

+ const DEFAULT_TIMEOUT = 1000 * 60 * 5; // 5 minutes
  const timeout = Number(process.env.STREAM_TIMEOUT ?? DEFAULT_TIMEOUT);

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
export function createStreamTimeout(stream: StreamData) {
const timeout = Number(process.env.STREAM_TIMEOUT ?? 1000 * 60 * 5); // default to 5 minutes
const t = setTimeout(() => {
appendEventData(stream, `Stream timed out after ${timeout / 1000} seconds`);
stream.close();
}, timeout);
return t;
}
export function createStreamTimeout(stream: StreamData) {
const DEFAULT_TIMEOUT = 1000 * 60 * 5; // 5 minutes
const timeout = Number(process.env.STREAM_TIMEOUT ?? DEFAULT_TIMEOUT);
const t = setTimeout(() => {
appendEventData(stream, `Stream timed out after ${timeout / 1000} seconds`);
stream.close();
}, timeout);
return t;
}


export function createCallbackManager(stream: StreamData) {
const callbackManager = new CallbackManager();

Expand Down Expand Up @@ -112,3 +121,17 @@ export function createCallbackManager(stream: StreamData) {

return callbackManager;
}

export type UploadedCsv = {
content: string;
filename: string;
filesize: number;
};

export function appendCsvData(data: StreamData, uploadedCsv?: UploadedCsv) {
if (!uploadedCsv) return;
data.appendMessageAnnotation({
type: "csv",
data: uploadedCsv,
});
}
55 changes: 49 additions & 6 deletions templates/types/streaming/nextjs/app/api/chat/llamaindex-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,78 @@ import {
type AIStreamCallbacksAndOptions,
} from "ai";
import {
MessageContent,
Metadata,
NodeWithScore,
Response,
ToolCallLLMMessageOptions,
} from "llamaindex";

import { AgentStreamChatResponse } from "llamaindex/agent/base";
import { appendImageData, appendSourceData } from "./stream-helper";
import {
UploadedCsv,
appendCsvData,
appendImageData,
appendSourceData,
} from "./stream-helper";

type LlamaIndexResponse =
| AgentStreamChatResponse<ToolCallLLMMessageOptions>
| Response;

type ParserOptions = {
image_url?: string;
export type DataParserOptions = {
imageUrl?: string;
uploadedCsv?: UploadedCsv;
};

export const convertMessageContent = (
textMessage: string,
additionalData?: DataParserOptions,
): MessageContent => {
if (!additionalData) return textMessage;
const content: MessageContent = [
{
type: "text",
text: textMessage,
},
];
if (additionalData?.imageUrl) {
content.push({
type: "image_url",
image_url: {
url: additionalData?.imageUrl,
},
});
}

if (additionalData?.uploadedCsv) {
const csvContent =
"Use the following CSV data:\n" +
"```csv\n" +
additionalData.uploadedCsv.content +
"\n```";
Comment on lines +55 to +58
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use template literals for better performance and readability in CSV content handling.

- "Use the following CSV data:\n" +
- "```csv\n" +
- additionalData.uploadedCsv.content +
- "\n```";
+ `Use the following CSV data:\n\`\`\`csv\n${additionalData.uploadedCsv.content}\n\`\`\``

content.push({
type: "text",
text: `${csvContent}\n\n${textMessage}`,
});
}

return content;
};

function createParser(
res: AsyncIterable<LlamaIndexResponse>,
data: StreamData,
opts?: ParserOptions,
opts?: DataParserOptions,
) {
const it = res[Symbol.asyncIterator]();
const trimStartOfStream = trimStartOfStreamHelper();

let sourceNodes: NodeWithScore<Metadata>[] | undefined;
return new ReadableStream<string>({
start() {
appendImageData(data, opts?.image_url);
appendImageData(data, opts?.imageUrl);
appendCsvData(data, opts?.uploadedCsv);
},
async pull(controller): Promise<void> {
const { value, done } = await it.next();
Expand Down Expand Up @@ -72,7 +115,7 @@ export function LlamaIndexStream(
data: StreamData,
opts?: {
callbacks?: AIStreamCallbacksAndOptions;
parserOptions?: ParserOptions;
parserOptions?: DataParserOptions;
},
): ReadableStream<Uint8Array> {
return createParser(response, data, opts?.parserOptions)
Expand Down
Loading
Loading