Skip to content

Commit

Permalink
created message list route and connect , run route
Browse files Browse the repository at this point in the history
Rohittomar01 committed Apr 25, 2024
1 parent 45e32b1 commit 4215d48
Showing 8 changed files with 285 additions and 79 deletions.
36 changes: 36 additions & 0 deletions src/app/api/assistantRun/createRun/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { NextRequest } from "next/server";
import OpenAI from "openai";
import { NextResponse } from "next/server";
import { env } from "@/app/env.mjs";

export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const threadId = searchParams.get("threadId");
const assistantId = searchParams.get("assistantId");

if (!threadId)
return NextResponse.json(
{ error: "No thread id provided" },
{ status: 400 },
);
if (!assistantId)
return NextResponse.json(
{ error: "No assistant id provided" },
{ status: 400 },
);

const openai = new OpenAI({ apiKey: env.OPEN_AI_API_KEY });

try {
const run = await openai.beta.threads.runs.create(threadId, {
assistant_id: assistantId,
});

console.log({ run: run });

return NextResponse.json({ run: run });
} catch (e) {
console.log(e);
return NextResponse.json({ error: e });
}
}
17 changes: 17 additions & 0 deletions src/app/api/assistantThread/createThread/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import OpenAI from "openai";
import { NextResponse } from "next/server";
import { env } from "@/app/env.mjs";

export async function GET() {
const openai = new OpenAI({ apiKey: env.OPEN_AI_API_KEY });

try {
const thread = await openai.beta.threads.create();
console.log(thread);

return NextResponse.json({ thread: thread });
} catch (e) {
console.log(e);
return NextResponse.json({ error: e });
}
}
27 changes: 27 additions & 0 deletions src/app/api/messagesThread/createMessages/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { NextRequest } from "next/server";
import OpenAI from "openai";
import { NextResponse } from "next/server";
import { env } from "@/app/env.mjs";

export async function POST(req: NextRequest) {
const { message, threadId } = await req.json();

if (!threadId || !message)
return NextResponse.json({ error: "Invalid message" }, { status: 400 });

const openai = new OpenAI({ apiKey: env.OPEN_AI_API_KEY });

try {
const threadMessage = await openai.beta.threads.messages.create(threadId, {
role: "user",
content: message,
});

console.log("threadMessage", threadMessage);

return NextResponse.json({ status: 200, message: threadMessage });
} catch (e) {
console.log(e);
return NextResponse.json({ status: 500, error: e });
}
}
22 changes: 22 additions & 0 deletions src/app/api/messagesThread/messagesList/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import OpenAI from "openai";
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { env } from "@/app/env.mjs";

const openai = new OpenAI({ apiKey: env.OPEN_AI_API_KEY });

export async function POST(req: NextRequest) {
try {
const { threadId } = await req.json(); // Ensure threadId is being sent in the request body
const threadMessages = await openai.beta.threads.messages.list(threadId);

console.log("Thread Messages:", threadMessages.data);
return NextResponse.json({
status: 200,
threadMessages: threadMessages.data,
});
} catch (e) {
console.log("Error:", e);
return NextResponse.json({ status: 500, error: e });
}
}
20 changes: 20 additions & 0 deletions src/components/chat.tsx
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ import { getUserIdList } from "./chatusersavatars";
import { useDropzone } from "react-dropzone";
import { X } from "lucide-react";
import { useImageState } from "@/store/tlDrawImage";
import { useAssistantState } from "@/store/assistant";

interface ChatProps {
orgId: string;
@@ -40,6 +41,7 @@ export default function Chat(props: ChatProps) {
settldrawImageUrl,
onClickOpenChatSheet,
} = useImageState();
const { threadId } = useAssistantState();
const [choosenAI, setChoosenAI] = useState<AIType>("universal");
const [isChatCompleted, setIsChatCompleted] = useState<boolean>(false);
const [calculatedMessages, setCalculatedMessages] = useState<Message[][]>([]);
@@ -83,6 +85,24 @@ export default function Chat(props: ChatProps) {
noKeyboard: true,
});

const threadMessagesFetch = async () => {
if (threadId) {
const responce = await fetch("/api/messagesThread/messagesList", {
method: "POST",
body: JSON.stringify({
threadId: threadId,
}),
});
const data = await responce.json();
console.log("responce", data);
}
};
useEffect(() => {
if (props.type === "rag") {
threadMessagesFetch();
}
}, [threadId]);

