feat: ai course chat

feat/chat
Arik Chakma 3 weeks ago
parent 7d7cec3f4a
commit b897b97406
  1. 10
      src/components/GenerateCourse/AICourseContent.tsx
  2. 323
      src/components/GenerateCourse/AICourseLesson.tsx
  3. 407
      src/components/GenerateCourse/AICourseLessonChat.tsx

@ -392,6 +392,9 @@ export function AICourseContent(props: AICourseContentProps) {
className={cn(
'flex-1 overflow-y-scroll p-6 transition-all duration-200 ease-in-out max-lg:p-3',
sidebarOpen ? 'lg:ml-0' : '',
viewMode === 'module'
? 'flex flex-col overflow-hidden p-0 max-lg:p-0'
: '',
)}
key={`${courseSlug}-${viewMode}`}
>
@ -442,7 +445,12 @@ export function AICourseContent(props: AICourseContentProps) {
/>
)}
<div className="mx-auto mb-10 mt-5 text-center text-sm text-gray-400">
<div
className={cn(
'mx-auto mb-10 mt-5 text-center text-sm text-gray-400',
viewMode === 'module' ? 'hidden' : '',
)}
>
AI can make mistakes, check important info.
</div>
</main>

@ -28,6 +28,7 @@ import { AICourseFollowUp } from './AICourseFollowUp';
import './AICourseFollowUp.css';
import { RegenerateLesson } from './RegenerateLesson';
import { TestMyKnowledgeAction } from './TestMyKnowledgeAction';
import { AICourseLessonChat } from './AICourseLessonChat';
type AICourseLessonProps = {
courseSlug: string;
@ -209,39 +210,167 @@ export function AICourseLesson(props: AICourseLessonProps) {
isLoading;
return (
<div className="mx-auto max-w-4xl">
<div className="relative rounded-lg border border-gray-200 bg-white p-6 shadow-sm max-lg:px-4 max-lg:pb-4 max-lg:pt-3">
{(isGenerating || isLoading) && (
<div className="absolute right-3 top-3 flex items-center justify-center">
<Loader2Icon
size={18}
strokeWidth={3}
className="animate-spin text-gray-400/70"
/>
</div>
)}
<div className="grid h-full grid-cols-5">
<div className="relative col-span-3">
<div className="absolute inset-0 overflow-y-auto bg-white p-8 pb-0 max-lg:px-4 max-lg:pt-3">
{(isGenerating || isLoading) && (
<div className="absolute right-6 top-6 flex items-center justify-center">
<Loader2Icon
size={18}
strokeWidth={3}
className="animate-spin text-gray-400/70"
/>
</div>
)}
<div className="mb-4 flex items-center justify-between">
<div className="text-sm text-gray-500">
Lesson {activeLessonIndex + 1} of {totalLessons}
</div>
<div className="mb-4 flex items-center justify-between">
<div className="text-sm text-gray-500">
Lesson {activeLessonIndex + 1} of {totalLessons}
{!isGenerating && !isLoading && (
<div className="absolute right-6 top-6 flex items-center justify-between gap-2">
<RegenerateLesson
onRegenerateLesson={(prompt) => {
generateAiCourseContent(true, prompt);
}}
/>
<button
disabled={isLoading || isTogglingDone}
className={cn(
'flex items-center gap-1.5 rounded-full bg-black py-1 pl-2 pr-3 text-sm text-white hover:bg-gray-800 disabled:opacity-50 max-lg:text-xs',
isLessonDone
? 'bg-red-500 hover:bg-red-600'
: 'bg-green-500 hover:bg-green-600',
)}
onClick={() => toggleDone()}
>
{isTogglingDone ? (
<>
<Loader2Icon
size={16}
strokeWidth={3}
className="animate-spin text-white"
/>
Please wait ...
</>
) : (
<>
{isLessonDone ? (
<>
<XIcon size={16} />
Mark as Undone
</>
) : (
<>
<CheckIcon size={16} />
Mark as Done
</>
)}
</>
)}
</button>
</div>
)}
</div>
{!isGenerating && !isLoading && (
<div className="absolute right-3 top-3 flex items-center justify-between gap-2">
<RegenerateLesson
onRegenerateLesson={(prompt) => {
generateAiCourseContent(true, prompt);
}}
/>
<h1 className="mb-6 text-balance text-3xl font-semibold max-lg:mb-3 max-lg:text-xl">
{currentLessonTitle?.replace(/^Lesson\s*?\d+[\.:]\s*/, '')}
</h1>
{!error && isLoggedIn() && (
<div
className="course-content prose prose-lg mt-8 max-w-full text-black prose-headings:mb-3 prose-headings:mt-8 prose-blockquote:font-normal prose-pre:rounded-2xl prose-pre:text-lg prose-li:my-1 prose-thead:border-zinc-800 prose-tr:border-zinc-800 max-lg:mt-4 max-lg:text-base max-lg:prose-h2:mt-3 max-lg:prose-h2:text-lg max-lg:prose-h3:text-base max-lg:prose-pre:px-3 max-lg:prose-pre:text-sm"
dangerouslySetInnerHTML={{ __html: lessonHtml }}
/>
)}
{error && isLoggedIn() && (
<div className="mt-8 flex min-h-[300px] items-center justify-center rounded-xl bg-red-50/80">
{error.includes('reached the limit') ? (
<div className="flex max-w-sm flex-col items-center text-center">
<h2 className="text-xl font-semibold text-red-600">
Limit reached
</h2>
<p className="my-3 text-red-600">
You have reached the AI usage limit for today.
{!isPaidUser && (
<>Please upgrade your account to continue.</>
)}
{isPaidUser && (
<>&nbsp;Please wait until tomorrow to continue.</>
)}
</p>
{!isPaidUser && (
<button
onClick={() => {
onUpgrade();
}}
className="rounded-full bg-red-600 px-4 py-1 text-white hover:bg-red-700"
>
Upgrade Account
</button>
)}
</div>
) : (
<p className="text-red-600">{error}</p>
)}
</div>
)}
{!isLoggedIn() && (
<div className="mt-8 flex min-h-[152px] flex-col items-center justify-center gap-3 rounded-lg border border-gray-200 p-8">
<LockIcon className="size-7 stroke-[2] text-gray-400/90" />
<p className="text-sm text-gray-500">
Please login to generate course content
</p>
</div>
)}
{!isLoading && !isGenerating && !error && (
<TestMyKnowledgeAction
courseSlug={courseSlug}
activeModuleIndex={activeModuleIndex}
activeLessonIndex={activeLessonIndex}
/>
)}
<div className="mt-8 flex items-center justify-between">
<button
onClick={onGoToPrevLesson}
disabled={cantGoBack}
className={cn(
'flex items-center rounded-full px-4 py-2 disabled:opacity-50 max-lg:px-3 max-lg:py-1.5 max-lg:text-sm',
cantGoBack
? 'cursor-not-allowed text-gray-400'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200',
)}
>
<ChevronLeft size={16} className="mr-2" />
Previous <span className="hidden lg:inline">&nbsp;Lesson</span>
</button>
<div>
<button
disabled={isLoading || isTogglingDone}
onClick={() => {
if (!isLessonDone) {
toggleDone(undefined, {
onSuccess: () => {
onGoToNextLesson();
},
});
} else {
onGoToNextLesson();
}
}}
disabled={cantGoForward || isTogglingDone}
className={cn(
'flex items-center gap-1.5 rounded-full bg-black py-1 pl-2 pr-3 text-sm text-white hover:bg-gray-800 disabled:opacity-50 max-lg:text-xs',
isLessonDone
? 'bg-red-500 hover:bg-red-600'
: 'bg-green-500 hover:bg-green-600',
'flex items-center rounded-full px-4 py-2 disabled:opacity-50 max-lg:px-3 max-lg:py-1.5 max-lg:text-sm',
cantGoForward
? 'cursor-not-allowed text-gray-400'
: 'bg-gray-800 text-white hover:bg-gray-700',
)}
onClick={() => toggleDone()}
>
{isTogglingDone ? (
<>
@ -254,145 +383,27 @@ export function AICourseLesson(props: AICourseLessonProps) {
</>
) : (
<>
{isLessonDone ? (
<>
<XIcon size={16} />
Mark as Undone
</>
) : (
<>
<CheckIcon size={16} />
Mark as Done
</>
)}
Next <span className="hidden lg:inline">&nbsp;Lesson</span>
<ChevronRight size={16} className="ml-2" />
</>
)}
</button>
</div>
)}
</div>
<h1 className="mb-6 text-balance text-3xl font-semibold max-lg:mb-3 max-lg:text-xl">
{currentLessonTitle?.replace(/^Lesson\s*?\d+[\.:]\s*/, '')}
</h1>
{!error && isLoggedIn() && (
<div
className="course-content prose prose-lg mt-8 max-w-full text-black prose-headings:mb-3 prose-headings:mt-8 prose-blockquote:font-normal prose-pre:rounded-2xl prose-pre:text-lg prose-li:my-1 prose-thead:border-zinc-800 prose-tr:border-zinc-800 max-lg:mt-4 max-lg:text-base max-lg:prose-h2:mt-3 max-lg:prose-h2:text-lg max-lg:prose-h3:text-base max-lg:prose-pre:px-3 max-lg:prose-pre:text-sm"
dangerouslySetInnerHTML={{ __html: lessonHtml }}
/>
)}
{error && isLoggedIn() && (
<div className="mt-8 flex min-h-[300px] items-center justify-center rounded-xl bg-red-50/80">
{error.includes('reached the limit') ? (
<div className="flex max-w-sm flex-col items-center text-center">
<h2 className="text-xl font-semibold text-red-600">
Limit reached
</h2>
<p className="my-3 text-red-600">
You have reached the AI usage limit for today.
{!isPaidUser && <>Please upgrade your account to continue.</>}
{isPaidUser && <>&nbsp;Please wait until tomorrow to continue.</>}
</p>
{!isPaidUser && (
<button
onClick={() => {
onUpgrade();
}}
className="rounded-full bg-red-600 px-4 py-1 text-white hover:bg-red-700"
>
Upgrade Account
</button>
)}
</div>
) : (
<p className="text-red-600">{error}</p>
)}
</div>
)}
{!isLoggedIn() && (
<div className="mt-8 flex min-h-[152px] flex-col items-center justify-center gap-3 rounded-lg border border-gray-200 p-8">
<LockIcon className="size-7 stroke-[2] text-gray-400/90" />
<p className="text-sm text-gray-500">
Please login to generate course content
</p>
</div>
)}
{!isLoading && !isGenerating && !error && (
<TestMyKnowledgeAction
courseSlug={courseSlug}
activeModuleIndex={activeModuleIndex}
activeLessonIndex={activeLessonIndex}
/>
)}
<div className="mt-8 flex items-center justify-between">
<button
onClick={onGoToPrevLesson}
disabled={cantGoBack}
className={cn(
'flex items-center rounded-full px-4 py-2 disabled:opacity-50 max-lg:px-3 max-lg:py-1.5 max-lg:text-sm',
cantGoBack
? 'cursor-not-allowed text-gray-400'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200',
)}
>
<ChevronLeft size={16} className="mr-2" />
Previous <span className="hidden lg:inline">&nbsp;Lesson</span>
</button>
<div>
<button
onClick={() => {
if (!isLessonDone) {
toggleDone(undefined, {
onSuccess: () => {
onGoToNextLesson();
},
});
} else {
onGoToNextLesson();
}
}}
disabled={cantGoForward || isTogglingDone}
className={cn(
'flex items-center rounded-full px-4 py-2 disabled:opacity-50 max-lg:px-3 max-lg:py-1.5 max-lg:text-sm',
cantGoForward
? 'cursor-not-allowed text-gray-400'
: 'bg-gray-800 text-white hover:bg-gray-700',
)}
>
{isTogglingDone ? (
<>
<Loader2Icon
size={16}
strokeWidth={3}
className="animate-spin text-white"
/>
Please wait ...
</>
) : (
<>
Next <span className="hidden lg:inline">&nbsp;Lesson</span>
<ChevronRight size={16} className="ml-2" />
</>
)}
</button>
<div className="mx-auto mb-10 mt-5 text-center text-sm text-gray-400">
AI can make mistakes, check important info.
</div>
</div>
</div>
{!isGenerating && !isLoading && (
<AICourseFollowUp
courseSlug={courseSlug}
moduleTitle={currentModuleTitle}
lessonTitle={currentLessonTitle}
/>
)}
<AICourseLessonChat
courseSlug={courseSlug}
moduleTitle={currentModuleTitle}
lessonTitle={currentLessonTitle}
onUpgradeClick={onUpgrade}
isDisabled={isGenerating || isLoading || isTogglingDone}
/>
</div>
);
}

@ -0,0 +1,407 @@
import { useQuery } from '@tanstack/react-query';
import {
BookOpen,
Bot,
Hammer,
HelpCircle,
LockIcon,
Send,
} from 'lucide-react';
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type FormEvent,
} from 'react';
import { flushSync } from 'react-dom';
import TextareaAutosize from 'react-textarea-autosize';
import { useOutsideClick } from '../../hooks/use-outside-click';
import { useToast } from '../../hooks/use-toast';
import { readStream } from '../../lib/ai';
import { cn } from '../../lib/classname';
import { isLoggedIn, removeAuthToken } from '../../lib/jwt';
import {
markdownToHtml,
markdownToHtmlWithHighlighting,
} from '../../lib/markdown';
import { getAiCourseLimitOptions } from '../../queries/ai-course';
import { queryClient } from '../../stores/query-client';
import { billingDetailsOptions } from '../../queries/billing';
export type AllowedAIChatRole = 'user' | 'assistant';
export type AIChatHistoryType = {
role: AllowedAIChatRole;
content: string;
isDefault?: boolean;
html?: string;
};
type AICourseLessonChatProps = {
courseSlug: string;
moduleTitle: string;
lessonTitle: string;
onUpgradeClick: () => void;
isDisabled?: boolean;
};
export function AICourseLessonChat(props: AICourseLessonChatProps) {
const { courseSlug, moduleTitle, lessonTitle, onUpgradeClick, isDisabled } =
props;
const toast = useToast();
const scrollareaRef = useRef<HTMLDivElement | null>(null);
const [courseAIChatHistory, setCourseAIChatHistory] = useState<
AIChatHistoryType[]
>([
{
role: 'assistant',
content:
'Hey, I am your AI instructor. Here are some examples of what you can ask me about 🤖',
isDefault: true,
},
]);
const [isStreamingMessage, setIsStreamingMessage] = useState(false);
const [message, setMessage] = useState('');
const [streamedMessage, setStreamedMessage] = useState('');
const { data: tokenUsage, isLoading } = useQuery(
getAiCourseLimitOptions(),
queryClient,
);
const { data: userBillingDetails, isLoading: isBillingDetailsLoading } =
useQuery(billingDetailsOptions(), queryClient);
const isLimitExceeded = (tokenUsage?.used || 0) >= (tokenUsage?.limit || 0);
const isPaidUser = userBillingDetails?.status === 'active';
const handleChatSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const trimmedMessage = message.trim();
if (
!trimmedMessage ||
isStreamingMessage ||
!isLoggedIn() ||
isLimitExceeded ||
isLoading
) {
return;
}
const newMessages: AIChatHistoryType[] = [
...courseAIChatHistory,
{
role: 'user',
content: trimmedMessage,
},
];
flushSync(() => {
setCourseAIChatHistory(newMessages);
setMessage('');
});
scrollToBottom();
completeCourseAIChat(newMessages);
};
const scrollToBottom = useCallback(() => {
scrollareaRef.current?.scrollTo({
top: scrollareaRef.current.scrollHeight,
behavior: 'smooth',
});
}, [scrollareaRef]);
const completeCourseAIChat = async (messages: AIChatHistoryType[]) => {
setIsStreamingMessage(true);
const response = await fetch(
`${import.meta.env.PUBLIC_API_URL}/v1-follow-up-ai-course/${courseSlug}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify({
moduleTitle,
lessonTitle,
messages: messages.slice(-10),
}),
},
);
if (!response.ok) {
const data = await response.json();
toast.error(data?.message || 'Something went wrong');
setCourseAIChatHistory([...messages].slice(0, messages.length - 1));
setIsStreamingMessage(false);
if (data.status === 401) {
removeAuthToken();
window.location.reload();
}
}
const reader = response.body?.getReader();
if (!reader) {
setIsStreamingMessage(false);
toast.error('Something went wrong');
return;
}
await readStream(reader, {
onStream: async (content) => {
flushSync(() => {
setStreamedMessage(content);
});
scrollToBottom();
},
onStreamEnd: async (content) => {
const newMessages: AIChatHistoryType[] = [
...messages,
{
role: 'assistant',
content,
html: await markdownToHtmlWithHighlighting(content),
},
];
flushSync(() => {
setStreamedMessage('');
setIsStreamingMessage(false);
setCourseAIChatHistory(newMessages);
});
queryClient.invalidateQueries(getAiCourseLimitOptions());
scrollToBottom();
},
});
setIsStreamingMessage(false);
};
useEffect(() => {
scrollToBottom();
}, []);
return (
<div className="relative col-span-2 h-full border-l border-gray-200">
<div className="absolute inset-0 flex w-full flex-col overflow-hidden bg-white">
<div className="flex items-center justify-between gap-2 border-b border-gray-200 px-4 py-2 text-sm">
<h4 className="text-base font-medium">Course AI</h4>
</div>
<div
className="scrollbar-thumb-gray-300 scrollbar-track-transparent scrollbar-thin relative grow overflow-y-auto"
ref={scrollareaRef}
>
<div className="absolute inset-0 flex flex-col">
<div className="flex grow flex-col justify-end">
<div className="flex flex-col justify-end gap-2 px-3 py-2">
{courseAIChatHistory.map((chat, index) => {
return (
<>
<AIChatCard
key={`chat-${index}`}
role={chat.role}
content={chat.content}
html={chat.html}
/>
{chat.isDefault && (
<div className="mb-1 mt-0.5">
<div className="grid grid-cols-2 gap-2">
{capabilities.map((capability, index) => (
<CapabilityCard
key={`capability-${index}`}
{...capability}
/>
))}
</div>
</div>
)}
</>
);
})}
{isStreamingMessage && !streamedMessage && (
<AIChatCard role="assistant" content="Thinking..." />
)}
{streamedMessage && (
<AIChatCard role="assistant" content={streamedMessage} />
)}
</div>
</div>
</div>
</div>
<form
className="relative flex items-start border-t border-gray-200 text-sm"
onSubmit={handleChatSubmit}
>
{isLimitExceeded && (
<div className="absolute inset-0 flex items-center justify-center gap-2 bg-black text-white">
<LockIcon
className="size-4 cursor-not-allowed"
strokeWidth={2.5}
/>
<p className="cursor-not-allowed">
Limit reached for today
{isPaidUser ? '. Please wait until tomorrow.' : ''}
</p>
{!isPaidUser && (
<button
onClick={() => {
onUpgradeClick();
}}
className="rounded-md bg-white px-2 py-1 text-xs font-medium text-black hover:bg-gray-300"
>
Upgrade for more
</button>
)}
</div>
)}
<TextareaAutosize
className={cn(
'h-full min-h-[41px] grow resize-none bg-transparent px-4 py-2 focus:outline-none',
isDisabled ? 'cursor-not-allowed opacity-50' : 'cursor-auto',
)}
placeholder="Ask AI anything about the lesson..."
value={message}
onChange={(e) => setMessage(e.target.value)}
autoFocus={true}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
handleChatSubmit(e as unknown as FormEvent<HTMLFormElement>);
}
}}
/>
<button
type="submit"
disabled={isDisabled || isStreamingMessage || isLimitExceeded}
className="flex aspect-square size-[41px] items-center justify-center text-zinc-500 hover:text-black disabled:cursor-not-allowed disabled:opacity-50"
>
<Send className="size-4 stroke-[2.5]" />
</button>
</form>
</div>
</div>
);
}
type AIChatCardProps = {
role: AllowedAIChatRole;
content: string;
html?: string;
};
function AIChatCard(props: AIChatCardProps) {
const { role, content, html: defaultHtml } = props;
const html = useMemo(() => {
if (defaultHtml) {
return defaultHtml;
}
return markdownToHtml(content, false);
}, [content, defaultHtml]);
return (
<div
className={cn(
'flex flex-col rounded-lg',
role === 'user' ? 'bg-gray-300/30' : 'bg-yellow-500/30',
)}
>
<div className="flex items-start gap-2.5 p-3">
<div
className={cn(
'flex size-6 shrink-0 items-center justify-center rounded-full',
role === 'user'
? 'bg-gray-200 text-black'
: 'bg-yellow-400 text-black',
)}
>
<Bot className="size-4 stroke-[2.5]" />
</div>
<div
className="course-content course-ai-content prose prose-sm mt-0.5 max-w-full overflow-hidden text-sm"
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
</div>
);
}
type CapabilityCardProps = {
icon: React.ReactNode;
title: string;
description: string;
className?: string;
};
function CapabilityCard({
icon,
title,
description,
className,
}: CapabilityCardProps) {
return (
<div
className={cn(
'flex flex-col gap-2 rounded-lg bg-yellow-500/10 p-3',
className,
)}
>
<div className="flex items-center gap-2">
{icon}
<span className="text-[13px] font-medium leading-none text-black">
{title}
</span>
</div>
<p className="text-[12px] leading-normal text-gray-600">{description}</p>
</div>
);
}
const capabilities = [
{
icon: (
<HelpCircle
className="size-4 shrink-0 text-yellow-600"
strokeWidth={2.5}
/>
),
title: 'Clarify Concepts',
description: "If you don't understand a concept, ask me to clarify it",
},
{
icon: (
<BookOpen className="size-4 shrink-0 text-yellow-600" strokeWidth={2.5} />
),
title: 'More Details',
description: 'Get deeper insights about topics covered in the lesson',
},
{
icon: (
<Hammer className="size-4 shrink-0 text-yellow-600" strokeWidth={2.5} />
),
title: 'Real-world Examples',
description: 'Ask for real-world examples to understand better',
},
{
icon: <Bot className="size-4 shrink-0 text-yellow-600" strokeWidth={2.5} />,
title: 'Best Practices',
description: 'Learn about best practices and common pitfalls',
},
] as const;
Loading…
Cancel
Save