@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
@@ -0,0 +1,125 @@
1
+ import type { ChatCompletionParams } from '@namzu/sdk'
2
+ import { describe, expect, it } from 'vitest'
3
+
4
+ import { OPENAI_CAPABILITIES, toOpenAIMessages } from '../client.js'
5
+
6
+ /**
7
+ * This driver declared `supportsDocuments: true` and had no document
8
+ * branch: every attachment became an `image_url` part, so a PDF went up as
9
+ * `data:application/pdf;base64,...` inside an image. The capability was a
10
+ * claim nothing in the mapper could honour.
11
+ *
12
+ * Citations are the other half, and this wire has no way to return them.
13
+ * Sending the document anyway would answer the question and drop the
14
+ * checkability the caller asked for — silently, since an empty citation
15
+ * list reads as "the model cited nothing" rather than "nobody asked". So a
16
+ * document requesting citations is refused here rather than degraded.
17
+ */
18
+
19
+ const PDF = 'JVBERi0xLjQKJSVFT0Y='
20
+
21
+ function partsFor(attachments: unknown[], content = 'summarize this') {
22
+ const [message] = toOpenAIMessages([
23
+ { role: 'user', content, attachments },
24
+ ] as unknown as ChatCompletionParams['messages'])
25
+ return message?.content as unknown as Record<string, unknown>[]
26
+ }
27
+
28
+ describe('a document attachment reaches the wire as a file', () => {
29
+ it('sends a file part, not an image part', async () => {
30
+ const parts = partsFor([{ type: 'document', data: PDF, mediaType: 'application/pdf' }])
31
+
32
+ const file = parts.find((p) => p.type === 'file')
33
+ expect(file?.file).toMatchObject({ file_data: `data:application/pdf;base64,${PDF}` })
34
+ // The bug in one assertion: it used to be an image part.
35
+ expect(parts.some((p) => p.type === 'image_url')).toBe(false)
36
+ })
37
+
38
+ it('keeps the prose ahead of the file', () => {
39
+ const parts = partsFor([{ type: 'document', data: PDF, mediaType: 'application/pdf' }])
40
+
41
+ expect(parts[0]).toEqual({ type: 'text', text: 'summarize this' })
42
+ })
43
+
44
+ it('carries the filename when one was given', () => {
45
+ const parts = partsFor([
46
+ { type: 'document', data: PDF, mediaType: 'application/pdf', name: 'lease.pdf' },
47
+ ])
48
+
49
+ expect((parts.find((p) => p.type === 'file')?.file as { filename?: string }).filename).toBe(
50
+ 'lease.pdf',
51
+ )
52
+ })
53
+
54
+ it('omits the filename when none was given', () => {
55
+ const parts = partsFor([{ type: 'document', data: PDF, mediaType: 'application/pdf' }])
56
+
57
+ expect(parts.find((p) => p.type === 'file')?.file).not.toHaveProperty('filename')
58
+ })
59
+
60
+ it('still maps an image attachment as an image', () => {
61
+ const parts = partsFor([{ type: 'image', data: 'AAAA', mediaType: 'image/png' }])
62
+
63
+ expect(parts.find((p) => p.type === 'image_url')?.image_url).toEqual({
64
+ url: 'data:image/png;base64,AAAA',
65
+ })
66
+ expect(parts.some((p) => p.type === 'file')).toBe(false)
67
+ })
68
+
69
+ it('carries both kinds in one message, in the order given', () => {
70
+ const parts = partsFor([
71
+ { type: 'document', data: PDF, mediaType: 'application/pdf' },
72
+ { type: 'image', data: 'AAAA', mediaType: 'image/png' },
73
+ ])
74
+
75
+ expect(parts.map((p) => p.type)).toEqual(['text', 'file', 'image_url'])
76
+ })
77
+
78
+ it('leaves a plain text message as a string', () => {
79
+ const [message] = toOpenAIMessages([
80
+ { role: 'user', content: 'no attachments here' },
81
+ ] as ChatCompletionParams['messages'])
82
+
83
+ expect(message?.content).toBe('no attachments here')
84
+ })
85
+ })
86
+
87
+ describe('a document asking for citations is refused, not answered without them', () => {
88
+ it('throws rather than sending it', () => {
89
+ expect(() =>
90
+ partsFor([{ type: 'document', data: PDF, mediaType: 'application/pdf', citations: true }]),
91
+ ).toThrow(/citations/i)
92
+ })
93
+
94
+ it('names the document, so the caller knows which one to change', () => {
95
+ expect(() =>
96
+ partsFor([
97
+ {
98
+ type: 'document',
99
+ data: PDF,
100
+ mediaType: 'application/pdf',
101
+ name: 'lease.pdf',
102
+ citations: true,
103
+ },
104
+ ]),
105
+ ).toThrow(/lease\.pdf/)
106
+ })
107
+
108
+ it('says what to do instead', () => {
109
+ expect(() =>
110
+ partsFor([{ type: 'document', data: PDF, mediaType: 'application/pdf', citations: true }]),
111
+ ).toThrow(/Drop `citations`/)
112
+ })
113
+
114
+ it('accepts the same document without the request', () => {
115
+ expect(() =>
116
+ partsFor([{ type: 'document', data: PDF, mediaType: 'application/pdf', citations: false }]),
117
+ ).not.toThrow()
118
+ })
119
+ })
120
+
121
+ describe('the capability claim matches the mapper', () => {
122
+ it('declares document support, which is now true', () => {
123
+ expect(OPENAI_CAPABILITIES.supportsDocuments).toBe(true)
124
+ })
125
+ })
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Provider error taxonomy — OpenAI driver.
3
+ *
4
+ * Like the Anthropic driver, this one lets the vendor SDK's own error type
5
+ * escape verbatim (`RateLimitError`, `BadRequestError`, …). Those carry a
6
+ * status but are vendor classes, so no caller can classify them without
7
+ * importing `openai` — and their `message` interpolates the response body.
8
+ *
9
+ * Transport seam: `OpenAIConfig.baseURL` — a loopback server answering
10
+ * with a scripted status/headers/body, so the REAL vendor client runs
11
+ * (including its internal retries, which this group must not disturb).
12
+ */
13
+
14
+ import { type Server, createServer } from 'node:http'
15
+ import type { AddressInfo } from 'node:net'
16
+ import { afterEach, describe, expect, it } from 'vitest'
17
+ import { OpenAIProvider } from '../client.js'
18
+
19
+ /** Obviously fake, non-functional token — present only as a leak probe. */
20
+ const FAKE_CREDENTIAL = 'sk-ant-FAKE-DO-NOT-USE-0000'
21
+
22
+ interface ScriptedReply {
23
+ status: number
24
+ body: string
25
+ headers?: Record<string, string>
26
+ }
27
+
28
+ let server: Server | undefined
29
+
30
+ afterEach(async () => {
31
+ if (server) {
32
+ await new Promise<void>((resolve) => server?.close(() => resolve()))
33
+ server = undefined
34
+ }
35
+ })
36
+
37
+ async function startEndpoint(reply: ScriptedReply): Promise<string> {
38
+ server = createServer((_req, res) => {
39
+ res.writeHead(reply.status, {
40
+ 'Content-Type': 'application/json',
41
+ ...(reply.headers ?? {}),
42
+ })
43
+ res.end(reply.body)
44
+ })
45
+ await new Promise<void>((resolve) => server?.listen(0, '127.0.0.1', () => resolve()))
46
+ const { port } = server.address() as AddressInfo
47
+ return `http://127.0.0.1:${port}/v1`
48
+ }
49
+
50
+ async function captureChatStreamError(reply: ScriptedReply): Promise<unknown> {
51
+ const baseURL = await startEndpoint(reply)
52
+ // maxRetries is deliberately NOT set: this group classifies errors and
53
+ // must leave the vendor SDK's own retry behaviour exactly as it is.
54
+ const provider = new OpenAIProvider({
55
+ apiKey: 'test-key',
56
+ model: 'gpt-4o-mini',
57
+ baseURL,
58
+ })
59
+ try {
60
+ for await (const _chunk of provider.chatStream({
61
+ model: 'gpt-4o-mini',
62
+ messages: [{ role: 'user', content: 'hi' }],
63
+ })) {
64
+ // drain
65
+ }
66
+ } catch (err) {
67
+ return err
68
+ }
69
+ throw new Error('expected chatStream to throw')
70
+ }
71
+
72
+ async function captureProviderError(
73
+ provider: OpenAIProvider,
74
+ signal?: AbortSignal,
75
+ ): Promise<unknown> {
76
+ try {
77
+ for await (const _chunk of provider.chatStream({
78
+ model: 'gpt-4o-mini',
79
+ messages: [{ role: 'user', content: 'hi' }],
80
+ signal,
81
+ })) {
82
+ // drain
83
+ }
84
+ } catch (err) {
85
+ return err
86
+ }
87
+ throw new Error('expected chatStream to throw')
88
+ }
89
+
90
+ describe('@namzu/openai — provider error taxonomy', () => {
91
+ it('(a) 429 with `retry-after: 2` throws a throttle-classified error carrying retryAfterMs', async () => {
92
+ const err = await captureChatStreamError({
93
+ status: 429,
94
+ headers: { 'retry-after': '2' },
95
+ body: JSON.stringify({
96
+ error: { message: 'Rate limit reached', type: 'rate_limit_error' },
97
+ }),
98
+ })
99
+
100
+ expect(err).toMatchObject({
101
+ name: 'ProviderRequestError',
102
+ kind: 'throttle',
103
+ status: 429,
104
+ retryAfterMs: 2000,
105
+ providerId: 'openai',
106
+ })
107
+ }, 60_000)
108
+
109
+ it("(c) 400 whose body reports a context-length overflow classifies as 'context_overflow'", async () => {
110
+ const err = await captureChatStreamError({
111
+ status: 400,
112
+ body: JSON.stringify({
113
+ error: {
114
+ message:
115
+ "This model's maximum context length is 128000 tokens. However, your messages resulted in 190210 tokens.",
116
+ type: 'invalid_request_error',
117
+ code: 'context_length_exceeded',
118
+ },
119
+ }),
120
+ })
121
+
122
+ expect(err).toMatchObject({
123
+ name: 'ProviderRequestError',
124
+ kind: 'context_overflow',
125
+ status: 400,
126
+ providerId: 'openai',
127
+ })
128
+ }, 30_000)
129
+
130
+ it("(c) 400 that is not an overflow classifies as 'bad_request'", async () => {
131
+ const err = await captureChatStreamError({
132
+ status: 400,
133
+ body: JSON.stringify({
134
+ error: {
135
+ message: "Unrecognized request argument: 'temperture'",
136
+ type: 'invalid_request_error',
137
+ },
138
+ }),
139
+ })
140
+
141
+ expect(err).toMatchObject({
142
+ name: 'ProviderRequestError',
143
+ kind: 'bad_request',
144
+ status: 400,
145
+ providerId: 'openai',
146
+ })
147
+ }, 30_000)
148
+
149
+ it("(auth) 401 classifies as 'auth'", async () => {
150
+ const err = await captureChatStreamError({
151
+ status: 401,
152
+ body: JSON.stringify({
153
+ error: {
154
+ message: 'Incorrect API key provided',
155
+ type: 'invalid_request_error',
156
+ },
157
+ }),
158
+ })
159
+
160
+ expect(err).toMatchObject({
161
+ name: 'ProviderRequestError',
162
+ kind: 'auth',
163
+ status: 401,
164
+ providerId: 'openai',
165
+ })
166
+ }, 30_000)
167
+
168
+ it('(d) SECURITY: a credential echoed back in a 401 body never reaches the thrown message', async () => {
169
+ const err = await captureChatStreamError({
170
+ status: 401,
171
+ body: JSON.stringify({
172
+ error: { message: `Incorrect API key provided: ${FAKE_CREDENTIAL}` },
173
+ }),
174
+ })
175
+
176
+ expect((err as Error).message).not.toContain(FAKE_CREDENTIAL)
177
+ expect(JSON.stringify(err)).not.toContain(FAKE_CREDENTIAL)
178
+ expect('cause' in (err as object)).toBe(false)
179
+ }, 30_000)
180
+
181
+ it('classifies and sanitizes an SDK failure thrown after streaming began', async () => {
182
+ const vendor = Object.assign(new Error(`overloaded_error ${FAKE_CREDENTIAL}`), {
183
+ name: 'APIError',
184
+ })
185
+ const provider = new OpenAIProvider({
186
+ apiKey: 'test-key',
187
+ model: 'gpt-4o-mini',
188
+ })
189
+ const stream = {
190
+ async *[Symbol.asyncIterator]() {
191
+ yield {
192
+ id: 'chatcmpl-1',
193
+ choices: [{ delta: { content: 'partial' }, finish_reason: null }],
194
+ usage: null,
195
+ }
196
+ throw vendor
197
+ },
198
+ }
199
+ ;(provider as unknown as { client: unknown }).client = {
200
+ chat: { completions: { create: async () => stream } },
201
+ }
202
+
203
+ const err = await captureProviderError(provider)
204
+
205
+ expect(err).toMatchObject({
206
+ name: 'ProviderRequestError',
207
+ kind: 'server',
208
+ providerId: 'openai',
209
+ })
210
+ expect((err as Error).message).not.toContain(FAKE_CREDENTIAL)
211
+ expect('cause' in (err as object)).toBe(false)
212
+ })
213
+
214
+ it('preserves the caller abort reason when the SDK replaces the error object', async () => {
215
+ const controller = new AbortController()
216
+ const reason = new Error('user stopped')
217
+ const sdkAbort = Object.assign(new Error('request aborted'), {
218
+ name: 'APIUserAbortError',
219
+ })
220
+ controller.abort(reason)
221
+ const provider = new OpenAIProvider({
222
+ apiKey: 'test-key',
223
+ model: 'gpt-4o-mini',
224
+ })
225
+ ;(provider as unknown as { client: unknown }).client = {
226
+ chat: { completions: { create: async () => Promise.reject(sdkAbort) } },
227
+ }
228
+
229
+ const err = await captureProviderError(provider, controller.signal)
230
+
231
+ expect(sdkAbort).not.toBe(reason)
232
+ expect(err).toBe(reason)
233
+ })
234
+ })
@@ -47,6 +47,7 @@ describe('@namzu/openai', () => {
47
47
  supportsStreaming: true,
48
48
  supportsFunctionCalling: true,
49
49
  supportsVision: true,
50
+ supportsDocuments: true,
50
51
  })
