Skip to content
This repository has been archived by the owner on Sep 9, 2024. It is now read-only.

Co-Pilot: Stream Response and Vector Chunk Search Draft #176

Merged
merged 2 commits into from
Jul 23, 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
86 changes: 59 additions & 27 deletions packages/ocular-ui/components/chat/chat-helpers/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import router from "next/router"
import React from "react"
import { toast } from "sonner"
import { v4 as uuidv4 } from "uuid"
import { createReader,readStream } from '@/lib/stream';
import { da, ro } from "date-fns/locale"


export const handleChat = async (
Expand All @@ -26,11 +28,8 @@ export const handleChat = async (
setFirstTokenReceived: React.Dispatch<React.SetStateAction<boolean>>,
setChatMessages: React.Dispatch<React.SetStateAction<ChatMessage[]>>,
) => {
const requestBody = {
// chatSettings: payload.chatSettings,

// customModelId: provider === "custom" ? modelData.hostedId : ""
}


const response = await fetchChatResponse(
chat,
Expand All @@ -40,16 +39,6 @@ export const handleChat = async (
setIsGenerating,
setChatMessages
)


return await processResponse(
response,
// true,
cancelTokenSource,
setFirstTokenReceived,
setChatMessages,
// setToolInUse
)
}

export const fetchChatResponse = async (
Expand All @@ -60,18 +49,59 @@ export const fetchChatResponse = async (
setIsGenerating: React.Dispatch<React.SetStateAction<boolean>>,
setChatMessages: React.Dispatch<React.SetStateAction<ChatMessage[]>>
) => {
const response = await api.chats.sendMessage(chat.id,{message:content,stream:false},cancelTokenSource)
if (!response.data.ok) {
if (response.status === 404) {
toast.error(
"Failed To Chat",
)
}
const errorData = await response.data
toast.error(errorData.message)
setIsGenerating(false)
}
return response.data

let idx=0;
api.chats.sendMessage(chat.id,{message:content,stream:true},cancelTokenSource)
.then(async response => {
console.log("Streaming Copilot Response")
const reader = createReader(response.body);
const chunks = readStream(reader);
for await (const chunk of chunks) {
setChatMessages(prevChatMessages => {
const updatedMessages = [...prevChatMessages];
if (idx=== 0) {
updatedMessages.push({
message: {
chat_id: chunk.metadata?.chat_id,
content: chunk.choices[0].delta.content,
created_at: new Date(),
id: "123",
role: chunk.metadata.role,
updated_at: new Date(),
user_id: chunk.metadata.user_id
},
fileItems: []
});
idx++;
} else {
const lastMessage = updatedMessages[updatedMessages.length - 1];
lastMessage.message.content = chunk.choices[0].delta.content;
lastMessage.message.updated_at = new Date();
}
return updatedMessages;
});
}

// setChatMessages(prevChatMessages => [...prevChatMessages,
Copy link
Contributor

Choose a reason for hiding this comment

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

@Vivek-Lahole do we still need this too?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

no dont need that

// {
// message: {
// chat_id: data.metadata?.chat_id,
// content: data.choices[0].delta.content,
// created_at: new Date(),
// id: "123",
// role: data.metadata.role,
// updated_at: new Date(),
// user_id: data.metadata.user_id
// },
// fileItems: []
// }
// ]);

})
.catch(error => {
console.error(error);
setIsGenerating(false)
});
}

// lastChatMessage: ChatMessage,
Expand All @@ -85,7 +115,7 @@ export const processResponse = async (
let fullText = ""
let contentToAdd = ""


if (response) {

router.push(`/dashboard/chat/${response.message.chat_id}`)
Expand Down Expand Up @@ -127,3 +157,5 @@ export const handleCreateChat = async (

return createdChat.data.chat
}


37 changes: 27 additions & 10 deletions packages/ocular-ui/components/chat/chat-hooks/use-chat-handler.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { ApplicationContext } from "@/context/context"
import { buildFinalMessages } from "@/lib/build-prompt"
import { useRouter } from "next/navigation"
import { useContext, useEffect, useRef } from "react"
import axios from "axios";
Expand All @@ -8,6 +7,7 @@ import {
handleChat,
} from "../chat-helpers/index"


export const useChatHandler = () => {
const router = useRouter()

Expand Down Expand Up @@ -62,11 +62,13 @@ export const useChatHandler = () => {
// setIsFilePickerOpen(false)
// setNewMessageImages([])

const cancelTokenSource = axios.CancelToken.source();

const cancelTokenSource = axios.CancelToken.source();
setCancelTokenSource(cancelTokenSource);

let currentChat = selectedChat ? { ...selectedChat } : null



if (!currentChat) {
currentChat = await handleCreateChat(
Expand All @@ -80,14 +82,29 @@ export const useChatHandler = () => {

if (!currentChat) return

let generatedText = ""
generatedText = await handleChat(
currentChat,
messageContent,
cancelTokenSource,
setIsGenerating,
setFirstTokenReceived,
setChatMessages,
setChatMessages(prevChatMessages => [...prevChatMessages,
{
message: {
chat_id: currentChat?.id,
content: messageContent,
created_at: new Date(),
id: "123",
role: "user",
updated_at: new Date(),
user_id: currentChat?.user_id
},
fileItems: []
}
]);


await handleChat(
currentChat,
messageContent,
cancelTokenSource,
setIsGenerating,
setFirstTokenReceived,
setChatMessages,
)

setIsGenerating(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ export default function Search() {
.then(async response => {
console.log("Streaming Copilot 1")
setIsLoadingCopilot(false);

if (stream) {
const reader = createReader(response.body);
const chunks = readStream(reader);
Expand Down
2 changes: 1 addition & 1 deletion packages/ocular-ui/services/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export default {
console.log('controller', cancelToken);
const path = `/chat/${id}/message`;
console.log('path', data);
return ocularRequest('POST', path, data, false, cancelToken);
return ocularStreamingRequest('POST', path, data, true, cancelToken);
},
getMessages(id) {
const path = `/chat/${id}/messages`;
Expand Down
46 changes: 23 additions & 23 deletions packages/ocular/core-config-dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,35 +177,35 @@ module.exports = {
chunk_over_lap: 0,
},
},
// {
// resolve: PluginNameDefinitions.AZUREOPENAI,
// options: {
// open_ai_key: process.env.AZURE_OPEN_AI_KEY,
// open_ai_version: "2023-05-15",
// endpoint: process.env.AZURE_OPEN_AI_ENDPOINT,
// embedding_deployment_name:
// process.env.AZURE_OPEN_AI_EMBEDDER_DEPLOYMENT_NAME,
// embedding_model: process.env.AZURE_OPEN_AI_EMBEDDING_MODEL,
// chat_deployment_name: process.env.AZURE_OPEN_AI_CHAT_DEPLOYMENT_NAME,
// chat_model: process.env.AZURE_OPEN_AI_CHAT_MODEL,
// rate_limiter_opts: {
// requests: 1, // Number of Tokens
// interval: 1, // Interval in Seconds
// },
// },
// },
{
resolve: PluginNameDefinitions.OPENAI,
resolve: PluginNameDefinitions.AZUREOPENAI,
options: {
open_ai_key: process.env.OPEN_AI_KEY,
embedding_model: process.env.OPEN_AI_EMBEDDING_MODEL,
chat_model: process.env.OPEN_AI_CHAT_MODEL,
open_ai_key: process.env.AZURE_OPEN_AI_KEY,
open_ai_version: "2023-05-15",
endpoint: process.env.AZURE_OPEN_AI_ENDPOINT,
embedding_deployment_name:
process.env.AZURE_OPEN_AI_EMBEDDER_DEPLOYMENT_NAME,
embedding_model: process.env.AZURE_OPEN_AI_EMBEDDING_MODEL,
chat_deployment_name: process.env.AZURE_OPEN_AI_CHAT_DEPLOYMENT_NAME,
chat_model: process.env.AZURE_OPEN_AI_CHAT_MODEL,
rate_limiter_opts: {
requests: 1000000, // Number of Tokens
interval: 60, // Interval in Seconds
requests: 1, // Number of Tokens
interval: 1, // Interval in Seconds
},
},
},
// {
// resolve: PluginNameDefinitions.OPENAI,
// options: {
// open_ai_key: process.env.OPEN_AI_KEY,
// embedding_model: process.env.OPEN_AI_EMBEDDING_MODEL,
// chat_model: process.env.OPEN_AI_CHAT_MODEL,
// rate_limiter_opts: {
// requests: 1000000, // Number of Tokens
// interval: 60, // Interval in Seconds
// },
// },
// },
{
resolve: `qdrant-vector-search-service`,
options: {
Expand Down
8 changes: 6 additions & 2 deletions packages/ocular/src/api/routes/member/chat/create-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@ export default async (req, res) => {
try {
const { message } = validated;
const chatService = req.scope.resolve("chatService") as ChatService
const chatResponse = await chatService.chat(id, message, {})
return res.status(200).send(chatResponse)
const chatResponse = await chatService.chatWithStreaming(id, message, {})
for await (const chunk of chatResponse) {
res.write(JSON.stringify(chunk) + "\n");
}
res.status(200);
res.end();
} catch (_error: unknown) {
console.error(_error)
return res.status(500).send("Error: Failed to execute Chat");
Expand Down
Loading