@namzu/openai 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/dist/__tests__/document-input.test.d.ts +2 -0
  3. package/dist/__tests__/document-input.test.d.ts.map +1 -0
  4. package/dist/__tests__/document-input.test.js +92 -0
  5. package/dist/__tests__/document-input.test.js.map +1 -0
  6. package/dist/__tests__/error-taxonomy.test.d.ts +14 -0
  7. package/dist/__tests__/error-taxonomy.test.d.ts.map +1 -0
  8. package/dist/__tests__/error-taxonomy.test.js +203 -0
  9. package/dist/__tests__/error-taxonomy.test.js.map +1 -0
  10. package/dist/__tests__/openai.test.js +74 -3
  11. package/dist/__tests__/openai.test.js.map +1 -1
  12. package/dist/__tests__/reasoning-params.test.d.ts +2 -0
  13. package/dist/__tests__/reasoning-params.test.d.ts.map +1 -0
  14. package/dist/__tests__/reasoning-params.test.js +61 -0
  15. package/dist/__tests__/reasoning-params.test.js.map +1 -0
  16. package/dist/__tests__/strict-schema.test.d.ts +2 -0
  17. package/dist/__tests__/strict-schema.test.d.ts.map +1 -0
  18. package/dist/__tests__/strict-schema.test.js +85 -0
  19. package/dist/__tests__/strict-schema.test.js.map +1 -0
  20. package/dist/client.d.ts +28 -1
  21. package/dist/client.d.ts.map +1 -1
  22. package/dist/client.js +162 -67
  23. package/dist/client.js.map +1 -1
  24. package/dist/strict-schema.d.ts +2 -0
  25. package/dist/strict-schema.d.ts.map +1 -0
  26. package/dist/strict-schema.js +2 -0
  27. package/dist/strict-schema.js.map +1 -0
  28. package/package.json +4 -4
  29. package/src/__tests__/document-input.test.ts +125 -0
  30. package/src/__tests__/error-taxonomy.test.ts +234 -0
  31. package/src/__tests__/openai.test.ts +77 -3
  32. package/src/__tests__/reasoning-params.test.ts +76 -0
  33. package/src/__tests__/strict-schema.test.ts +110 -0
  34. package/src/client.ts +169 -67
  35. package/src/strict-schema.ts +0 -0
package/src/client.ts CHANGED
@@ -8,6 +8,13 @@ import type {
8
8
  TokenUsage,
9
9
  ToolChoice,
10
10
  } from '@namzu/sdk'
11
+ import { toolResultToText } from '@namzu/sdk'
12
+ import {
13
+ ProviderRequestError,
14
+ isCallerAbortError,
15
+ isProviderRequestError,
16
+ providerVendorError,
17
+ } from '@namzu/sdk'
11
18
  import OpenAI from 'openai'
12
19
  import type {
13
20
  ChatCompletionContentPart,
@@ -27,6 +34,7 @@ export const OPENAI_CAPABILITIES: ProviderCapabilities = {
27
34
  supportsStreaming: true,
28
35
  supportsFunctionCalling: true,
29
36
  supportsVision: true,
37
+ supportsDocuments: true,
30
38
  }
31
39
 
32
40
  type OpenAIFinishReason = 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call'
@@ -84,6 +92,47 @@ function formatToolChoice(tc: ToolChoice | undefined): ChatCompletionToolChoiceO
84
92
  return undefined
85
93
  }
86
94
 
