| 86 | const encoder = new TextEncoder() |
| 87 | const readable = new ReadableStream({ |
| 88 | async start(controller) { |
| 89 | try { |
| 90 | const streamResult = summarize({ |
| 91 | ...options, |
| 92 | text, |
| 93 | maxLength, |
| 94 | style, |
| 95 | stream: true, |
| 96 | }) |
| 97 | |
| 98 | for await (const chunk of streamResult) { |
| 99 | const data = JSON.stringify({ |
| 100 | type: chunk.type, |
| 101 | delta: 'delta' in chunk ? chunk.delta : undefined, |
| 102 | content: 'content' in chunk ? chunk.content : undefined, |
| 103 | provider, |
| 104 | model: ('model' in chunk && chunk.model) || actualModel, |
| 105 | }) |
| 106 | controller.enqueue(encoder.encode(`data: ${data}\n\n`)) |
| 107 | } |
| 108 | |
| 109 | controller.enqueue(encoder.encode('data: [DONE]\n\n')) |
| 110 | controller.close() |
| 111 | } catch (error: any) { |
| 112 | const errorData = JSON.stringify({ |
| 113 | type: 'error', |
| 114 | error: error.message || 'An error occurred', |
| 115 | }) |
| 116 | controller.enqueue(encoder.encode(`data: ${errorData}\n\n`)) |
| 117 | controller.close() |
| 118 | } |
| 119 | }, |
| 120 | }) |
| 121 | |
| 122 | return new Response(readable, { |