51
52
  })
52
53
 
@@ -97,8 +98,14 @@ describe('@namzu/openai', () => {
97
98
  role: 'user',
98
99
  content: [
99
100
  { type: 'text', text: 'what is in this image?' },
100
- { type: 'image_url', image_url: { url: 'data:image/png;base64,aGVsbG8=' } },
101
- { type: 'image_url', image_url: { url: 'data:image/jpeg;base64,d29ybGQ=' } },
101
+ {
102
+ type: 'image_url',
103
+ image_url: { url: 'data:image/png;base64,aGVsbG8=' },
104
+ },
105
+ {
106
+ type: 'image_url',
107
+ image_url: { url: 'data:image/jpeg;base64,d29ybGQ=' },
108
+ },
102
109
  ],
103
110
  })
104
111
  })
@@ -115,7 +122,12 @@ describe('@namzu/openai', () => {
115
122
  const [mapped] = toOpenAIMessages(messages)
116
123
  expect(mapped).toEqual({
117
124
  role: 'user',
118
- content: [{ type: 'image_url', image_url: { url: 'data:image/webp;base64,aGVsbG8=' } }],
125
+ content: [
126
+ {
127
+ type: 'image_url',
128
+ image_url: { url: 'data:image/webp;base64,aGVsbG8=' },
129
+ },
130
+ ],
119
131
  })
120
132
  })
