d3ro-voice/apps/web/src/components/knowledge/knowledge-search.tsx

134 lines
4.1 KiB
TypeScript

'use client'
// apps/web/src/components/knowledge/knowledge-search.tsx
// 지식 베이스 시맨틱 검색 — search-knowledge Edge Function 호출
import { useState } from 'react'
import { Box, TextField, Button, Stack, Alert, CircularProgress } from '@mui/material'
import SearchIcon from '@mui/icons-material/Search'
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
interface SearchResult {
id: string
document_id: string
chunk_index: number
content: string
similarity: number
}
export function KnowledgeSearch(): React.ReactElement {
const [query, setQuery] = useState('')
const [results, setResults] = useState<SearchResult[]>([])
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSearch(): Promise<void> {
if (!query.trim()) return
setError(null)
setBusy(true)
try {
const supabase = getSupabaseBrowserClient()
const {
data: { session }
} = await supabase.auth.getSession()
if (!session) {
setError('로그인이 필요합니다')
return
}
const response = await fetch(
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/search-knowledge`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${session.access_token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ query: query.trim(), count: 8 })
}
)
if (!response.ok) {
const errData = (await response.json()) as { error?: string; message?: string }
throw new Error(errData.message ?? errData.error ?? `검색 실패: ${response.status}`)
}
const data = (await response.json()) as { results: SearchResult[] }
setResults(data.results)
} catch (e) {
setError(e instanceof Error ? e.message : 'Unknown error')
} finally {
setBusy(false)
}
}
return (
<Stack spacing={2}>
<Stack direction="row" spacing={1}>
<TextField
fullWidth
size="small"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
void handleSearch()
}
}}
placeholder="지식 베이스에서 검색... (시맨틱)"
disabled={busy}
/>
<Button
variant="contained"
startIcon={busy ? <CircularProgress size={16} color="inherit" /> : <SearchIcon />}
onClick={() => void handleSearch()}
disabled={busy || !query.trim()}
>
검색
</Button>
</Stack>
{error && (
<Alert severity="error" variant="outlined">
{error}
</Alert>
)}
{results.length > 0 && (
<Stack spacing={1.5}>
<PhosphorText variant="label" color="label">
검색 결과 ({results.length})
</PhosphorText>
{results.map((r) => (
<MetalCard key={r.id} sx={{ p: 2 }}>
<Stack direction="row" alignItems="center" spacing={1} sx={{ mb: 1 }}>
<Box sx={{ ...typoSx('label'), color: d3roPalette.text.label }}>
#{r.chunk_index}
</Box>
<Box
sx={{
px: 1,
py: 0.25,
borderRadius: 0.5,
bgcolor: d3roPalette.tag.greenBg,
color: d3roPalette.tag.green,
fontSize: 11,
fontVariantNumeric: 'tabular-nums'
}}
>
{Math.round(r.similarity * 100)}%
</Box>
</Stack>
<Box sx={{ ...typoSx('body'), color: d3roPalette.text.primary, whiteSpace: 'pre-wrap' }}>
{r.content}
</Box>
</MetalCard>
))}
</Stack>
)}
</Stack>
)
}