Open History to see the last commit
1import type { ClientOptions } from 'openai'
2
3type Fetch = NonNullable<ClientOptions['fetch']>
4
5function isRecord(value: unknown): value is Record<string, unknown> {
6 return typeof value === 'object' && value !== null && !Array.isArray(value)
7}
8
9/** The text of a `reasoning` part: its `text`, `summary[].text` and `content[].text`. */
10function reasoningText(part: Record<string, unknown>): string {
11 let text = typeof part.text === 'string' ? part.text : ''
12 for (const key of ['summary', 'content']) {
13 const entries = part[key]
14 if (!Array.isArray(entries)) continue
15 for (const entry of entries) {
16 if (isRecord(entry) && typeof entry.text === 'string') text += entry.text
17 }
18 }
19 return text
20}
21
22/**
23 * Turn an array `content` on a message or delta into the string the Chat
24 * Completions spec requires. `text` parts become `content`; `reasoning` parts
25 * go to `reasoning_content`, where the adapter reads reasoning.
26 */
27function flattenContent(target: unknown): boolean {
28 if (!isRecord(target) || !Array.isArray(target.content)) return false
29 let text = ''
30 let reasoning = ''
31 for (const part of target.content) {
32 if (!isRecord(part)) continue
33 if (part.type === 'text' && typeof part.text === 'string') text += part.text
34 else if (part.type === 'reasoning') reasoning += reasoningText(part)
35 }
36 target.content = text
37 if (reasoning) {
38 const existing =
39 typeof target.reasoning_content === 'string'
40 ? target.reasoning_content
41 : ''
42 target.reasoning_content = existing + reasoning
43 }
44 return true
45}
46
47/** Repair Neon content and usage fields, or return `undefined` when unchanged. */
48function rewrite(json: string): string | undefined {
49 let body: unknown
50 try {
51 body = JSON.parse(json)
52 } catch {
53 return undefined
54 }
55 if (!isRecord(body) || !Array.isArray(body.choices)) return undefined
56 let changed = false
57 for (const choice of body.choices) {
58 if (!isRecord(choice)) continue
59 if (flattenContent(choice.message)) changed = true
60 if (flattenContent(choice.delta)) changed = true
61 }
62 // Gemini reports reasoning tokens at the root of usage. The inherited
63 // Chat Completions parser reads the standard nested field, including on
64 // usage-only chunks whose choices array is empty.
65 if (isRecord(body.usage) && typeof body.usage.reasoning_tokens === 'number') {
66 const details = isRecord(body.usage.completion_tokens_details)
67 ? body.usage.completion_tokens_details
68 : {}
69 body.usage.completion_tokens_details = {
70 ...details,
71 reasoning_tokens: details.reasoning_tokens ?? body.usage.reasoning_tokens,
72 }
73 changed = true
74 }
75 return changed ? JSON.stringify(body) : undefined
76}
77
78/** Rewrites each SSE `data:` line, buffering a line split across chunks. */
79function sseRewriter(): TransformStream<string, string> {
80 let buffer = ''
81 const rewriteLine = (line: string) => {
82 if (!line.startsWith('data:')) return line
83 const fixed = rewrite(line.slice(5))
84 return fixed === undefined ? line : `data: ${fixed}`
85 }
86 return new TransformStream({
87 transform(chunk, controller) {
88 buffer += chunk
89 const lines = buffer.split('\n')
90 buffer = lines.pop() ?? ''
91 if (lines.length > 0) {
92 controller.enqueue(lines.map(rewriteLine).join('\n') + '\n')
93 }
94 },
95 flush(controller) {
96 if (buffer) controller.enqueue(rewriteLine(buffer))
97 },
98 })
99}
100
101function withBody(response: Response, body: BodyInit): Response {
102 const headers = new Headers(response.headers)
103 // The body is already decoded, and a rewrite changes its length.
104 headers.delete('content-length')
105 headers.delete('content-encoding')
106 return new Response(body, {
107 status: response.status,
108 statusText: response.statusText,
109 headers,
110 })
111}
112
113/**
114 * A fetch for the Chat Completions route. For some models the gateway sends
115 * `content` as an array of `{ type: 'reasoning' | 'text' }` parts instead of a
116 * string, in JSON and in each streamed delta. This fetch rewrites those to the
117 * spec shape before the OpenAI SDK reads them, so `chatStream`,
118 * `structuredOutput` and `structuredOutputStream` all see strings. A body
119 * with string content passes through unchanged.
120 *
121 * ponytail: remove when Neon returns string content (neondatabase/neon-pkgs#308).
122 */
123export function normalizeNeonContent(baseFetch?: Fetch): Fetch {
124 return async (input, init) => {
125 const response = await (baseFetch ?? globalThis.fetch)(input, init)
126 if (!response.ok || !response.body) return response
127 const type = response.headers.get('content-type') ?? ''
128 if (type.includes('text/event-stream')) {
129 return withBody(
130 response,
131 response.body
132 .pipeThrough(new TextDecoderStream())
133 .pipeThrough(sseRewriter())
134 .pipeThrough(new TextEncoderStream()),
135 )
136 }
137 if (type.includes('application/json')) {
138 const text = await response.text()
139 return withBody(response, rewrite(text) ?? text)
140 }
141 return response
142 }
143}