121
133
 
@@ -124,4 +136,66 @@ describe('@namzu/openai', () => {
124
136
  expect(toOpenAIMessages(messages)).toEqual([{ role: 'user', content: 'hello' }])
125
137
  })
126
138
  })
139
+
140
+ it('keeps the Namzu enforcement hint out of the OpenAI SDK request', async () => {
141
+ const provider = new OpenAIProvider({ apiKey: 'test-key' })
142
+ let requestBody: Record<string, unknown> | undefined
143
+ ;(provider as unknown as { client: unknown }).client = {
144
+ chat: {
145
+ completions: {
146
+ create: async (body: Record<string, unknown>) => {
147
+ requestBody = body
148
+ return (async function* () {
149
+ yield {
150
+ id: 'msg_done',
151
+ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
152
+ usage: {
153
+ prompt_tokens: 1,
154
+ completion_tokens: 0,
155
+ total_tokens: 1,
156
+ },
157
+ }
158
+ })()
159
+ },
160
+ },
161
+ },
162
+ }
163
+ const tools = [
164
+ {
165
+ type: 'function' as const,
166
+ function: {
167
+ name: 'edit',
168
+ description: 'Edit',
169
+ parameters: { type: 'object' },
170
+ },
171
+ },
172
+ ]
173
+
174
+ for await (const _chunk of provider.chatStream({
175
+ model: 'gpt-5',
176
+ messages: [{ role: 'user', content: 'edit' }],
177
+ tools,
178
+ enforceToolInputSchema: ['edit'],
179
+ })) {
180
+ // Drain the test stream.
181
+ }
182
+
183
+ // The hint is not a wire field, so it must never appear verbatim —
184
+ // that is what "keeps it out of the request" means.
185
+ expect(requestBody).not.toHaveProperty('enforceToolInputSchema')
186
+ // It is consumed, not ignored. This used to assert the tools went
187
+ // through untouched, which read as "the hint is kept out" and
188
+ // actually pinned "the hint does nothing".
189
+ expect(requestBody?.tools).toEqual([
190
+ {
191
+ type: 'function',
192
+ function: {
193
+ name: 'edit',
194
+ description: 'Edit',
195
+ parameters: { type: 'object' },
196
+ strict: true,
197
+ },
198
+ },
199
+ ])
200
+ })
127
201
  })
