|
| 1 | +import { env } from '@codebuff/internal/env' |
| 2 | + |
| 3 | +export async function handleOpenrouterStream({ body }: { body: any }) { |
| 4 | + // Ensure usage tracking is enabled |
| 5 | + if (body.usage === undefined) { |
| 6 | + body.usage = {} |
| 7 | + } |
| 8 | + body.usage.include = true |
| 9 | + |
| 10 | + const response = await fetch( |
| 11 | + 'https://openrouter.ai/api/v1/chat/completions', |
| 12 | + { |
| 13 | + method: 'POST', |
| 14 | + headers: { |
| 15 | + Authorization: `Bearer ${env.OPEN_ROUTER_API_KEY}`, |
| 16 | + 'HTTP-Referer': 'https://codebuff.com', |
| 17 | + 'X-Title': 'Codebuff', |
| 18 | + 'Content-Type': 'application/json', |
| 19 | + }, |
| 20 | + body: JSON.stringify(body), |
| 21 | + } |
| 22 | + ) |
| 23 | + |
| 24 | + if (!response.ok) { |
| 25 | + throw new Error(`OpenRouter API error: ${response.statusText}`) |
| 26 | + } |
| 27 | + |
| 28 | + const reader = response.body?.getReader() |
| 29 | + if (!reader) { |
| 30 | + throw new Error('Failed to get response reader') |
| 31 | + } |
| 32 | + |
| 33 | + let heartbeatInterval: ReturnType<typeof setInterval> |
| 34 | + |
| 35 | + // Create a ReadableStream that Next.js can handle |
| 36 | + const stream = new ReadableStream({ |
| 37 | + async start(controller) { |
| 38 | + const decoder = new TextDecoder() |
| 39 | + let buffer = '' |
| 40 | + |
| 41 | + // Send initial connection message |
| 42 | + controller.enqueue( |
| 43 | + new TextEncoder().encode(`: connected ${new Date().toISOString()}\n`) |
| 44 | + ) |
| 45 | + |
| 46 | + // Start heartbeat |
| 47 | + heartbeatInterval = setInterval(() => { |
| 48 | + controller.enqueue( |
| 49 | + new TextEncoder().encode( |
| 50 | + `: heartbeat ${new Date().toISOString()}\n\n` |
| 51 | + ) |
| 52 | + ) |
| 53 | + }, 30000) |
| 54 | + |
| 55 | + try { |
| 56 | + while (true) { |
| 57 | + const { done, value } = await reader.read() |
| 58 | + |
| 59 | + if (done) { |
| 60 | + break |
| 61 | + } |
| 62 | + |
| 63 | + buffer += decoder.decode(value, { stream: true }) |
| 64 | + let lineEnd = buffer.indexOf('\n') |
| 65 | + |
| 66 | + while (lineEnd !== -1) { |
| 67 | + const line = buffer.slice(0, lineEnd + 1) |
| 68 | + buffer = buffer.slice(lineEnd + 1) |
| 69 | + |
| 70 | + // Forward the line to the client |
| 71 | + controller.enqueue(new TextEncoder().encode(line)) |
| 72 | + |
| 73 | + lineEnd = buffer.indexOf('\n') |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + controller.close() |
| 78 | + } catch (error) { |
| 79 | + controller.error(error) |
| 80 | + } finally { |
| 81 | + clearInterval(heartbeatInterval) |
| 82 | + reader.cancel() |
| 83 | + } |
| 84 | + }, |
| 85 | + cancel() { |
| 86 | + clearInterval(heartbeatInterval) |
| 87 | + reader.cancel() |
| 88 | + }, |
| 89 | + }) |
| 90 | + |
| 91 | + return stream |
| 92 | +} |
0 commit comments