( streamCompletion: AsyncGenerator<string | ChatMessage>, log: boolean = false, )
| 98 | * Convert a stream of arbitrary chunks to a stream of lines |
| 99 | */ |
| 100 | export async function* streamLines( |
| 101 | streamCompletion: AsyncGenerator<string | ChatMessage>, |
| 102 | log: boolean = false, |
| 103 | ): LineStream { |
| 104 | let allLines = []; |
| 105 | |
| 106 | let buffer = ""; |
| 107 | |
| 108 | try { |
| 109 | for await (const update of streamCompletion) { |
| 110 | const chunk = |
| 111 | typeof update === "string" ? update : renderChatMessage(update); |
| 112 | buffer += chunk; |
| 113 | const lines = buffer.split("\n"); |
| 114 | buffer = lines.pop() ?? ""; |
| 115 | for (const line of lines) { |
| 116 | yield line; |
| 117 | allLines.push(line); |
| 118 | } |
| 119 | |
| 120 | // if (buffer === "" && chunk.endsWith("\n")) { |
| 121 | // yield ""; |
| 122 | // allLines.push(""); |
| 123 | // } |
| 124 | } |
| 125 | if (buffer.length > 0) { |
| 126 | yield buffer; |
| 127 | allLines.push(buffer); |
| 128 | } |
| 129 | } finally { |
| 130 | if (log) { |
| 131 | console.log("Streamed lines: ", allLines.join("\n")); |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | export async function* generateLines<T>(lines: T[]): AsyncGenerator<T> { |
| 137 | for (const line of lines) { |
no test coverage detected