Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: api-integration added #12

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ lerna-debug.log*

node_modules
dist
build
dist-ssr
*.local
pnpm-lock.yaml
.eslintcache

# Editor directories and files
.idea
Expand All @@ -23,3 +24,4 @@ pnpm-lock.yaml
*.sw?

.firebase
.env
118 changes: 0 additions & 118 deletions src/components/Chatbot/Chatbot.tsx

This file was deleted.

53 changes: 53 additions & 0 deletions src/components/Chatbot/MessageInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import SendIcon from '@mui/icons-material/Send'
import { Box, CircularProgress, IconButton, TextField } from '@mui/material'
import { useCallback, useState } from 'react'

interface MessageInputProps {
onSend: (message: string) => Promise<void>
isLoading: boolean
}

const MessageInput = ({ onSend, isLoading }: MessageInputProps) => {
const [input, setInput] = useState('')

const handleSendClick = useCallback(async () => {
if (input.trim()) {
await onSend(input.trim())
setInput('')
}
}, [input, onSend])

const handleInputKeyDown = useCallback(
async (event_: React.KeyboardEvent<HTMLDivElement>) => {
if (event_.key === 'Enter') {
event_.preventDefault()
await handleSendClick()
}
},
[handleSendClick],
)

return (
<Box sx={{ p: 2, borderTop: 1, borderColor: 'divider' }}>
<Box sx={{ display: 'flex', gap: 1 }}>
<TextField
fullWidth
variant="outlined"
placeholder="Type your message..."
value={input}
onChange={event_ => setInput(event_.target.value)}
onKeyDown={handleInputKeyDown}
/>
<IconButton
color="primary"
onClick={handleSendClick}
disabled={!input.trim() || isLoading}
>
{isLoading ? <CircularProgress size={24} /> : <SendIcon />}
</IconButton>
</Box>
</Box>
)
}

export default MessageInput
57 changes: 57 additions & 0 deletions src/components/Chatbot/MessageList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Box } from '@mui/material'
import { memo, useEffect, useRef } from 'react'

const MessageList = memo(({ messages }: { messages: Message[] }) => {
const lastMessageRef = useRef<HTMLDivElement | null>(null)

useEffect(() => {
if (lastMessageRef.current) {
lastMessageRef.current.scrollIntoView({ behavior: 'smooth' })
}
}, [messages])

return (
<Box
sx={{
flex: 1,
overflowY: 'auto',
p: 2,
display: 'flex',
flexDirection: 'column',
gap: 2,
}}
>
{messages.map(({ id, text, sender, timestamp }, index) => (
<Box
key={id}
ref={index === messages.length - 1 ? lastMessageRef : null}
sx={{
alignSelf: sender === 'user' ? 'flex-end' : 'flex-start',
maxWidth: '70%',
p: 2,
borderRadius: 2,
bgcolor: sender === 'user' ? 'primary.main' : 'grey.200',
color: sender === 'user' ? 'common.white' : 'text.primary',
}}
>
<Box>{text}</Box>
<Box
sx={{
fontSize: '0.75rem',
color:
sender === 'user'
? 'rgba(255,255,255,0.7)'
: 'text.secondary',
mt: 0.5,
textAlign: 'right',
}}
>
{timestamp.toLocaleTimeString()}
</Box>
</Box>
))}
</Box>
)
})

export default MessageList
1 change: 0 additions & 1 deletion src/components/Chatbot/index.ts

This file was deleted.

25 changes: 25 additions & 0 deletions src/components/Chatbot/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { CustomDialog } from '@/components/common'
import { useChatbot } from '@/hooks'
import { Box } from '@mui/material'
import MessageInput from './MessageInput'
import MessageList from './MessageList'

interface ChatbotProps {
open: boolean
onClose: () => void
}

const Chatbot = ({ open, onClose }: ChatbotProps) => {
const { messages, handleSend, isLoading } = useChatbot()

return (
<CustomDialog open={open} onClose={onClose} title="PlanifyAI Chatbot" maxWidth="md" fullWidth>
<Box sx={{ display: 'flex', flexDirection: 'column', height: 500 }}>
<MessageList messages={messages} />
<MessageInput onSend={handleSend} isLoading={isLoading} />
</Box>
</CustomDialog>
)
}

export default Chatbot
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as useChatbot } from './useChatbot'
79 changes: 79 additions & 0 deletions src/hooks/useChatbot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { useCallback, useReducer, useState } from 'react'

interface MessageAction {
type: 'add'
payload: Message
}

const messageReducer = (state: Message[], action: MessageAction) => {
switch (action.type) {
case 'add':
return [...state, action.payload]
default:
return state
}
}

const useChatbot = () => {
const [messages, dispatch] = useReducer(messageReducer, [])
const [isLoading, setIsLoading] = useState(false)

const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions'
const DEEPSEEK_API_KEY = import.meta.env.VITE_API_KEY as string

const addMessage = useCallback((text: string, sender: 'user' | 'bot') => {
dispatch({
type: 'add',
payload: {
id: Date.now(),
text,
sender,
timestamp: new Date(),
},
})
}, [])

const handleSend = useCallback(
async (input: string) => {
addMessage(input, 'user')
setIsLoading(true)

try {
const response = await fetch(DEEPSEEK_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: [{ role: 'user', content: input }],
temperature: 0.7,
max_tokens: 1000,
}),
})

if (!response.ok) {
throw new Error('API Error')
}

const data = await response.json() as DeepSeekResponse
const botMessage
= data?.choices?.[0]?.message?.content ?? 'No response from the bot.'
addMessage(botMessage, 'bot')
}
catch (error) {
console.error('Error:', error)
addMessage('An error occurred. Please try again later.', 'bot')
}
finally {
setIsLoading(false)
}
},
[addMessage, DEEPSEEK_API_URL, DEEPSEEK_API_KEY],
)

return { messages, handleSend, isLoading }
}

export default useChatbot
2 changes: 1 addition & 1 deletion src/pages/Home.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Chatbot } from '@/components/Chatbot'
import Chatbot from '@/components/Chatbot'
import { Calendar } from '@/components/Home'
import ChatIcon from '@mui/icons-material/Chat'
import { Box, Fab } from '@mui/material'
Expand Down
23 changes: 23 additions & 0 deletions src/types/chatBot.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
interface DeepSeekError {
error?: {
message?: string
}
}

interface DeepSeekMessage {
role: string
content: string
}

interface DeepSeekResponse {
choices?: Array<{
message?: DeepSeekMessage
}>
}

interface Message {
id: number
text: string
sender: 'user' | 'bot'
timestamp: Date
}
Loading