Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremyphilemon committed Dec 5, 2024
1 parent b74c077 commit d49cc6e
Show file tree
Hide file tree
Showing 11 changed files with 193 additions and 151 deletions.
14 changes: 7 additions & 7 deletions app/(chat)/actions.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
"use server";
'use server';

import { type CoreUserMessage, generateText, Message } from "ai";
import { cookies } from "next/headers";
import { type CoreUserMessage, generateText, Message } from 'ai';
import { cookies } from 'next/headers';

import { customModel } from "@/lib/ai";
import { customModel } from '@/lib/ai';
import {
deleteMessagesByChatIdAfterTimestamp,
getMessageById,
updateMessageContentById,
} from "@/lib/db/queries";
} from '@/lib/db/queries';

export async function saveModelId(model: string) {
const cookieStore = await cookies();
cookieStore.set("model-id", model);
cookieStore.set('model-id', model);
}

export async function generateTitleFromUserMessage({
Expand All @@ -21,7 +21,7 @@ export async function generateTitleFromUserMessage({
message: CoreUserMessage;
}) {
const { text: title } = await generateText({
model: customModel("gpt-4o-mini"),
model: customModel('gpt-4o-mini'),
system: `\n
- you will generate a short title based on the first message a user begins a conversation with
- ensure it is not more than 80 characters long
Expand Down
9 changes: 8 additions & 1 deletion app/(chat)/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,14 +81,21 @@ export async function POST(request: Request) {
await saveChat({ id, userId: session.user.id, title });
}

const userMessageId = generateUUID();

await saveMessages({
messages: [
{ ...userMessage, id: generateUUID(), createdAt: new Date(), chatId: id },
{ ...userMessage, id: userMessageId, createdAt: new Date(), chatId: id },
],
});

const streamingData = new StreamData();

streamingData.append({
type: 'user-message-id',
content: userMessageId,
});

const result = streamText({
model: customModel(model.apiIdentifier),
system: systemPrompt,
Expand Down
38 changes: 19 additions & 19 deletions components/chat.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
"use client";
'use client';

import type { Attachment, Message } from "ai";
import { useChat } from "ai/react";
import { AnimatePresence } from "framer-motion";
import { useState } from "react";
import useSWR, { useSWRConfig } from "swr";
import { useWindowSize } from "usehooks-ts";
import type { Attachment, Message } from 'ai';
import { useChat } from 'ai/react';
import { AnimatePresence } from 'framer-motion';
import { useEffect, useState } from 'react';
import useSWR, { useSWRConfig } from 'swr';
import { useWindowSize } from 'usehooks-ts';

import { ChatHeader } from "@/components/chat-header";
import type { Vote } from "@/lib/db/schema";
import { fetcher } from "@/lib/utils";
import { ChatHeader } from '@/components/chat-header';
import type { Vote } from '@/lib/db/schema';
import { fetcher } from '@/lib/utils';

import { Block, type UIBlock } from "./block";
import { BlockStreamHandler } from "./block-stream-handler";
import { MultimodalInput } from "./multimodal-input";
import { Messages } from "./messages";
import { Block, type UIBlock } from './block';
import { BlockStreamHandler } from './block-stream-handler';
import { MultimodalInput } from './multimodal-input';
import { Messages } from './messages';

export function Chat({
id,
Expand Down Expand Up @@ -43,18 +43,18 @@ export function Chat({
body: { id, modelId: selectedModelId },
initialMessages,
onFinish: () => {
mutate("/api/history");
mutate('/api/history');
},
});

const { width: windowWidth = 1920, height: windowHeight = 1080 } =
useWindowSize();

const [block, setBlock] = useState<UIBlock>({
documentId: "init",
content: "",
title: "",
status: "idle",
documentId: 'init',
content: '',
title: '',
status: 'idle',
isVisible: false,
boundingBox: {
top: windowHeight / 4,
Expand Down
46 changes: 23 additions & 23 deletions components/message-actions.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import type { Message } from "ai";
import { toast } from "sonner";
import { useSWRConfig } from "swr";
import { useCopyToClipboard } from "usehooks-ts";
import type { Message } from 'ai';
import { toast } from 'sonner';
import { useSWRConfig } from 'swr';
import { useCopyToClipboard } from 'usehooks-ts';

import type { Vote } from "@/lib/db/schema";
import { getMessageIdFromAnnotations } from "@/lib/utils";
import type { Vote } from '@/lib/db/schema';
import { getMessageIdFromAnnotations } from '@/lib/utils';

import { CopyIcon, ThumbDownIcon, ThumbUpIcon } from "./icons";
import { Button } from "./ui/button";
import { CopyIcon, ThumbDownIcon, ThumbUpIcon } from './icons';
import { Button } from './ui/button';
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "./ui/tooltip";
} from './ui/tooltip';

export function MessageActions({
chatId,
Expand All @@ -30,7 +30,7 @@ export function MessageActions({
const [_, copyToClipboard] = useCopyToClipboard();

if (isLoading) return null;
if (message.role === "user") return null;
if (message.role === 'user') return null;
if (message.toolInvocations && message.toolInvocations.length > 0)
return null;

Expand All @@ -44,7 +44,7 @@ export function MessageActions({
variant="outline"
onClick={async () => {
await copyToClipboard(message.content as string);
toast.success("Copied to clipboard!");
toast.success('Copied to clipboard!');
}}
>
<CopyIcon />
Expand All @@ -62,17 +62,17 @@ export function MessageActions({
onClick={async () => {
const messageId = getMessageIdFromAnnotations(message);

const upvote = fetch("/api/vote", {
method: "PATCH",
const upvote = fetch('/api/vote', {
method: 'PATCH',
body: JSON.stringify({
chatId,
messageId,
type: "up",
type: 'up',
}),
});

toast.promise(upvote, {
loading: "Upvoting Response...",
loading: 'Upvoting Response...',
success: () => {
mutate<Array<Vote>>(
`/api/vote?chatId=${chatId}`,
Expand All @@ -95,9 +95,9 @@ export function MessageActions({
{ revalidate: false },
);

return "Upvoted Response!";
return 'Upvoted Response!';
},
error: "Failed to upvote response.",
error: 'Failed to upvote response.',
});
}}
>
Expand All @@ -116,17 +116,17 @@ export function MessageActions({
onClick={async () => {
const messageId = getMessageIdFromAnnotations(message);

const downvote = fetch("/api/vote", {
method: "PATCH",
const downvote = fetch('/api/vote', {
method: 'PATCH',
body: JSON.stringify({
chatId,
messageId,
type: "down",
type: 'down',
}),
});

toast.promise(downvote, {
loading: "Downvoting Response...",
loading: 'Downvoting Response...',
success: () => {
mutate<Array<Vote>>(
`/api/vote?chatId=${chatId}`,
Expand All @@ -149,9 +149,9 @@ export function MessageActions({
{ revalidate: false },
);

return "Downvoted Response!";
return 'Downvoted Response!';
},
error: "Failed to downvote response.",
error: 'Failed to downvote response.',
});
}}
>
Expand Down
38 changes: 23 additions & 15 deletions components/message-editor.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
"use client";
'use client';

import { ChatRequestOptions, Message } from "ai";
import { Button } from "./ui/button";
import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
import { Textarea } from "./ui/textarea";
import { deleteTrailingMessages } from "@/app/(chat)/actions";
import { ChatRequestOptions, Message } from 'ai';
import { Button } from './ui/button';
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react';
import { Textarea } from './ui/textarea';
import { deleteTrailingMessages } from '@/app/(chat)/actions';
import { toast } from 'sonner';
import { useUserMessageId } from '@/hooks/use-user-message-id';

export type MessageEditorProps = {
chatId: string;
message: Message;
setMode: Dispatch<SetStateAction<"view" | "edit">>;
setMode: Dispatch<SetStateAction<'view' | 'edit'>>;
setMessages: (
messages: Message[] | ((messages: Message[]) => Message[]),
) => void;
Expand All @@ -19,12 +20,13 @@ export type MessageEditorProps = {
};

export function MessageEditor({
chatId,
message,
setMode,
setMessages,
reload,
}: MessageEditorProps) {
const { userMessageIdFromServer } = useUserMessageId();

const [draftContent, setDraftContent] = useState<string>(message.content);
const textareaRef = useRef<HTMLTextAreaElement>(null);

Expand All @@ -36,7 +38,7 @@ export function MessageEditor({

const adjustHeight = () => {
if (textareaRef.current) {
textareaRef.current.style.height = "auto";
textareaRef.current.style.height = 'auto';
textareaRef.current.style.height = `${textareaRef.current.scrollHeight + 2}px`;
}
};
Expand All @@ -50,7 +52,7 @@ export function MessageEditor({
<div className="flex flex-col gap-2 w-full">
<Textarea
ref={textareaRef}
className="bg-transparent outline-none overflow-hidden resize-none text-base rounded-xl w-full"
className="bg-transparent outline-none overflow-hidden resize-none !text-base rounded-xl w-full"
value={draftContent}
onChange={handleInput}
/>
Expand All @@ -60,7 +62,7 @@ export function MessageEditor({
variant="outline"
className="h-fit py-2 px-3"
onClick={() => {
setMode("view");
setMode('view');
}}
>
Cancel
Expand All @@ -69,8 +71,15 @@ export function MessageEditor({
variant="default"
className="h-fit py-2 px-3"
onClick={async () => {
const messageId = userMessageIdFromServer ?? message.id;

if (!messageId) {
toast.error('Something went wrong, please try again!');
return;
}

await deleteTrailingMessages({
id: message.id,
id: messageId,
});

setMessages((messages) => {
Expand All @@ -88,8 +97,7 @@ export function MessageEditor({
return messages;
});

setMode("view");

setMode('view');
reload();
}}
>
Expand Down
Loading

0 comments on commit d49cc6e

Please sign in to comment.