(requestBody: ChatCompletionRequest)
| 404 | |
| 405 | // Fallback to HTTP if WebSocket fails |
| 406 | const fallbackToHttp = async (requestBody: ChatCompletionRequest) => { |
| 407 | try { |
| 408 | // Make the API call using HTTP |
| 409 | const apiResponse = await fetch(`/api/chat/stream`, { |
| 410 | method: 'POST', |
| 411 | headers: { |
| 412 | 'Content-Type': 'application/json', |
| 413 | }, |
| 414 | body: JSON.stringify(requestBody) |
| 415 | }); |
| 416 | |
| 417 | if (!apiResponse.ok) { |
| 418 | throw new Error(`API error: ${apiResponse.status}`); |
| 419 | } |
| 420 | |
| 421 | // Process the streaming response |
| 422 | const reader = apiResponse.body?.getReader(); |
| 423 | const decoder = new TextDecoder(); |
| 424 | |
| 425 | if (!reader) { |
| 426 | throw new Error('Failed to get response reader'); |
| 427 | } |
| 428 | |
| 429 | // Read the stream |
| 430 | let fullResponse = ''; |
| 431 | while (true) { |
| 432 | const { done, value } = await reader.read(); |
| 433 | if (done) break; |
| 434 | |
| 435 | const chunk = decoder.decode(value, { stream: true }); |
| 436 | fullResponse += chunk; |
| 437 | setResponse(fullResponse); |
| 438 | |
| 439 | // Extract research stage if this is a deep research response |
| 440 | if (deepResearch) { |
| 441 | const stage = extractResearchStage(fullResponse, researchIteration); |
| 442 | if (stage) { |
| 443 | // Add the stage to the research stages |
| 444 | setResearchStages(prev => { |
| 445 | const existingStageIndex = prev.findIndex(s => s.iteration === stage.iteration && s.type === stage.type); |
| 446 | if (existingStageIndex >= 0) { |
| 447 | const newStages = [...prev]; |
| 448 | newStages[existingStageIndex] = stage; |
| 449 | return newStages; |
| 450 | } else { |
| 451 | return [...prev, stage]; |
| 452 | } |
| 453 | }); |
| 454 | } |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | // Check if research is complete |
| 459 | const isComplete = checkIfResearchComplete(fullResponse); |
| 460 | |
| 461 | // Force completion after a maximum number of iterations (5) |
| 462 | const forceComplete = researchIteration >= 5; |
| 463 |
no test coverage detected