Skip to content

Commit

Permalink
fix: bug related to chat history or continuity chat
Browse files Browse the repository at this point in the history
  • Loading branch information
mrevanzak committed Jun 29, 2024
1 parent 7c82d6c commit 238390b
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 12 deletions.
1 change: 1 addition & 0 deletions apps/web/src/app/(app)/@user/card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export function ChatCard() {
onFinish={() => utils.chat.get.invalidate()}
initialMessages={initialMessages}
placeholder={"/ : " + t("chooseTopic")}
id={data?.id}
/>
</CardContent>
<CardFooter>
Expand Down
20 changes: 14 additions & 6 deletions apps/web/src/app/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { getLocale } from "next-intl/server";
import { z } from "zod";
import { fromZodError } from "zod-validation-error";

import { generateId } from "@tanya.in/ui";

// TODO: Remove this when backend has domain
// export const runtime = "edge";

Expand All @@ -25,16 +27,16 @@ export async function POST(req: Request) {
return new Response("Unauthorized", { status: 401 });
}

const { success } = await ratelimit.limit(session.user.id);
if (!success) return new Response("Too many request", { status: 429 });
const limiter = await ratelimit.limit(session.user.id);
if (!limiter.success)
return new Response("Too many request", { status: 429 });

const body = z
.object({
chatId: z.string(),
messages: z
.object({
id: z.string(),
role: z.enum(["user", "assistant"] as const),
content: z.string(),
})
.array(),
Expand All @@ -45,7 +47,11 @@ export async function POST(req: Request) {
const error = fromZodError(body.error).toString();
return new Response(error, { status: 400 });
}
const lastMessage = body.data.messages.pop()?.content;
const lastMessage = body.data.messages.pop();

if (!lastMessage) {
return new Response("No message", { status: 400 });
}

const isTesting = await get("testing");
const res = await fetch(
Expand All @@ -58,7 +64,7 @@ export async function POST(req: Request) {
},
body: JSON.stringify({
id: body.data.chatId,
question: lastMessage,
question: lastMessage.content,
isBahasa: (await getLocale()) === "id",
}),
},
Expand All @@ -83,8 +89,9 @@ export async function POST(req: Request) {
.returning({ id: chats.id });

await db.insert(messages).values({
id: lastMessage.id,
chatId: chatId[0]?.id ?? body.data.chatId,
content: lastMessage ?? "",
content: lastMessage.content,
});

const reader = res.body.getReader();
Expand All @@ -95,6 +102,7 @@ export async function POST(req: Request) {
const { done, value } = await reader.read();
if (done) {
await db.insert(messages).values({
id: generateId(),
chatId: chatId[0]?.id ?? body.data.chatId,
content: data,
});
Expand Down
6 changes: 5 additions & 1 deletion apps/web/src/server/api/routers/chat/chat.procedure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ export const chatRouter = createTRPCRouter({
return await ctx.db.query.chats.findFirst({
where: (chat, { eq }) => eq(chat.id, input.id),
with: {
messages: true,
messages: {
columns: {
chatId: false,
},
},
},
});
}),
Expand Down
4 changes: 1 addition & 3 deletions apps/web/src/server/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,7 @@ export const chatRelations = relations(chats, ({ many }) => ({
}));

export const messages = createTable("message", {
id: text("id")
.primaryKey()
.$defaultFn(() => crypto.randomUUID()),
id: text("id").primaryKey(),
content: text("content").notNull(),
createdAt: timestamp("created_at", { mode: "date" }).defaultNow(),
chatId: uuid("chat_id")
Expand Down
4 changes: 3 additions & 1 deletion packages/ui/src/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ export function Chat({
onFinish,
initialMessages,
placeholder,
id,
}: UseChatOptions & { placeholder?: string }) {
const chatId = React.useMemo(() => crypto.randomUUID(), []);
const chatId = React.useMemo(() => (id ? id : crypto.randomUUID()), [id]);

const {
messages,
Expand All @@ -62,6 +63,7 @@ export function Chat({
sendExtraMessageFields: true,
onFinish,
initialMessages,
id,
});
const chatContainerRef = useChatScroll(messages);

Expand Down
3 changes: 2 additions & 1 deletion packages/ui/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { Message } from "ai";
import { NextUIProvider } from "@nextui-org/system";
import { generateId } from "ai";
import { cx } from "class-variance-authority";
import { twMerge } from "tailwind-merge";

const cn = (...inputs: Parameters<typeof cx>) => twMerge(cx(inputs));

export { cn, NextUIProvider, type Message };
export { cn, NextUIProvider, type Message, generateId };

0 comments on commit 238390b

Please sign in to comment.