@@ -0,0 +1,76 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { OPENAI_CAPABILITIES, assertThinkingSupported } from '../client.js'
4
+
5
+ /**
6
+ * This driver does not implement extended thinking, and used to accept the
7
+ * request anyway.
8
+ *
9
+ * So a caller who asked for reasoning got an ordinary completion: no
10
+ * thinking, no reasoning blocks, and no error. The empty reasoning list
11
+ * that came back reads as "the model did not reason" rather than "nobody
12
+ * asked it to" — which is the failure mode, not the missing feature. Same
13
+ * call as the citations one in this driver: refuse what cannot be
14
+ * delivered rather than deliver something else quietly.
15
+ */
16
+
17
+ describe('an extended-thinking request is refused, not dropped', () => {
18
+ it('throws when thinking is asked for', () => {
19
+ expect(() => assertThinkingSupported({ thinking: { type: 'enabled' } })).toThrow(
20
+ /extended thinking/i,
21
+ )
22
+ })
23
+
24
+ it('says what to do instead', () => {
25
+ expect(() => assertThinkingSupported({ thinking: { type: 'enabled' } })).toThrow(
26
+ /Drop `thinking`/,
27
+ )
28
+ })
29
+
30
+ it('explains why silence would be worse than an error', () => {
31
+ // The message has to name the symptom the caller would otherwise
32
+ // see, or they will read the empty list as an answer.
33
+ expect(() => assertThinkingSupported({ thinking: { type: 'enabled' } })).toThrow(
34
+ /empty reasoning list/,
35
+ )
36
+ })
37
+ })
38
+
39
+ describe('asking for it to be off is honoured as a no-op', () => {
40
+ it('accepts an explicit disable', () => {
41
+ // Off is the state this driver is already in, so refusing here would
42
+ // reject a request it is in fact satisfying.
43
+ expect(() => assertThinkingSupported({ thinking: { type: 'disabled' } })).not.toThrow()
44
+ })
45
+
46
+ it('accepts a call that says nothing about thinking', () => {
47
+ expect(() => assertThinkingSupported({})).not.toThrow()
48
+ })
49
+ })
50
+
51
+ describe('the declared capabilities stay honest', () => {
52
+ it('claims the tools and streaming it does implement', () => {
53
+ expect(OPENAI_CAPABILITIES.supportsTools).toBe(true)
54
+ expect(OPENAI_CAPABILITIES.supportsStreaming).toBe(true)
55
+ expect(OPENAI_CAPABILITIES.supportsFunctionCalling).toBe(true)
56
+ })
57
+
58
+ it('claims the vision and documents it now maps', () => {
59
+ expect(OPENAI_CAPABILITIES.supportsVision).toBe(true)
60
+ expect(OPENAI_CAPABILITIES.supportsDocuments).toBe(true)
61
+ })
62
+
63
+ it('answers every flag the negotiation reads', () => {
64
+ // An absent flag defaults to permissive, so a missing one is not a
65
+ // neutral omission — it is a claim.
66
+ for (const flag of [
67
+ 'supportsTools',
68
+ 'supportsStreaming',
69
+ 'supportsFunctionCalling',
70
+ 'supportsVision',
71
+ 'supportsDocuments',
72
+ ] as const) {
73
+ expect(typeof OPENAI_CAPABILITIES[flag]).toBe('boolean')
74
+ }
75
+ })
76
+ })
@@ -0,0 +1,110 @@
1
+ import type { ChatCompletionParams } from '@namzu/sdk'
2
+ import { describe, expect, it } from 'vitest'
3
+
4
+ import { toOpenAITools } from '../client.js'
5
+
6
+ /**
7
+ * `enforceToolInputSchema` names the tools whose model-facing schema should
8
+ * be enforced by constrained generation rather than merely suggested.
9
+ *
10
+ * Both sibling drivers consumed it. This one dropped it on the floor, so a
11
+ * caller who had asked for a guaranteed-valid tool input silently got a
12
+ * best-effort one, and learned about it from a repair attempt rather than
13
+ * from an error. This is the wire the flag maps onto most directly — it
14
+ * takes the flag on the function itself.
15
+ */
16
+
17
+ const TOOLS = [
18
+ {
19
+ type: 'function' as const,
20
+ function: {
21
+ name: 'read',
22
+ description: 'read a file',
23
+ parameters: { type: 'object', properties: { path: { type: 'string' } } },
24
+ },
25
+ },
26
+ {
27
+ type: 'function' as const,
28
+ function: { name: 'write', description: 'write a file', parameters: { type: 'object' } },
29
+ },
30
+ ]
31
+
32
+ type FunctionTool = {
33
+ function: { name: string; description?: string; parameters?: unknown; strict?: boolean }
34
+ }
35
+
36
+ function toolsFor(enforceToolInputSchema?: readonly string[]): FunctionTool[] | undefined {
37
+ return toOpenAITools({
38
+ model: 'm',
39
+ messages: [],
40
+ tools: TOOLS,
41
+ ...(enforceToolInputSchema ? { enforceToolInputSchema } : {}),
42
+ } as ChatCompletionParams) as unknown as FunctionTool[] | undefined
43
+ }
44
+
45
+ describe('the schema of a named tool is enforced, not suggested', () => {
46
+ it('marks the tool the caller named', () => {
47
+ const tools = toolsFor(['read'])
48
+
49
+ expect(tools?.find((t) => t.function.name === 'read')?.function.strict).toBe(true)
50
+ })
51
+
52
+ it('leaves every other tool alone', () => {
53
+ const tools = toolsFor(['read'])
54
+
55
+ // Enforcement is not free and not always possible; marking a tool
56
+ // nobody asked about changes behaviour the caller did not ask to
57
+ // change.
58
+ expect(tools?.find((t) => t.function.name === 'write')?.function).not.toHaveProperty('strict')
59
+ })
60
+
61
+ it('marks several when several were named', () => {
62
+ const tools = toolsFor(['read', 'write'])
63
+
64
+ expect(tools?.every((t) => t.function.strict === true)).toBe(true)
65
+ })
66
+
67
+ it('marks nothing when the hint is absent', () => {
68
+ expect(toolsFor()?.some((t) => 'strict' in t.function)).toBe(false)
69
+ })
70
+
71
+ it('marks nothing when the hint names no tool', () => {
72
+ expect(toolsFor([])?.some((t) => 'strict' in t.function)).toBe(false)
73
+ })
74
+
75
+ it('ignores a name that matches no registered tool', () => {
76
+ const tools = toolsFor(['nonexistent'])
77
+
78
+ expect(tools).toHaveLength(2)
79
+ expect(tools?.some((t) => 'strict' in t.function)).toBe(false)
80
+ })
81
+ })
82
+
83
+ describe('the rest of the tool schema is untouched', () => {
84
+ it('keeps the name, description and parameters', () => {
85
+ const read = toolsFor(['read'])?.find((t) => t.function.name === 'read')
86
+
87
+ expect(read?.function.description).toBe('read a file')
88
+ expect(read?.function.parameters).toMatchObject({
89
+ type: 'object',
90
+ properties: { path: { type: 'string' } },
91
+ })
92
+ })
93
+
94
+ it('substitutes an empty object for missing parameters', () => {
95
+ const tools = toOpenAITools({
96
+ model: 'm',
97
+ messages: [],
98
+ tools: [{ type: 'function', function: { name: 'ping' } }],
99
+ } as unknown as ChatCompletionParams) as unknown as FunctionTool[]
100
+
101
+ expect(tools?.[0]?.function.parameters).toEqual({})
102
+ })
103
+
104
+ it('sends no tools at all when there are none', () => {
105
+ expect(toOpenAITools({ model: 'm', messages: [] } as ChatCompletionParams)).toBeUndefined()
106
+ expect(
107
+ toOpenAITools({ model: 'm', messages: [], tools: [] } as ChatCompletionParams),
108
+ ).toBeUndefined()
109
+ })
110
+ })