95
+ /**
96
+ * Refuse an extended-thinking request this driver does not implement.
97
+ *
98
+ * The parameter was accepted and dropped, so a caller who had asked for
99
+ * reasoning got an ordinary completion: no thinking, no reasoning blocks,
100
+ * no error — and the empty reasoning array reads as "the model did not
101
+ * reason" rather than "nobody asked it to". Turning it OFF is honoured as
102
+ * a no-op, because that is the state the driver is already in.
103
+ */
104
+ export function assertThinkingSupported(params: {
105
+ thinking?: { type: 'enabled' | 'disabled' }
106
+ }): void {
107
+ if (params.thinking?.type !== 'enabled') return
108
+ throw new Error(
109
+ 'This provider driver does not implement extended thinking, and silently ' +
110
+ 'ignoring the request would return an ordinary completion with an empty ' +
111
+ 'reasoning list. Drop `thinking`, or use a driver that implements it.',
112
+ )
113
+ }
114
+
115
+ /**
116
+ * Refuse a document whose citations this wire cannot return.
117
+ *
118
+ * Citations are the difference between an answer you trust and one you
119
+ * verify, and this request format has no mechanism to carry them back.
120
+ * Sending the document anyway would answer the question and quietly drop
121
+ * the checkability the caller specifically asked for — the caller would
122
+ * see prose, no error, and an empty `citations` array they might read as
123
+ * "the model cited nothing" rather than "nobody asked".
124
+ */
125
+ function assertCitationsSupported(
126
+ attachment: { citations?: boolean; name?: string },
127
+ index: number,
128
+ ): void {
129
+ if (!attachment.citations) return
130
+ const which = attachment.name ?? `attachment ${index}`
131
+ throw new Error(
132
+ `This provider cannot return citations, and ${which} asked for them. Drop \`citations\` to send the document without them, or use a provider whose capabilities include citation support.`,
133
+ )
134
+ }
135
+
87
136
  export function toOpenAIMessages(
88
137
  messages: ChatCompletionParams['messages'],
89
138
  ): ChatCompletionMessageParam[] {
@@ -92,16 +141,32 @@ export function toOpenAIMessages(
92
141
  return { role: 'system', content: msg.content }
93
142
  }
94
143
  if (msg.role === 'user') {
95
- // User message with image attachments → multimodal content parts
96
- // (text first, then each image as an `image_url` part carrying a
97
- // base64 data URI). Mirrors the Anthropic driver's image-block
98
- // mapping; plain text-only user messages keep the string form.
144
+ // User message with attachments → multimodal content parts, text
145
+ // first. Images become an `image_url` part carrying a base64 data
146
+ // URI; documents become a `file` part. Plain text-only user
147
+ // messages keep the string form.
99
148
  if (msg.attachments && msg.attachments.length > 0) {
100
149
  const parts: ChatCompletionContentPart[] = []
101
150
  if (msg.content.length > 0) {
102
151
  parts.push({ type: 'text', text: msg.content })
103
152
  }
104
- for (const att of msg.attachments) {
153
+ for (const [index, att] of msg.attachments.entries()) {
154
+ if (att.type === 'document') {
155
+ // A document is not an image with a different media
156
+ // type. Every attachment used to become an `image_url`,
157
+ // so a PDF went up as `data:application/pdf;base64,...`
158
+ // inside an image part — while the capability set
159
+ // claimed documents were supported.
160
+ assertCitationsSupported(att, index)
161
+ parts.push({
162
+ type: 'file',
163
+ file: {
164
+ file_data: `data:${att.mediaType};base64,${att.data}`,
165
+ ...(att.name ? { filename: att.name } : {}),
166
+ },
167
+ } as ChatCompletionContentPart)
168
+ continue
169
+ }
105
170
  parts.push({
106
171
  type: 'image_url',
107
172
  image_url: { url: `data:${att.mediaType};base64,${att.data}` },
@@ -114,7 +179,10 @@ export function toOpenAIMessages(
114
179
  if (msg.role === 'tool') {
115
180
  return {
116
181
  role: 'tool',
117
- content: msg.content,
182
+ // Tool messages are text-only on this wire, so a content block
183
+ // degrades to an honest placeholder rather than having its
184
+ // base64 payload dumped as text.
185
+ content: toolResultToText(msg.content),
118
186
  tool_call_id: msg.toolCallId,
119
187
  }
120
188
  }
@@ -137,14 +205,28 @@ export function toOpenAIMessages(
137
205
  })
138
206
  }
139
207
 
140
- function toOpenAITools(params: ChatCompletionParams): ChatCompletionTool[] | undefined {
208
+ /**
209
+ * Tool schemas, with constrained generation where the caller asked for it.
210
+ *
211
+ * `enforceToolInputSchema` names the tools whose schema should be enforced
212
+ * rather than suggested. Both sibling drivers consumed it; this one dropped
213
+ * it on the floor, so a caller who had asked for a guaranteed-valid tool
214
+ * input got a best-effort one — and found out from a repair attempt rather
215
+ * than from an error.
216
+ *
217
+ * This wire is the one the flag maps onto most directly: it takes `strict`
218
+ * on the function itself.
219
+ */
220
+ export function toOpenAITools(params: ChatCompletionParams): ChatCompletionTool[] | undefined {
141
221
  if (!params.tools || params.tools.length === 0) return undefined
222
+ const enforced = new Set(params.enforceToolInputSchema ?? [])
142
223
  return params.tools.map((t) => ({
143
224
  type: 'function' as const,
144
225
  function: {
145
226
  name: t.function.name,
146
227
  description: t.function.description ?? '',
147
228
  parameters: (t.function.parameters ?? {}) as Record<string, unknown>,
229
+ ...(enforced.has(t.function.name) ? { strict: true } : {}),
148
230
  },
149
231
  }))
150
232
  }
@@ -187,74 +269,94 @@ export class OpenAIProvider implements LLMProvider {
187
269
 
188
270
  async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
189
271
  const model = this.resolveModel(params)
272
+ assertThinkingSupported(params)
190
273
 
191
- const stream = await this.client.chat.completions.create(
192
- {
193
- model,
194
- messages: toOpenAIMessages(params.messages),
195
- stream: true,
196
- stream_options: { include_usage: true },
197
- tools: toOpenAITools(params),
198
- tool_choice: formatToolChoice(params.toolChoice),
199
- parallel_tool_calls: params.parallelToolCalls,
200
- temperature: params.temperature,
201
- max_tokens: params.maxTokens,
202
- top_p: params.topP,
203
- frequency_penalty: params.frequencyPenalty,
204
- presence_penalty: params.presencePenalty,
205
- stop: params.stop,
206
- response_format: params.responseFormat,
207
- },
208
- // Per-request abort: a Stop tears the in-flight SSE request down.
209
- { signal: params.signal },
210
- )
274
+ let stream: Awaited<ReturnType<typeof this.client.chat.completions.create>>
275
+ try {
276
+ stream = await this.client.chat.completions.create(
277
+ {
278
+ model,
279
+ messages: toOpenAIMessages(params.messages),
280
+ stream: true,
281
+ stream_options: { include_usage: true },
282
+ tools: toOpenAITools(params),
283
+ tool_choice: formatToolChoice(params.toolChoice),
284
+ parallel_tool_calls: params.parallelToolCalls,
285
+ temperature: params.temperature,
286
+ max_tokens: params.maxTokens,
287
+ top_p: params.topP,
288
+ frequency_penalty: params.frequencyPenalty,
289
+ presence_penalty: params.presencePenalty,
290
+ stop: params.stop,
291
+ response_format: params.responseFormat,
292
+ },
293
+ // Per-request abort: a Stop tears the in-flight SSE request down.
294
+ { signal: params.signal },
295
+ )
296
+ } catch (err) {
297
+ // The vendor SDK builds its error message FROM the response body, so a
298
+ // credential the upstream echoed back is already inside `err.message`
299
+ // before this code runs (proven with a planted fake token). Classify from
300
+ // the status and drop the vendor error entirely — no re-throw, no
301
+ // `cause`, because a `cause` is exactly what a structured logger walks.
302
+ if (isCallerAbortError(err, params.signal)) throw params.signal?.reason ?? err
303
+ if (isProviderRequestError(err)) throw err
304
+ throw providerVendorError({ providerId: 'openai', error: err })
305
+ }
211
306
 
212
- for await (const chunk of stream) {
213
- // Stop pulling promptly on abort; `for await` calls the stream's
214
- // `.return()` on this throw, releasing the connection.
215
- params.signal?.throwIfAborted()
216
- try {
217
- const choice = chunk.choices[0]
218
- const delta = choice?.delta
307
+ try {
308
+ for await (const chunk of stream) {
309
+ // Stop pulling promptly on abort; `for await` calls the stream's
310
+ // `.return()` on this throw, releasing the connection.
311
+ params.signal?.throwIfAborted()
312
+ try {
313
+ const choice = chunk.choices[0]
314
+ const delta = choice?.delta
219
315
 
220
- const toolCalls = delta?.tool_calls?.map((tc) => ({
221
- index: tc.index,
222
- id: tc.id,
223
- type: tc.type,
224
- function: tc.function
225
- ? {
226
- name: tc.function.name,
227
- arguments: tc.function.arguments,
228
- }
229
- : undefined,
230
- }))
316
+ const toolCalls = delta?.tool_calls?.map((tc) => ({
317
+ index: tc.index,
318
+ id: tc.id,
319
+ type: tc.type,
320
+ function: tc.function
321
+ ? {
322
+ name: tc.function.name,
323
+ arguments: tc.function.arguments,
324
+ }
325
+ : undefined,
326
+ }))
231
327
 
232
- const hasDelta =
233
- (delta?.content !== undefined && delta.content !== null) ||
234
- (toolCalls && toolCalls.length > 0)
235
- const finishReason = choice?.finish_reason
236
- ? mapFinishReason(choice.finish_reason)
237
- : undefined
238
- const usage = chunk.usage ? parseUsage(chunk.usage) : undefined
328
+ const hasDelta =
329
+ (delta?.content !== undefined && delta.content !== null) ||
330
+ (toolCalls && toolCalls.length > 0)
331
+ const finishReason = choice?.finish_reason
332
+ ? mapFinishReason(choice.finish_reason)
333
+ : undefined
334
+ const usage = chunk.usage ? parseUsage(chunk.usage) : undefined
239
335
 
240
- if (!hasDelta && !finishReason && !usage) continue
336
+ if (!hasDelta && !finishReason && !usage) continue
241
337
 
242
- yield {
243
- id: chunk.id,
244
- delta: {
245
- content: delta?.content ?? undefined,
246
- toolCalls,
247
- },
248
- finishReason,
249
- usage,
250
- }
251
- } catch (parseErr) {
252
- yield {
253
- id: chunk.id ?? '',
254
- delta: {},
255
- error: `Stream parse error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
338
+ yield {
339
+ id: chunk.id,
340
+ delta: {
341
+ content: delta?.content ?? undefined,
342
+ toolCalls,
343
+ },
344
+ finishReason,
345
+ usage,
346
+ }
347
+ } catch (parseErr) {
348
+ if (isProviderRequestError(parseErr)) throw parseErr
349
+ throw new ProviderRequestError({
350
+ kind: 'server',
351
+ providerId: 'openai',
352
+ detail: 'the provider stream returned malformed data',
353
+ })
256
354
  }
257
355
  }
356
+ } catch (err) {
357
+ if (isCallerAbortError(err, params.signal)) throw params.signal?.reason ?? err
358
+ if (isProviderRequestError(err)) throw err
359
+ throw providerVendorError({ providerId: 'openai', error: err })
258
360
  }
259
361
  }
260
362
 
File without changes