Spaces:
Sleeping
Sleeping
File size: 5,427 Bytes
f871fed | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | 'use client'
import { useState, useCallback } from 'react'
import { toast } from 'sonner'
import { searchApi } from '@/lib/api/search'
import { AskStreamEvent } from '@/lib/types/search'
interface AskModels {
strategy: string
answer: string
finalAnswer: string
}
interface StrategyData {
reasoning: string
searches: Array<{ term: string; instructions: string }>
}
interface AskState {
isStreaming: boolean
strategy: StrategyData | null
answers: string[]
finalAnswer: string | null
error: string | null
}
export function useAsk() {
const [state, setState] = useState<AskState>({
isStreaming: false,
strategy: null,
answers: [],
finalAnswer: null,
error: null
})
const sendAsk = useCallback(async (question: string, models: AskModels) => {
// Validate inputs
if (!question.trim()) {
toast.error('Please enter a question')
return
}
if (!models.strategy || !models.answer || !models.finalAnswer) {
toast.error('Please configure all required models')
return
}
// Reset state
setState({
isStreaming: true,
strategy: null,
answers: [],
finalAnswer: null,
error: null
})
try {
const response = await searchApi.askKnowledgeBase({
question,
strategy_model: models.strategy,
answer_model: models.answer,
final_answer_model: models.finalAnswer
})
if (!response) {
throw new Error('No response body received from server')
}
const reader = response.getReader()
const decoder = new TextDecoder()
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
// Keep the last incomplete line in buffer
buffer = lines.pop() || ''
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const jsonStr = line.slice(6).trim()
if (!jsonStr) continue
const data: AskStreamEvent = JSON.parse(jsonStr)
if (data.type === 'strategy') {
setState(prev => ({
...prev,
strategy: {
reasoning: data.reasoning || '',
searches: data.searches || []
}
}))
} else if (data.type === 'answer') {
setState(prev => ({
...prev,
answers: [...prev.answers, data.content || '']
}))
} else if (data.type === 'final_answer') {
setState(prev => ({
...prev,
finalAnswer: data.content || '',
isStreaming: false
}))
} else if (data.type === 'complete') {
setState(prev => ({
...prev,
isStreaming: false
}))
} else if (data.type === 'error') {
throw new Error(data.message || 'Stream error occurred')
}
} catch (e) {
console.error('Error parsing SSE data:', e, 'Line:', line)
// Don't throw - continue processing other lines
}
}
}
}
// Ensure streaming is stopped
setState(prev => ({ ...prev, isStreaming: false }))
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'An unexpected error occurred'
console.error('Ask error:', error)
setState(prev => ({
...prev,
isStreaming: false,
error: errorMessage
}))
toast.error('Ask failed', {
description: errorMessage
})
}
}, [])
const reset = useCallback(() => {
setState({
isStreaming: false,
strategy: null,
answers: [],
finalAnswer: null,
error: null
})
}, [])
// Direct AI ask (without RAG - uses LLM's general knowledge)
const sendDirectAsk = useCallback(async (question: string, modelId?: string) => {
if (!question.trim()) {
toast.error('Please enter a question')
return
}
setState({
isStreaming: true,
strategy: null,
answers: [],
finalAnswer: null,
error: null
})
try {
const response = await fetch('/api/search/ask/direct', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
question,
model_id: modelId || undefined
})
})
if (!response.ok) {
const error = await response.json()
throw new Error(error.detail || 'Failed to get AI response')
}
const data = await response.json()
setState(prev => ({
...prev,
finalAnswer: data.answer,
isStreaming: false
}))
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'An unexpected error occurred'
console.error('Direct ask error:', error)
setState(prev => ({
...prev,
isStreaming: false,
error: errorMessage
}))
toast.error('Ask failed', { description: errorMessage })
}
}, [])
return {
...state,
sendAsk,
sendDirectAsk,
reset
}
}
|