Spaces:
Sleeping
Sleeping
KV template
Browse filesFiles changed (23)
- app/api/chat/route.ts+2-9
- app/api/upload/route.tsAdded+32
- app/chat/layout.tsxAdded+27
- app/chat/page.tsx+1-21
- app/layout.tsx+1
- app/page.tsx+15-7
- app/project/[projectId]/page.tsx+1-1
- app/project/layout.tsx+2-2
- components/Header.tsx+2-2
- components/chat-sidebar/ChatCard.tsxAdded+29
- components/chat-sidebar/ChatListSidebar.tsxAdded+16
- components/chat/ImageSelector.tsxAdded+57
- components/chat/index.tsx+8-4
- components/sidebar/ProjectCard.tsx → components/project-sidebar/ProjectCard.tsxRenamed
- components/sidebar/ProjectListSideBar.tsx → components/project-sidebar/ProjectListSideBar.tsxRenamed
- components/ui/Icons.tsx+1-1
- app/project/loading.tsx → components/ui/Loading.tsxRenamed+1-1
- lib/fetch/index.ts+9-21
- lib/kv/chat.tsAdded+69
- lib/types.ts-2
- lib/utils.ts+30-29
- package.json+2-1
- pnpm-lock.yaml
7 unmodified lines8910111213146 unmodified lines2122232425262 unmodified lines29303132333435363738394041427 unmodified linesChatCompletionContentPartImage,} from 'openai/resources';import { MessageWithSelectedDataset } from '../../../lib/types';import { postAgentChat } from '@/lib/fetch';export const runtime = 'edge';6 unmodified linesconst { messages } = json as {messages: MessageWithSelectedDataset[];};const session = await auth();if (!session?.user?.email) {2 unmodified lines});}// const lastMessage = messages[messages.length - 1];// const firstMessage = messages[0];// const resp = await postAgentChat({// input: lastMessage.content,// image: firstMessage.dataset?.[0]?.url,// });const formattedMessage: ChatCompletionMessageParam[] = messages.map(message => {const { dataset, ...rest } = message;7 unmodified lines8910111213146 unmodified lines212223242526272 unmodified lines3031323334357 unmodified linesChatCompletionContentPartImage,} from 'openai/resources';import { MessageWithSelectedDataset } from '../../../lib/types';// import { postAgentChat } from '@/lib/fetch';export const runtime = 'edge';6 unmodified linesconst { messages } = json as {messages: MessageWithSelectedDataset[];};console.log('[Ming] ~ POST ~ messages:', messages);const session = await auth();if (!session?.user?.email) {2 unmodified lines});}const formattedMessage: ChatCompletionMessageParam[] = messages.map(message => {const { dataset, ...rest } = message;
1234567891011121314151617181920212223242526272829303132import { auth } from '@/auth';import { nanoid } from '@/lib/utils';import { kv } from '@vercel/kv';import { format } from 'date-fns';
export async function POST(req: Request) { const session = await auth(); console.log('[Ming] ~ POST ~ session:', session); const email = session?.user?.email; if (!email) { return new Response('Unauthorized', { status: 401, }); }
const json = await req.json(); console.log('[Ming] ~ POST ~ json:', json);
const id = nanoid();
await kv.hmset(`chat:${id}`, json); await kv.zadd(`user:chat:${email}`, { score: Date.now(), member: `chat:${id}`, }); await kv.zadd('user:chat:all', { score: Date.now(), member: `chat:${id}`, });
return 'success';}123456789101112131415161718192021222324252627import ChatSidebarList from '@/components/chat-sidebar/ChatListSidebar';import Loading from '@/components/ui/Loading';import { Suspense } from 'react';
interface ChatLayoutProps { children: React.ReactNode;}
export default async function Layout({ children }: ChatLayoutProps) { return ( <div className="relative flex h-[calc(100vh_-_theme(spacing.16))] overflow-hidden"> <div data-state="open" className="peer absolute inset-y-0 z-30 hidden border-r bg-muted duration-300 ease-in-out translate-x-0 lg:flex lg:w-[250px] xl:w-[300px] h-full flex-col dark:bg-zinc-950 overflow-auto py-2" > <Suspense fallback={<Loading />}> <ChatSidebarList /> </Suspense> </div> <Suspense fallback={<Loading />}> <div className="group w-full overflow-auto pl-0 animate-in duration-300 ease-in-out peer-[[data-state=open]]:lg:pl-[250px] peer-[[data-state=open]]:xl:pl-[300px]"> {children} </div> </Suspense> </div> );}123456789101112131415161718192021222324252627'use client';import { nanoid } from '@/lib/utils';import { Chat } from '@/components/chat';import { ThemeToggle } from '../../components/ThemeToggle';import { useAtomValue } from 'jotai';import { datasetAtom } from '../../state';import { EmptyScreen } from '../../components/chat/EmptyScreen';export default function Page() {const id = nanoid();const dataset = useAtomValue(datasetAtom);if (!dataset.length)return (<div className="pb-[150px] pt-4 md:pt-10 h-full"><EmptyScreen /></div>);return (<><Chat id={id} /><ThemeToggle /></>);}1234567import { nanoid } from '@/lib/utils';import { Chat } from '@/components/chat';export default function Page() {const id = nanoid();return <Chat id={id} />;}
6 unmodified lines7891011126 unmodified linesimport { TailwindIndicator } from '@/components/TailwindIndicator';import { Providers } from '@/components/Providers';import { Header } from '@/components/Header';export const metadata = {metadataBase: new URL(`https://${process.env.VERCEL_URL}`),6 unmodified lines789101112136 unmodified linesimport { TailwindIndicator } from '@/components/TailwindIndicator';import { Providers } from '@/components/Providers';import { Header } from '@/components/Header';import { ThemeToggle } from '@/components/ThemeToggle';export const metadata = {metadataBase: new URL(`https://${process.env.VERCEL_URL}`),
123456789'use client';export default function Page() {return (<div className="flex flex-col h-[calc(100vh-theme(spacing.16))] items-center justify-center py-10 space-y-2">Welcome to Insight Playground</div>);}1234567891011121314151617import { auth } from '@/auth';import { redirect } from 'next/navigation';export default async function Page() {const session = await auth();if (!session) {return null;}redirect('/chat');// return (// <div className="flex flex-col h-[calc(100vh-theme(spacing.16))] items-center justify-center py-10 space-y-2">// Welcome to Insight Playground// </div>// );}
1234567import MediaGrid from '@/components/project/MediaGrid';import { fetchProjectMedia } from '@/lib/fetch';import { Suspense } from 'react';import Loading from '../loading';import Chat from '@/components/project/Chat';interface PageProps {1234567import MediaGrid from '@/components/project/MediaGrid';import { fetchProjectMedia } from '@/lib/fetch';import { Suspense } from 'react';import Loading from '../../../components/ui/Loading';import Chat from '@/components/project/Chat';interface PageProps {
123456import ProjectListSideBar from '@/components/sidebar/ProjectListSideBar';import { Suspense } from 'react';import Loading from './loading';interface ChatLayoutProps {children: React.ReactNode;123456import ProjectListSideBar from '@/components/project-sidebar/ProjectListSideBar';import { Suspense } from 'react';import Loading from '@/components/ui/Loading';interface ChatLayoutProps {children: React.ReactNode;
14 unmodified lines15161718192021222314 unmodified linesreturn (<header className="sticky top-0 z-50 flex items-center justify-end w-full h-16 px-8 border-b shrink-0 bg-gradient-to-b from-background/10 via-background/50 to-background/80 backdrop-blur-xl"><Button variant="link" asChild className="mr-2"><Link href="/project">Projects</Link></Button><Button variant="link" asChild className="mr-2"><Link href="/chat">Chat</Link></Button>14 unmodified lines15161718192021222314 unmodified linesreturn (<header className="sticky top-0 z-50 flex items-center justify-end w-full h-16 px-8 border-b shrink-0 bg-gradient-to-b from-background/10 via-background/50 to-background/80 backdrop-blur-xl">{/* <Button variant="link" asChild className="mr-2"><Link href="/project">Projects</Link></Button> */}<Button variant="link" asChild className="mr-2"><Link href="/chat">Chat</Link></Button>
1234567891011121314151617181920212223242526272829'use client';
import Link from 'next/link';import { useParams } from 'next/navigation';import { cn } from '@/lib/utils';
export interface ChatCardProps { id: string; title: string;}
const ChatCard: React.FC<ChatCardProps> = ({ id, title }) => { const { chatId: chatIdFromParam } = useParams(); return ( <Link className={cn( 'p-4 m-2 bg-white l:h-[250px] rounded-xl shadow-md flex items-center border border-transparent hover:border-gray-500 transition-all cursor-pointer', chatIdFromParam === id && 'border-gray-500', )} href={`/chat/${id}`} > <div className="overflow-hidden"> <p className="text-sm font-medium text-black mb-1">{title}</p> </div> </Link> );};
export default ChatCard;12345678910111213141516import { getKVChats } from '@/lib/kv/chat';import ChatCard from './ChatCard';
export interface ChatSidebarListProps {}
export default async function ChatSidebarList({}: ChatSidebarListProps) { const chats = await getKVChats(); console.log('[Ming] ~ ChatSidebarList ~ chats:', chats); return ( <> {chats.map(chat => ( <ChatCard key={chat.id} id={chat.id} title={chat.title} /> ))} </> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import React from 'react';import Image from 'next/image';import useImageUpload from '../../lib/hooks/useImageUpload';import { fetcher } from '@/lib/utils';
export interface ImageSelectorProps {}
const examples = [ 'https://landing-lens-support.s3.us-east-2.amazonaws.com/vision-agent-examples/cereal-example.jpg', 'https://landing-lens-support.s3.us-east-2.amazonaws.com/vision-agent-examples/people-example.jpeg', 'https://landing-lens-support.s3.us-east-2.amazonaws.com/vision-agent-examples/house-exmaple.jpg', 'https://landing-lens-support.s3.us-east-2.amazonaws.com/vision-agent-examples/safari-example.png',];
const ImageSelector: React.FC<ImageSelectorProps> = () => { const { getRootProps, getInputProps } = useImageUpload(); return ( <div className="mx-auto max-w-2xl px-4"> <div className="rounded-lg border bg-background p-8"> <h1 className="mb-2 text-lg font-semibold">Welcome to Vision Agent</h1> <p>Lets start by choosing an image</p> <div {...getRootProps()} className="dropzone border-2 border-dashed border-gray-400 w-full h-64 flex items-center justify-center rounded-lg mt-4 cursor-pointer" > <input {...getInputProps()} /> <p className="text-gray-400 text-lg"> Drag or drop image here, or click to select images </p> </div> <p className="mt-4 mb-2"> You can also choose from below examples we provided </p> <div className="flex"> {examples.map((example, index) => ( <Image src={example} key={index} width={120} height={120} alt="example images" className="object-cover rounded mr-3 shadow-md hover:scale-105 cursor-pointer transition-transform" onClick={() => fetcher('/api/upload', { method: 'POST', body: JSON.stringify({ url: example }), }) } /> ))} </div> </div> </div> );};
export default ImageSelector;4 unmodified lines56789101112131415161718192021222324254 unmodified linesimport { ChatScrollAnchor } from '@/components/chat/ChatScrollAnchor';import ImageList from './ImageList';import useChatWithDataset from '../../lib/hooks/useChatWithDataset';export interface ChatProps extends React.ComponentProps<'div'> {id?: string;}export function Chat({ id, className }: ChatProps) {const { messages, append, reload, stop, isLoading, input, setInput } =useChatWithDataset();return (<><div className={cn('pb-[150px] pt-4 md:pt-10 h-full', className)}><div className="flex h-full"><div className="w-1/2 relative border-r-2 border-gray-300 overflow-auto"><ImageList /></div><div className="w-1/2 relative overflow-auto"><ChatList messages={messages} />4 unmodified lines5678910111213141516171819202122232425262728294 unmodified linesimport { ChatScrollAnchor } from '@/components/chat/ChatScrollAnchor';import ImageList from './ImageList';import useChatWithDataset from '../../lib/hooks/useChatWithDataset';import { useChat } from 'ai/react';import { Button } from '../ui/Button';import ImageSelector from './ImageSelector';export interface ChatProps extends React.ComponentProps<'div'> {id: string;}export function Chat({ id, className }: ChatProps) {const { messages, append, reload, stop, isLoading, input, setInput } =useChat();return (<><div className={cn('pb-[150px] pt-4 md:pt-10 h-full', className)}><div className="flex h-full"><div className="w-1/2 relative border-r border-gray-400 overflow-auto">{/* <ImageList /> */}<ImageSelector /></div><div className="w-1/2 relative overflow-auto"><ChatList messages={messages} />
510 unmodified lines511512513514515516517510 unmodified linesreturn (<svgaria-hidden="true"className="size-8 text-gray-200 animate-spin dark:text-gray-600 fill-blue-600"viewBox="0 0 100 101"fill="none"xmlns="http://www.w3.org/2000/svg"510 unmodified lines511512513514515516517510 unmodified linesreturn (<svgaria-hidden="true"className="size-8 text-gray-200 animate-spin dark:text-gray-600 fill-gray-600"viewBox="0 0 100 101"fill="none"xmlns="http://www.w3.org/2000/svg"
123456import { IconLoading } from '@/components/ui/Icons';export default async function Loading() {return (<div className="flex justify-center items-center size-full text-sm"><IconLoading />123456import { IconLoading } from '@/components/ui/Icons';export default function Loading() {return (<div className="flex justify-center items-center size-full text-sm"><IconLoading />
6 unmodified lines789101112134 unmodified lines18192021222324252627282930313233343527 unmodified lines6364656667686924 unmodified lines94959697989910016 unmodified lines1171181191201211221231241251261271281291301311321331341356 unmodified linesdata: T;}const apiBuilder = <Params extends object | void, Resp>(path: string,options?: {// default to GET4 unmodified lines) => {return async (params: Params): Promise<Resp> => {const session = await auth();if (!session?.user?.email) {throw new Response('Unauthorized', {status: 401,});}const adminEmail = session.user.email;const sessionUser = {id: uuidV5(adminEmail, uuidV5.URL),orgId: '-1024',email: adminEmail,username: adminEmail.split('@')[0],userRole: 'adminPortal',bucket: 'fake_bucket',};27 unmodified linesfetchParams.body = formData;}console.log('[Ming] ~ return ~ fetchParams:', fetchParams, url.toString());const res = await fetch(url.toString(), fetchParams);24 unmodified lines* 3. projects not containing media or only contain sample media* @author https://github.com/landing-ai/landing-platform/blob/mingrui-04-08-meaningful-project/packages/server-clef/src/main_app/controllers/admin/get_admin_meaningful_project_controller.ts*/export const fetchRecentProjectList = apiBuilder<void, ProjectBaseInfo[]>('api/admin/projects/recent',);16 unmodified lines* Randomly fetch 10 media from a given project* @author https://github.com/landing-ai/landing-platform/blob/mingrui-04-08-meaningful-project/packages/server-clef/src/main_app/controllers/admin/get_admin_meaningful_project_controller.ts*/export const fetchProjectMedia = apiBuilder<{ projectId: number },MediaDetails[]>('api/admin/project/media');/*** Call vision agent* @author https://github.com/landing-ai/public-rest-api/pull/36*/export const postAgentChat = apiBuilder<{ input: string; image: string },MediaDetails[]>('v1/agent/chat?agent_class=vision_agent', {method: 'POST',prefix: 'api.dev',});6 unmodified lines789101112134 unmodified lines1819202122232425262728293031323334353627 unmodified lines64656667686924 unmodified lines94959697989910016 unmodified lines1171181191201211221236 unmodified linesdata: T;}const clefApiBuilder = <Params extends object | void, Resp>(path: string,options?: {// default to GET4 unmodified lines) => {return async (params: Params): Promise<Resp> => {const session = await auth();const email = session?.user?.email;if (!email || !email.endsWith('@landing.ai')) {throw new Response('Unauthorized', {status: 401,});}const sessionUser = {id: uuidV5(email, uuidV5.URL),orgId: '-1024',email: email,username: email.split('@')[0],userRole: 'adminPortal',bucket: 'fake_bucket',};27 unmodified linesfetchParams.body = formData;}const res = await fetch(url.toString(), fetchParams);24 unmodified lines* 3. projects not containing media or only contain sample media* @author https://github.com/landing-ai/landing-platform/blob/mingrui-04-08-meaningful-project/packages/server-clef/src/main_app/controllers/admin/get_admin_meaningful_project_controller.ts*/export const fetchRecentProjectList = clefApiBuilder<void, ProjectBaseInfo[]>('api/admin/projects/recent',);16 unmodified lines* Randomly fetch 10 media from a given project* @author https://github.com/landing-ai/landing-platform/blob/mingrui-04-08-meaningful-project/packages/server-clef/src/main_app/controllers/admin/get_admin_meaningful_project_controller.ts*/export const fetchProjectMedia = clefApiBuilder<{ projectId: number },MediaDetails[]>('api/admin/project/media');
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869'use server';
import { revalidatePath } from 'next/cache';import { redirect } from 'next/navigation';import { kv } from '@vercel/kv';
import { auth } from '@/auth';import { type Chat } from '@/lib/types';
export async function getKVChats() { const session = await auth(); const email = session?.user?.email;
if (!email) { return []; }
try { const pipeline = kv.pipeline(); const chats: string[] = await kv.zrange(`user:chat:${email}`, 0, -1, { rev: true, });
for (const chat of chats) { pipeline.hgetall(chat); }
const results = await pipeline.exec();
return results as Chat[]; } catch (error) { return []; }}
export async function getKVChat(id: string, userId: string) { const chat = await kv.hgetall<Chat>(`chat:${id}`);
if (!chat || (userId && chat.userId !== userId)) { return null; }
return chat;}
export async function removeKVChat({ id, path }: { id: string; path: string }) { const session = await auth();
if (!session) { return { error: 'Unauthorized', }; }
//Convert uid to string for consistent comparison with session.user.id const uid = String(await kv.hget(`chat:${id}`, 'userId'));
if (uid !== session?.user?.id) { return { error: 'Unauthorized', }; }
await kv.del(`chat:${id}`); await kv.zrem(`user:chat:${session.user.id}`, `chat:${id}`);
revalidatePath('/'); return revalidatePath(path);}123452 unmodified lines891011121314import { type Message } from 'ai';import { CreateMessage } from 'ai/react/dist';export interface Chat extends Record<string, any> {id: string;2 unmodified linesuserId: string;path: string;messages: Message[];sharePath?: string;}export type ServerActionResult<Result> = Promise<12342 unmodified lines789101112import { type Message } from 'ai';export interface Chat extends Record<string, any> {id: string;2 unmodified linesuserId: string;path: string;messages: Message[];}export type ServerActionResult<Result> = Promise<
12345678910111213141516171819202122232425262728293031323334353637383940414243import { clsx, type ClassValue } from 'clsx'import { customAlphabet } from 'nanoid'import { twMerge } from 'tailwind-merge'export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs))}export const nanoid = customAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',7) // 7-character random stringexport async function fetcher<JSON = any>(input: RequestInfo,init?: RequestInit): Promise<JSON> {const res = await fetch(input, init)if (!res.ok) {const json = await res.json()if (json.error) {const error = new Error(json.error) as Error & {status: number}error.status = res.statusthrow error} else {throw new Error('An unexpected error occurred')}}return res.json()}export function formatDate(input: string | number | Date): string {const date = new Date(input)return date.toLocaleDateString('en-US', {month: 'long',day: 'numeric',year: 'numeric'})}1234567891011121314151617181920212223242526272829303132333435363738394041424344import { clsx, type ClassValue } from 'clsx';import { customAlphabet } from 'nanoid';import { twMerge } from 'tailwind-merge';export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs));}export const nanoid = customAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',7,); // 7-character random stringexport async function fetcher<JSON = any>(input: RequestInfo,init?: RequestInit,): Promise<JSON> {const res = await fetch(input, init);console.log('[Ming] ~ res:', res);if (!res.ok) {const json = await res.json();if (json.error) {const error = new Error(json.error) as Error & {status: number;};error.status = res.status;throw error;} else {throw new Error('An unexpected error occurred');}}return res.json();}export function formatDate(input: string | number | Date): string {const date = new Date(input);return date.toLocaleDateString('en-US', {month: 'long',day: 'numeric',year: 'numeric',});}
19 unmodified lines20212223242540 unmodified lines666768697019 unmodified lines"@radix-ui/react-slot": "^1.0.2","@radix-ui/react-switch": "^1.0.3","@radix-ui/react-tooltip": "^1.0.7","ai": "^2.2.31","class-variance-authority": "^0.7.0","clsx": "^2.1.0",40 unmodified lines"tailwindcss-animate": "^1.0.7","typescript": "^5.3.3"},"packageManager": "pnpm@8.6.3"}19 unmodified lines2021222324252640 unmodified lines676869707119 unmodified lines"@radix-ui/react-slot": "^1.0.2","@radix-ui/react-switch": "^1.0.3","@radix-ui/react-tooltip": "^1.0.7","@vercel/kv": "^1.0.1","ai": "^2.2.31","class-variance-authority": "^0.7.0","clsx": "^2.1.0",40 unmodified lines"tailwindcss-animate": "^1.0.7","typescript": "^5.3.3"},"packageManager": "pnpm@9.0.1"}
app/api/chat/route.ts+2-9
app/api/upload/route.tsAdded+32
app/chat/layout.tsxAdded+27
app/chat/page.tsx+1-21
app/layout.tsx+1
app/page.tsx+15-7
app/project/[projectId]/page.tsx+1-1
app/project/layout.tsx+2-2
components/Header.tsx+2-2
components/chat-sidebar/ChatCard.tsxAdded+29
components/chat-sidebar/ChatListSidebar.tsxAdded+16
components/chat/ImageSelector.tsxAdded+57
components/chat/index.tsx+8-4
components/sidebar/ProjectCard.tsx → components/project-sidebar/ProjectCard.tsxRenamed
components/sidebar/ProjectListSideBar.tsx → components/project-sidebar/ProjectListSideBar.tsxRenamed
components/ui/Icons.tsx+1-1
app/project/loading.tsx → components/ui/Loading.tsxRenamed+1-1
lib/fetch/index.ts+9-21
lib/kv/chat.tsAdded+69
lib/types.ts-2
lib/utils.ts+30-29
package.json+2-1
pnpm-lock.yaml