File size: 6,939 Bytes
116a473 | 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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | const TAIL_LIMIT = 4 * 1024
const encoder = new TextEncoder()
export async function prepareRequestBody(body: ReadableStream<Uint8Array>) {
const reader = body.getReader()
const chunks: Uint8Array[] = []
const decoder = new TextDecoder()
let text = ""
let done = false
let bom = 0
let index = 0
let depth = 0
let stringStart = -1
let escaped = false
let phase: "key" | "colon" | "value" | "comma" = "key"
let key = ""
let found: { model: string; start: number; end: number } | undefined
const scan = () => {
while (index < text.length && !found) {
const char = text[index]
if (stringStart >= 0) {
if (escaped) escaped = false
else if (char === "\\") escaped = true
else if (char === '"') {
if (depth === 1 && phase === "key") {
key = JSON.parse(text.slice(stringStart, index + 1))
phase = "colon"
} else if (depth === 1 && phase === "value") {
if (key === "model") {
const start = bom + utf8Length(text, stringStart + 1)
found = {
model: JSON.parse(text.slice(stringStart, index + 1)),
start,
end: bom + utf8Length(text, index),
}
}
phase = "comma"
}
stringStart = -1
}
index++
continue
}
if (char === '"') {
stringStart = index++
continue
}
if (char === "{" || char === "[") {
if (depth === 1 && phase === "value") phase = "comma"
depth++
index++
continue
}
if (char === "}" || char === "]") {
depth--
index++
continue
}
if (depth !== 1) {
index++
continue
}
if (char === ":" && phase === "colon") phase = "value"
else if (char === "," && phase === "comma") phase = "key"
else if (phase === "value" && !/\s/.test(char)) phase = "comma"
index++
}
}
while (!done && !found) {
const next = await reader.read()
done = next.done
if (!next.value) continue
if (!chunks.length && next.value[0] === 0xef && next.value[1] === 0xbb && next.value[2] === 0xbf) bom = 3
chunks.push(next.value)
text += decoder.decode(next.value, { stream: true })
scan()
}
if (done) {
text += decoder.decode()
scan()
}
const preview = text.substring(0, 300)
text = ""
let used = false
return {
model: found?.model ?? "",
preview,
cancel: () => reader.cancel(),
stream(providerModel: string, includeUsage: boolean) {
if (used) throw new Error("Request body stream already consumed")
if (!found) throw new Error("Missing model field")
used = true
const initial = replace(chunks, found.start, found.end, providerModel)
chunks.length = 0
const output = passthrough(initial, reader, done)
if (!includeUsage) return output
return appendUsage(output)
},
}
}
function utf8Length(value: string, end: number) {
let length = 0
for (let i = 0; i < end; i++) {
const code = value.charCodeAt(i)
if (code <= 0x7f) length++
else if (code <= 0x7ff) length += 2
else if (code >= 0xd800 && code <= 0xdbff && i + 1 < end && value.charCodeAt(i + 1) >= 0xdc00) {
length += 4
i++
} else length += 3
}
return length
}
function replace(chunks: Uint8Array[], start: number, end: number, value: string) {
let offset = 0
let inserted = false
return chunks.flatMap((chunk) => {
const chunkStart = offset
const chunkEnd = offset + chunk.length
offset = chunkEnd
if (chunkEnd <= start || chunkStart >= end) return [chunk]
const parts = [chunk.subarray(0, Math.max(0, start - chunkStart))]
if (!inserted) {
parts.push(encoder.encode(value))
inserted = true
}
parts.push(chunk.subarray(Math.min(chunk.length, end - chunkStart)))
return parts.filter((part) => part.length)
})
}
function passthrough(
initial: Array<Uint8Array | undefined>,
reader: ReadableStreamDefaultReader<Uint8Array>,
sourceDone: boolean,
) {
let done = sourceDone
let index = 0
return new ReadableStream<Uint8Array>({
async pull(controller) {
const chunk = initial[index]
if (chunk) {
initial[index++] = undefined
controller.enqueue(chunk)
return
}
initial.length = 0
if (done) {
controller.close()
return
}
const next = await reader.read()
done = next.done
if (next.value) controller.enqueue(next.value)
if (done) controller.close()
},
cancel(reason) {
initial.length = 0
return reader.cancel(reason)
},
})
}
function appendUsage(body: ReadableStream<Uint8Array>) {
const reader = body.getReader()
const decoder = new TextDecoder()
let tail = new Uint8Array()
let streamText = ""
let isStream = false
const inspect = (chunk?: Uint8Array) => {
streamText += chunk ? decoder.decode(chunk, { stream: true }) : decoder.decode()
for (const match of streamText.matchAll(/"stream"\s*:\s*(true|false)/g)) isStream = match[1] === "true"
streamText = streamText.slice(-64)
}
return new ReadableStream<Uint8Array>({
async pull(controller) {
while (true) {
const next = await reader.read()
if (next.done) {
inspect()
if (!isStream) {
if (tail.length) controller.enqueue(tail)
controller.close()
return
}
const close = tail.lastIndexOf(125)
if (close < 0) {
controller.error(new Error("Invalid JSON request body"))
return
}
if (close) controller.enqueue(tail.subarray(0, close))
controller.enqueue(encoder.encode(',"stream_options":{"include_usage":true}}'))
if (close + 1 < tail.length) controller.enqueue(tail.subarray(close + 1))
controller.close()
return
}
const chunk = next.value
inspect(chunk)
if (tail.length + chunk.length <= TAIL_LIMIT) {
const combined = new Uint8Array(tail.length + chunk.length)
combined.set(tail)
combined.set(chunk, tail.length)
tail = combined
continue
}
const emit = tail.length + chunk.length - TAIL_LIMIT
if (emit <= tail.length) {
controller.enqueue(tail.subarray(0, emit))
const combined = new Uint8Array(TAIL_LIMIT)
combined.set(tail.subarray(emit))
combined.set(chunk, tail.length - emit)
tail = combined
return
}
if (tail.length) controller.enqueue(tail)
controller.enqueue(chunk.subarray(0, emit - tail.length))
tail = chunk.slice(emit - tail.length)
return
}
},
cancel(reason) {
return reader.cancel(reason)
},
})
}
|