const chatFetcher = async () => {
const res = await axios.get(`/api/chats/${props.chatId}`);
const chats = res.data.chats;
201 changes: 125 additions & 76 deletions src/components/inputBar.tsx
Original file line number Diff line number Diff line change
@@ -23,11 +23,12 @@ import { Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { usePresence } from "ably/react";
import { useQueryClient } from "@tanstack/react-query";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import z from "zod";
import { toast } from "./ui/use-toast";
import usePreferences from "@/store/userPreferences";
import { useImageState } from "@/store/tlDrawImage";
import { useAssistantState } from "@/store/assistant";
import axios from "axios";
const isValidImageType = (value: string) =>
/^image\/(jpeg|png|jpg|webp)$/.test(value);

@@ -96,6 +97,7 @@ const InputBar = (props: InputBarProps) => {
settldrawImageUrl,
onClickOpenChatSheet,
} = useImageState();
const { threadId, setThreadId } = useAssistantState();
const [isAudioWaveVisible, setIsAudioWaveVisible] = useState<boolean>(false);
const [isRecording, setIsRecording] = useState<boolean>(false);
const [isTranscribing, setIsTranscribing] = useState<boolean>(false);
@@ -137,6 +139,52 @@ const InputBar = (props: InputBarProps) => {
name: `${props.username},${props.userId}`,
audio: "",
};

if (props.chattype === "rag") {
props.setInput("");
if (threadId) {
const res = await fetch("/api/messagesThread/createMessages", {
method: "POST",
body: JSON.stringify({
message: props.value,
threadId: threadId,
}),
});
const data = await res.json();

console.log("res thread message", data);
console.log("user message", data.message.content[0].text.value);
// const responce = await fetch("/api/messagesThread/messagesList", {
// method: "POST",
// body: JSON.stringify({
// threadId: threadId
// })
// });
// console.log("responce", responce.json())
return;
} else {
const createThread = async () => {
const res = await axios.get(`/api/assistantThread/createThread`);
console.log("thread data", res.data.thread.id);
setThreadId(res.data.thread.id);
};
createThread();
if (threadId) {
const res = await fetch("/api/messagesThread/createMessages", {
method: "POST",
body: JSON.stringify({
message: props.value,
threadId: threadId,
}),
});
const data = await res.json();
console.log("else thread message", data);
console.log("else user message", data.message.content[0].text.value);
return;
}
}
}

if (props.dropZoneActive) {
setDisableInputs(true);
setIsRagLoading(true);
@@ -241,81 +289,82 @@ const InputBar = (props: InputBarProps) => {
return;
}

if (props.chattype === "rag") {
setIsRagLoading(true);
setDisableInputs(true);
props.setMessages([...props.messages, message]);
props.setInput("");
let content = "";
const id = nanoid();
const assistantMessage: Message = {
id,
role: "assistant",
content: "",
};
let message2 = "";
try {
await fetchEventSource(`/api/chatmodel/${props.chatId}}`, {
method: "POST",
credentials: "include",
body: JSON.stringify({
input: props.value,
messages: [...props.messages, message],
userId: props.userId,
orgId: props.orgId,
chattype: props.chattype,
enableStreaming: true,
}),
openWhenHidden: true,
async onopen(response) {
setDisableInputs(true);
console.log("events started");
},
async onclose() {
setDisableInputs(false);
setIsRagLoading(false);
console.log("event reading closed", message2);
fetch(`/api/updatedb/${props.chatId}`, {
method: "POST",
body: JSON.stringify({
messages: [
...props.messages,
message,
{
...assistantMessage,
content: content,
},
],
orgId: props.orgId,
usreId: props.userId,
}),
}); // TODO: handle echoes is typing
return;
},
async onmessage(event: any) {
if (event.data !== "[END]" && event.event !== "function_call") {
message2 += event.data === "" ? `${event.data} \n` : event.data;
content += event.data === "" ? `${event.data} \n` : event.data;
props.setMessages([
...props.messages,
message,
{
...assistantMessage,
content: content,
},
]);
}
},
onerror(error: any) {
console.error("event reading error", error);
},
});
return;
} catch (error) {
console.error(error);
return;
}
}
// if (props.chattype === "rag") {
// setIsRagLoading(true);
// setDisableInputs(true);

// props.setMessages([...props.messages, message]);
// props.setInput("");
// let content = "";
// const id = nanoid();
// const assistantMessage: Message = {
// id,
// role: "assistant",
// content: "",
// };
// let message2 = "";
// try {
// await fetchEventSource(`/api/chatmodel/${props.chatId}}`, {
// method: "POST",
// credentials: "include",
// body: JSON.stringify({
// input: props.value,
// messages: [...props.messages, message],
// userId: props.userId,
// orgId: props.orgId,
// chattype: props.chattype,
// enableStreaming: true,
// }),
// openWhenHidden: true,
// async onopen(response) {
// setDisableInputs(true);
// console.log("events started");
// },
// async onclose() {
// setDisableInputs(false);
// setIsRagLoading(false);
// console.log("event reading closed", message2);
// fetch(`/api/updatedb/${props.chatId}`, {
// method: "POST",
// body: JSON.stringify({
// messages: [
// ...props.messages,
// message,
// {
// ...assistantMessage,
// content: content,
// },
// ],
// orgId: props.orgId,
// usreId: props.userId,
// }),
// }); // TODO: handle echoes is typing
// return;
// },
// async onmessage(event: any) {
// if (event.data !== "[END]" && event.event !== "function_call") {
// message2 += event.data === "" ? `${event.data} \n` : event.data;
// content += event.data === "" ? `${event.data} \n` : event.data;
// props.setMessages([
// ...props.messages,
// message,
// {
// ...assistantMessage,
// content: content,
// },
// ]);
// }
// },
// onerror(error: any) {
// console.error("event reading error", error);
// },
// });
// return;
// } catch (error) {
// console.error(error);
// return;
// }
// }
if (props.choosenAI === "universal") {
props.append(message as Message);
props.setInput("");
14 changes: 11 additions & 3 deletions src/components/startnewchatbutton.tsx
Original file line number Diff line number Diff line change
@@ -25,6 +25,7 @@ import {
FormMessage,
} from "@/components/ui/form";
import { MessageSquarePlus, PenTool, Database } from "lucide-react";
import { useAssistantState } from "@/store/assistant";

interface Props {
org_slug: string;
@@ -42,6 +43,7 @@ const Startnewchatbutton = (props: Props) => {
const [isBoardCreating, setIsBoardCreating] = useState(false);
const [showTitleInput, setShowTitleInput] = useState(false);
const [title, setTitle] = useState("");
const { setAssistantId, setThreadId } = useAssistantState();

const [isOpen, setIsOpen] = useState(false);
const router = useRouter();
@@ -69,15 +71,17 @@ const Startnewchatbutton = (props: Props) => {
body: JSON.stringify({ type: type, title: title }),
});
const data = await res.json();
console.log("got the data", data);
if (data.newChatId) {
if (data.newChatId && type === "rag") {
isLoding(false);
try {
const res = await fetch("/api/assistantApi/createAssistant", {
method: "GET",
});
const assistantData = await res.json();
if (assistantData.status === "ok") {
console.log("Got assistant data:", assistantData.id);
if (assistantData) {
setAssistantId(assistantData.id);
setThreadId("");
console.log("Got assistant data:", assistantData);
router.push(
`/dashboard/${props.org_slug}/chat/${Number(data.newChatId)}`,
@@ -90,6 +94,10 @@ const Startnewchatbutton = (props: Props) => {
console.error("Error fetching assistant data:", error);
// Handle fetch error
}
} else {
router.push(
`/dashboard/${props.org_slug}/chat/${Number(data.newChatId)}`,
);
}
};

27 changes: 27 additions & 0 deletions src/store/assistant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";

type AssistantState = {
assistantId: string;
threadId: string; // New state
setAssistantId: (id: string) => void;
setThreadId: (id: string) => void; // New setter function
};

export const useAssistantState = create<AssistantState>()(
persist(
(set, get) => ({
assistantId: "",
threadId: "", // Initialize to an empty string
setAssistantId: (id: string) => {
set({ assistantId: id });
},
setThreadId: (id: string) => {
set({ threadId: id });
},
}),
{
name: "assistant-state",
},
),
);

0 comments on commit 4215d48

Please sign in to comment.