@effect/ai-openai-compat 4.0.0-beta.10 → 4.0.0-beta.100

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 (41) hide show
  1. package/dist/OpenAiClient.d.ts +264 -52
  2. package/dist/OpenAiClient.d.ts.map +1 -1
  3. package/dist/OpenAiClient.js +97 -9
  4. package/dist/OpenAiClient.js.map +1 -1
  5. package/dist/OpenAiConfig.d.ts +68 -10
  6. package/dist/OpenAiConfig.d.ts.map +1 -1
  7. package/dist/OpenAiConfig.js +36 -7
  8. package/dist/OpenAiConfig.js.map +1 -1
  9. package/dist/OpenAiEmbeddingModel.d.ts +193 -0
  10. package/dist/OpenAiEmbeddingModel.d.ts.map +1 -0
  11. package/dist/OpenAiEmbeddingModel.js +187 -0
  12. package/dist/OpenAiEmbeddingModel.js.map +1 -0
  13. package/dist/OpenAiError.d.ts +109 -35
  14. package/dist/OpenAiError.d.ts.map +1 -1
  15. package/dist/OpenAiError.js +14 -1
  16. package/dist/OpenAiLanguageModel.d.ts +363 -50
  17. package/dist/OpenAiLanguageModel.d.ts.map +1 -1
  18. package/dist/OpenAiLanguageModel.js +158 -33
  19. package/dist/OpenAiLanguageModel.js.map +1 -1
  20. package/dist/OpenAiTelemetry.d.ts +76 -26
  21. package/dist/OpenAiTelemetry.d.ts.map +1 -1
  22. package/dist/OpenAiTelemetry.js +22 -10
  23. package/dist/OpenAiTelemetry.js.map +1 -1
  24. package/dist/index.d.ts +10 -17
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +10 -17
  27. package/dist/index.js.map +1 -1
  28. package/dist/internal/errors.js +4 -4
  29. package/dist/internal/errors.js.map +1 -1
  30. package/dist/internal/utilities.js +0 -6
  31. package/dist/internal/utilities.js.map +1 -1
  32. package/package.json +5 -6
  33. package/src/OpenAiClient.ts +273 -50
  34. package/src/OpenAiConfig.ts +69 -11
  35. package/src/OpenAiEmbeddingModel.ts +322 -0
  36. package/src/OpenAiError.ts +111 -35
  37. package/src/OpenAiLanguageModel.ts +468 -88
  38. package/src/OpenAiTelemetry.ts +81 -32
  39. package/src/index.ts +11 -17
  40. package/src/internal/errors.ts +4 -4
  41. package/src/internal/utilities.ts +0 -9
@@ -1,21 +1,24 @@
1
1
  /**
2
- * OpenAI Language Model implementation.
2
+ * The `OpenAiLanguageModel` module adapts OpenAI-compatible chat completions
3
+ * providers to Effect AI's `LanguageModel` service. It builds a model service
4
+ * from a model id, translates prompts, files, tools, structured output schemas,
5
+ * and provider-specific options into `OpenAiClient` requests, and maps normal
6
+ * or streaming chat completion results back into Effect AI response content and
7
+ * metadata.
3
8
  *
4
- * Provides a LanguageModel implementation for OpenAI's chat completions API,
5
- * supporting text generation, structured output, tool calling, and streaming.
6
- *
7
- * @since 1.0.0
9
+ * @since 4.0.0
8
10
  */
11
+ import * as Context from "effect/Context"
9
12
  import * as DateTime from "effect/DateTime"
10
13
  import * as Effect from "effect/Effect"
11
14
  import * as Encoding from "effect/Encoding"
12
15
  import { dual } from "effect/Function"
13
16
  import * as Layer from "effect/Layer"
17
+ import * as Option from "effect/Option"
14
18
  import * as Predicate from "effect/Predicate"
15
19
  import * as Redactable from "effect/Redactable"
16
20
  import type * as Schema from "effect/Schema"
17
21
  import * as AST from "effect/SchemaAST"
18
- import * as ServiceMap from "effect/ServiceMap"
19
22
  import * as Stream from "effect/Stream"
20
23
  import type { Span } from "effect/Tracer"
21
24
  import type { DeepMutable, Simplify } from "effect/Types"
@@ -57,52 +60,60 @@ type ImageDetail = "auto" | "low" | "high"
57
60
  // Configuration
58
61
  // =============================================================================
59
62
 
63
+ type ConfigOptions = Simplify<
64
+ & Partial<
65
+ Omit<CreateResponse, "input" | "tools" | "tool_choice" | "stream" | "text">
66
+ >
67
+ & {
68
+ /**
69
+ * File ID prefixes used to identify file IDs in Responses API.
70
+ * When undefined, all file data is treated as base64 content.
71
+ *
72
+ * Examples:
73
+ * - OpenAI: ['file-'] for IDs like 'file-abc123'
74
+ * - Azure OpenAI: ['assistant-'] for IDs like 'assistant-abc123'
75
+ */
76
+ readonly fileIdPrefixes?: ReadonlyArray<string> | undefined
77
+ /**
78
+ * Configuration options for a text response from the model.
79
+ */
80
+ readonly text?: {
81
+ /**
82
+ * Constrains the verbosity of the model's response. Lower values will
83
+ * result in more concise responses, while higher values will result in
84
+ * more verbose responses.
85
+ *
86
+ * Defaults to `"medium"`.
87
+ */
88
+ readonly verbosity?: "low" | "medium" | "high" | undefined
89
+ } | undefined
90
+ /**
91
+ * Whether to use strict JSON schema validation.
92
+ *
93
+ * Defaults to `true`.
94
+ */
95
+ readonly strictJsonSchema?: boolean | undefined
96
+ }
97
+ >
98
+ type ModelConfig = Omit<ConfigOptions, "model"> & { readonly [x: string]: unknown }
99
+
60
100
  /**
61
- * Service definition for OpenAI language model configuration.
101
+ * Context service for OpenAI language model configuration.
102
+ *
103
+ * **When to use**
104
+ *
105
+ * Use as the context service for OpenAI-compatible language model request
106
+ * configuration, especially when a scoped operation should override the defaults
107
+ * supplied to `model`, `make`, or `layer`.
108
+ *
109
+ * @see {@link withConfigOverride} for scoping language model request overrides
62
110
  *
63
- * @since 1.0.0
64
111
  * @category context
112
+ * @since 4.0.0
65
113
  */
66
- export class Config extends ServiceMap.Service<
114
+ export class Config extends Context.Service<
67
115
  Config,
68
- Simplify<
69
- & Partial<
70
- Omit<
71
- CreateResponse,
72
- "input" | "tools" | "tool_choice" | "stream" | "text"
73
- >
74
- >
75
- & {
76
- /**
77
- * File ID prefixes used to identify file IDs in Responses API.
78
- * When undefined, all file data is treated as base64 content.
79
- *
80
- * Examples:
81
- * - OpenAI: ['file-'] for IDs like 'file-abc123'
82
- * - Azure OpenAI: ['assistant-'] for IDs like 'assistant-abc123'
83
- */
84
- readonly fileIdPrefixes?: ReadonlyArray<string> | undefined
85
- /**
86
- * Configuration options for a text response from the model.
87
- */
88
- readonly text?: {
89
- /**
90
- * Constrains the verbosity of the model's response. Lower values will
91
- * result in more concise responses, while higher values will result in
92
- * more verbose responses.
93
- *
94
- * Defaults to `"medium"`.
95
- */
96
- readonly verbosity?: "low" | "medium" | "high" | undefined
97
- } | undefined
98
- /**
99
- * Whether to use strict JSON schema validation.
100
- *
101
- * Defaults to `true`.
102
- */
103
- readonly strictJsonSchema?: boolean | undefined
104
- }
105
- >
116
+ ConfigOptions & { readonly [x: string]: unknown }
106
117
  >()("@effect/ai-openai-compat/OpenAiLanguageModel/Config") {}
107
118
 
108
119
  // =============================================================================
@@ -110,7 +121,16 @@ export class Config extends ServiceMap.Service<
110
121
  // =============================================================================
111
122
 
112
123
  declare module "effect/unstable/ai/Prompt" {
124
+ /**
125
+ * OpenAI-compatible options for file prompt parts.
126
+ *
127
+ * @category request
128
+ * @since 4.0.0
129
+ */
113
130
  export interface FilePartOptions extends ProviderOptions {
131
+ /**
132
+ * Provider-specific file options for OpenAI-compatible APIs.
133
+ */
114
134
  readonly openai?: {
115
135
  /**
116
136
  * The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`.
@@ -119,7 +139,16 @@ declare module "effect/unstable/ai/Prompt" {
119
139
  } | null
120
140
  }
121
141
 
142
+ /**
143
+ * OpenAI-compatible options for reasoning prompt parts.
144
+ *
145
+ * @category request
146
+ * @since 4.0.0
147
+ */
122
148
  export interface ReasoningPartOptions extends ProviderOptions {
149
+ /**
150
+ * Provider-specific reasoning options for OpenAI-compatible APIs.
151
+ */
123
152
  readonly openai?: {
124
153
  /**
125
154
  * The ID of the item to reference.
@@ -134,40 +163,67 @@ declare module "effect/unstable/ai/Prompt" {
134
163
  } | null
135
164
  }
136
165
 
166
+ /**
167
+ * OpenAI-compatible options for assistant tool-call prompt parts.
168
+ *
169
+ * @category request
170
+ * @since 4.0.0
171
+ */
137
172
  export interface ToolCallPartOptions extends ProviderOptions {
173
+ /**
174
+ * Provider-specific tool-call options for OpenAI-compatible APIs.
175
+ */
138
176
  readonly openai?: {
139
177
  /**
140
178
  * The ID of the item to reference.
141
179
  */
142
180
  readonly itemId?: string | null
143
181
  /**
144
- * The status of item.
182
+ * The status to send for the tool-call item.
145
183
  */
146
184
  readonly status?: MessageStatus | null
147
185
  } | null
148
186
  }
149
187
 
188
+ /**
189
+ * OpenAI-compatible options for tool-result prompt parts.
190
+ *
191
+ * @category request
192
+ * @since 4.0.0
193
+ */
150
194
  export interface ToolResultPartOptions extends ProviderOptions {
195
+ /**
196
+ * Provider-specific tool-result options for OpenAI-compatible APIs.
197
+ */
151
198
  readonly openai?: {
152
199
  /**
153
200
  * The ID of the item to reference.
154
201
  */
155
202
  readonly itemId?: string | null
156
203
  /**
157
- * The status of item.
204
+ * The status to send for the tool-result item.
158
205
  */
159
206
  readonly status?: MessageStatus | null
160
207
  } | null
161
208
  }
162
209
 
210
+ /**
211
+ * OpenAI-compatible options for text prompt parts.
212
+ *
213
+ * @category request
214
+ * @since 4.0.0
215
+ */
163
216
  export interface TextPartOptions extends ProviderOptions {
217
+ /**
218
+ * Provider-specific text options for OpenAI-compatible APIs.
219
+ */
164
220
  readonly openai?: {
165
221
  /**
166
222
  * The ID of the item to reference.
167
223
  */
168
224
  readonly itemId?: string | null
169
225
  /**
170
- * The status of item.
226
+ * The status to send for the text item.
171
227
  */
172
228
  readonly status?: MessageStatus | null
173
229
  /**
@@ -179,8 +235,20 @@ declare module "effect/unstable/ai/Prompt" {
179
235
  }
180
236
 
181
237
  declare module "effect/unstable/ai/Response" {
238
+ /**
239
+ * OpenAI-compatible metadata attached to a complete text response part.
240
+ *
241
+ * @category response
242
+ * @since 4.0.0
243
+ */
182
244
  export interface TextPartMetadata extends ProviderMetadata {
245
+ /**
246
+ * Provider-specific metadata returned for the text part.
247
+ */
183
248
  readonly openai?: {
249
+ /**
250
+ * The OpenAI item ID associated with the text part.
251
+ */
184
252
  readonly itemId?: string | null
185
253
  /**
186
254
  * If the model emits a refusal content part, the refusal explanation
@@ -189,7 +257,7 @@ declare module "effect/unstable/ai/Response" {
189
257
  */
190
258
  readonly refusal?: string | null
191
259
  /**
192
- * The status of item.
260
+ * The status returned for the text item.
193
261
  */
194
262
  readonly status?: MessageStatus | null
195
263
  /**
@@ -199,55 +267,163 @@ declare module "effect/unstable/ai/Response" {
199
267
  }
200
268
  }
201
269
 
270
+ /**
271
+ * OpenAI-compatible metadata emitted when a streamed text part starts.
272
+ *
273
+ * @category response
274
+ * @since 4.0.0
275
+ */
202
276
  export interface TextStartPartMetadata extends ProviderMetadata {
277
+ /**
278
+ * Provider-specific metadata returned for the streamed text start.
279
+ */
203
280
  readonly openai?: {
281
+ /**
282
+ * The OpenAI item ID associated with the streamed text part.
283
+ */
204
284
  readonly itemId?: string | null
205
285
  } | null
206
286
  }
207
287
 
288
+ /**
289
+ * OpenAI-compatible metadata emitted when a streamed text part ends.
290
+ *
291
+ * @category response
292
+ * @since 4.0.0
293
+ */
208
294
  export interface TextEndPartMetadata extends ProviderMetadata {
295
+ /**
296
+ * Provider-specific metadata returned for the streamed text end.
297
+ */
209
298
  readonly openai?: {
299
+ /**
300
+ * The OpenAI item ID associated with the streamed text part.
301
+ */
210
302
  readonly itemId?: string | null
303
+ /**
304
+ * The annotations collected for the completed streamed text part.
305
+ */
211
306
  readonly annotations?: ReadonlyArray<Annotation> | null
212
307
  } | null
213
308
  }
214
309
 
310
+ /**
311
+ * OpenAI-compatible metadata attached to a complete reasoning response part.
312
+ *
313
+ * @category response
314
+ * @since 4.0.0
315
+ */
215
316
  export interface ReasoningPartMetadata extends ProviderMetadata {
317
+ /**
318
+ * Provider-specific metadata returned for the reasoning part.
319
+ */
216
320
  readonly openai?: {
321
+ /**
322
+ * The OpenAI item ID associated with the reasoning part.
323
+ */
217
324
  readonly itemId?: string | null
325
+ /**
326
+ * Encrypted reasoning content that can be sent back in later requests.
327
+ */
218
328
  readonly encryptedContent?: string | null
219
329
  } | null
220
330
  }
221
331
 
332
+ /**
333
+ * OpenAI-compatible metadata emitted when a streamed reasoning part starts.
334
+ *
335
+ * @category response
336
+ * @since 4.0.0
337
+ */
222
338
  export interface ReasoningStartPartMetadata extends ProviderMetadata {
339
+ /**
340
+ * Provider-specific metadata returned for the streamed reasoning start.
341
+ */
223
342
  readonly openai?: {
343
+ /**
344
+ * The OpenAI item ID associated with the reasoning part.
345
+ */
224
346
  readonly itemId?: string | null
347
+ /**
348
+ * Encrypted reasoning content that can be sent back in later requests.
349
+ */
225
350
  readonly encryptedContent?: string | null
226
351
  } | null
227
352
  }
228
353
 
354
+ /**
355
+ * OpenAI-compatible metadata emitted for a streamed reasoning delta.
356
+ *
357
+ * @category response
358
+ * @since 4.0.0
359
+ */
229
360
  export interface ReasoningDeltaPartMetadata extends ProviderMetadata {
361
+ /**
362
+ * Provider-specific metadata returned for the streamed reasoning delta.
363
+ */
230
364
  readonly openai?: {
365
+ /**
366
+ * The OpenAI item ID associated with the reasoning part.
367
+ */
231
368
  readonly itemId?: string | null
232
369
  } | null
233
370
  }
234
371
 
372
+ /**
373
+ * OpenAI-compatible metadata emitted when a streamed reasoning part ends.
374
+ *
375
+ * @category response
376
+ * @since 4.0.0
377
+ */
235
378
  export interface ReasoningEndPartMetadata extends ProviderMetadata {
379
+ /**
380
+ * Provider-specific metadata returned for the streamed reasoning end.
381
+ */
236
382
  readonly openai?: {
383
+ /**
384
+ * The OpenAI item ID associated with the reasoning part.
385
+ */
237
386
  readonly itemId?: string | null
387
+ /**
388
+ * Encrypted reasoning content that can be sent back in later requests.
389
+ */
238
390
  readonly encryptedContent?: string
239
391
  } | null
240
392
  }
241
393
 
394
+ /**
395
+ * OpenAI-compatible metadata attached to tool-call response parts.
396
+ *
397
+ * @category response
398
+ * @since 4.0.0
399
+ */
242
400
  export interface ToolCallPartMetadata extends ProviderMetadata {
401
+ /**
402
+ * Provider-specific metadata returned for the tool call.
403
+ */
243
404
  readonly openai?: {
405
+ /**
406
+ * The OpenAI item ID associated with the tool call.
407
+ */
244
408
  readonly itemId?: string | null
245
409
  } | null
246
410
  }
247
411
 
412
+ /**
413
+ * OpenAI-compatible metadata attached to document source citations.
414
+ *
415
+ * @category response
416
+ * @since 4.0.0
417
+ */
248
418
  export interface DocumentSourcePartMetadata extends ProviderMetadata {
419
+ /**
420
+ * Provider-specific citation metadata for OpenAI-compatible APIs.
421
+ */
249
422
  readonly openai?:
250
423
  | {
424
+ /**
425
+ * Identifies a citation to an uploaded file.
426
+ */
251
427
  readonly type: "file_citation"
252
428
  /**
253
429
  * The index of the file in the list of files.
@@ -259,6 +435,9 @@ declare module "effect/unstable/ai/Response" {
259
435
  readonly fileId: string
260
436
  }
261
437
  | {
438
+ /**
439
+ * Identifies a citation to a generated file path.
440
+ */
262
441
  readonly type: "file_path"
263
442
  /**
264
443
  * The index of the file in the list of files.
@@ -270,6 +449,9 @@ declare module "effect/unstable/ai/Response" {
270
449
  readonly fileId: string
271
450
  }
272
451
  | {
452
+ /**
453
+ * Identifies a citation to a file inside a container.
454
+ */
273
455
  readonly type: "container_file_citation"
274
456
  /**
275
457
  * The ID of the file.
@@ -283,8 +465,20 @@ declare module "effect/unstable/ai/Response" {
283
465
  | null
284
466
  }
285
467
 
468
+ /**
469
+ * OpenAI-compatible metadata attached to URL source citations.
470
+ *
471
+ * @category response
472
+ * @since 4.0.0
473
+ */
286
474
  export interface UrlSourcePartMetadata extends ProviderMetadata {
475
+ /**
476
+ * Provider-specific URL citation metadata for OpenAI-compatible APIs.
477
+ */
287
478
  readonly openai?: {
479
+ /**
480
+ * Identifies a citation to a URL.
481
+ */
288
482
  readonly type: "url_citation"
289
483
  /**
290
484
  * The index of the first character of the URL citation in the message.
@@ -297,8 +491,20 @@ declare module "effect/unstable/ai/Response" {
297
491
  } | null
298
492
  }
299
493
 
494
+ /**
495
+ * OpenAI-compatible metadata attached to finish response parts.
496
+ *
497
+ * @category response
498
+ * @since 4.0.0
499
+ */
300
500
  export interface FinishPartMetadata extends ProviderMetadata {
501
+ /**
502
+ * Provider-specific metadata returned when generation finishes.
503
+ */
301
504
  readonly openai?: {
505
+ /**
506
+ * The service tier reported by the OpenAI-compatible provider.
507
+ */
302
508
  readonly serviceTier?: "default" | "auto" | "flex" | "scale" | "priority" | null
303
509
  } | null
304
510
  }
@@ -309,40 +515,65 @@ declare module "effect/unstable/ai/Response" {
309
515
  // =============================================================================
310
516
 
311
517
  /**
312
- * @since 1.0.0
518
+ * Creates an OpenAI-compatible model descriptor that can be provided with `Effect.provide`.
519
+ *
520
+ * **When to use**
521
+ *
522
+ * Use when you want an OpenAI-compatible language model value that carries
523
+ * provider and model metadata and can be supplied directly to an Effect program.
524
+ *
525
+ * @see {@link layer} for creating a `LanguageModel.LanguageModel` layer directly
526
+ * @see {@link make} for constructing the language model service effectfully
527
+ *
313
528
  * @category constructors
529
+ * @since 4.0.0
314
530
  */
315
531
  export const model = (
316
532
  model: string,
317
- config?: Omit<typeof Config.Service, "model">
533
+ config?: ModelConfig
318
534
  ): AiModel.Model<"openai", LanguageModel.LanguageModel, OpenAiClient> =>
319
- AiModel.make("openai", layer({ model, config }))
535
+ AiModel.make("openai", model, layer({ model, config }))
320
536
 
321
537
  // TODO
322
538
  // /**
323
- // * @since 1.0.0
539
+ // * @since 4.0.0
324
540
  // * @category constructors
325
541
  // */
326
542
  // export const modelWithTokenizer = (
327
543
  // model: string,
328
544
  // config?: Omit<typeof Config.Service, "model">
329
545
  // ): AiModel.Model<"openai", LanguageModel.LanguageModel | Tokenizer.Tokenizer, OpenAiClient> =>
330
- // AiModel.make("openai", layerWithTokenizer({ model, config }))
546
+ // AiModel.make("openai", model, layerWithTokenizer({ model, config }))
331
547
 
332
548
  /**
333
- * Creates an OpenAI language model service.
549
+ * Creates an OpenAI-compatible `LanguageModel` service from a model identifier and optional request defaults.
550
+ *
551
+ * **When to use**
552
+ *
553
+ * Use to construct an OpenAI-compatible chat-completions language model service
554
+ * backed by `OpenAiClient`.
555
+ *
556
+ * **Details**
557
+ *
558
+ * The returned effect requires `OpenAiClient`. Request defaults from the
559
+ * `config` option are merged with any `Config` service in the context, with
560
+ * context values taking precedence. The service supports both `generateText` and
561
+ * `streamText`.
562
+ *
563
+ * @see {@link layer} for providing the service as a `Layer`
564
+ * @see {@link model} for creating a model descriptor for `AiModel.provide`
334
565
  *
335
- * @since 1.0.0
336
566
  * @category constructors
567
+ * @since 4.0.0
337
568
  */
338
569
  export const make = Effect.fnUntraced(function*({ model, config: providerConfig }: {
339
570
  readonly model: string
340
- readonly config?: Omit<typeof Config.Service, "model"> | undefined
571
+ readonly config?: ModelConfig | undefined
341
572
  }): Effect.fn.Return<LanguageModel.Service, never, OpenAiClient> {
342
573
  const client = yield* OpenAiClient
343
574
 
344
575
  const makeConfig = Effect.gen(function*() {
345
- const services = yield* Effect.services<never>()
576
+ const services = yield* Effect.context<never>()
346
577
  return { model, ...providerConfig, ...services.mapUnsafe.get(Config.key) }
347
578
  })
348
579
 
@@ -370,8 +601,9 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
370
601
  config,
371
602
  options
372
603
  })
604
+ const { fileIdPrefixes: _fip, strictJsonSchema: _sjs, ...apiConfig } = config
373
605
  const request: CreateResponse = {
374
- ...config,
606
+ ...apiConfig,
375
607
  input: messages,
376
608
  include: include.size > 0 ? Array.from(include) : null,
377
609
  text: {
@@ -386,6 +618,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
386
618
  )
387
619
 
388
620
  return yield* LanguageModel.make({
621
+ codecTransformer: toCodecOpenAI,
389
622
  generateText: Effect.fnUntraced(
390
623
  function*(options) {
391
624
  const config = yield* makeConfig
@@ -423,58 +656,124 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
423
656
  })
424
657
  )
425
658
  )
426
- }).pipe(Effect.provideService(
427
- LanguageModel.CurrentCodecTransformer,
428
- toCodecOpenAI
429
- ))
659
+ })
430
660
  })
431
661
 
432
662
  /**
433
- * Creates a layer for the OpenAI language model.
663
+ * Creates a layer for the OpenAI-compatible language model.
664
+ *
665
+ * **When to use**
666
+ *
667
+ * Use when composing application layers and you want OpenAI-compatible APIs to
668
+ * satisfy `LanguageModel.LanguageModel` while supplying `OpenAiClient` from
669
+ * another layer.
670
+ *
671
+ * @see {@link make} for constructing the language model service effectfully
672
+ * @see {@link model} for creating an AI model descriptor
434
673
  *
435
- * @since 1.0.0
436
674
  * @category layers
675
+ * @since 4.0.0
437
676
  */
438
677
  export const layer = (options: {
439
678
  readonly model: string
440
- readonly config?: Omit<typeof Config.Service, "model"> | undefined
679
+ readonly config?: ModelConfig | undefined
441
680
  }): Layer.Layer<LanguageModel.LanguageModel, never, OpenAiClient> =>
442
681
  Layer.effect(LanguageModel.LanguageModel, make(options))
443
682
 
444
683
  /**
445
- * Provides config overrides for OpenAI language model operations.
684
+ * Provides scoped config overrides for OpenAI-compatible language model operations.
685
+ *
686
+ * **When to use**
687
+ *
688
+ * Use to override request configuration for a single language model effect
689
+ * without changing the defaults supplied to `model`, `make`, or `layer`.
690
+ *
691
+ * **Details**
692
+ *
693
+ * Existing `Config` values from the Effect context are merged with `overrides`,
694
+ * and the override values take precedence.
695
+ *
696
+ * @see {@link Config} for the configuration shape
446
697
  *
447
- * @since 1.0.0
448
698
  * @category configuration
699
+ * @since 4.0.0
449
700
  */
450
701
  export const withConfigOverride: {
451
702
  /**
452
- * Provides config overrides for OpenAI language model operations.
703
+ * Provides scoped config overrides for OpenAI-compatible language model operations.
704
+ *
705
+ * **When to use**
706
+ *
707
+ * Use to override request configuration for a single language model effect
708
+ * without changing the defaults supplied to `model`, `make`, or `layer`.
709
+ *
710
+ * **Details**
711
+ *
712
+ * Existing `Config` values from the Effect context are merged with `overrides`,
713
+ * and the override values take precedence.
714
+ *
715
+ * @see {@link Config} for the configuration shape
453
716
  *
454
- * @since 1.0.0
455
717
  * @category configuration
718
+ * @since 4.0.0
456
719
  */
457
720
  (overrides: typeof Config.Service): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Config>>
458
721
  /**
459
- * Provides config overrides for OpenAI language model operations.
722
+ * Provides scoped config overrides for OpenAI-compatible language model operations.
723
+ *
724
+ * **When to use**
725
+ *
726
+ * Use to override request configuration for a single language model effect
727
+ * without changing the defaults supplied to `model`, `make`, or `layer`.
728
+ *
729
+ * **Details**
730
+ *
731
+ * Existing `Config` values from the Effect context are merged with `overrides`,
732
+ * and the override values take precedence.
733
+ *
734
+ * @see {@link Config} for the configuration shape
460
735
  *
461
- * @since 1.0.0
462
736
  * @category configuration
737
+ * @since 4.0.0
463
738
  */
464
739
  <A, E, R>(self: Effect.Effect<A, E, R>, overrides: typeof Config.Service): Effect.Effect<A, E, Exclude<R, Config>>
465
740
  } = dual<
466
741
  /**
467
- * Provides config overrides for OpenAI language model operations.
742
+ * Provides scoped config overrides for OpenAI-compatible language model operations.
743
+ *
744
+ * **When to use**
745
+ *
746
+ * Use to override request configuration for a single language model effect
747
+ * without changing the defaults supplied to `model`, `make`, or `layer`.
748
+ *
749
+ * **Details**
750
+ *
751
+ * Existing `Config` values from the Effect context are merged with `overrides`,
752
+ * and the override values take precedence.
753
+ *
754
+ * @see {@link Config} for the configuration shape
468
755
  *
469
- * @since 1.0.0
470
756
  * @category configuration
757
+ * @since 4.0.0
471
758
  */
472
759
  (overrides: typeof Config.Service) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Config>>,
473
760
  /**
474
- * Provides config overrides for OpenAI language model operations.
761
+ * Provides scoped config overrides for OpenAI-compatible language model operations.
762
+ *
763
+ * **When to use**
764
+ *
765
+ * Use to override request configuration for a single language model effect
766
+ * without changing the defaults supplied to `model`, `make`, or `layer`.
767
+ *
768
+ * **Details**
769
+ *
770
+ * Existing `Config` values from the Effect context are merged with `overrides`,
771
+ * and the override values take precedence.
772
+ *
773
+ * @see {@link Config} for the configuration shape
475
774
  *
476
- * @since 1.0.0
477
775
  * @category configuration
776
+ * @since 4.0.0
478
777
  */
479
778
  <A, E, R>(self: Effect.Effect<A, E, R>, overrides: typeof Config.Service) => Effect.Effect<A, E, Exclude<R, Config>>
480
779
  >(2, (self, overrides) =>
@@ -711,7 +1010,6 @@ const prepareMessages = Effect.fnUntraced(
711
1010
  type: "function_call",
712
1011
  name: toolName,
713
1012
  call_id: part.id,
714
- // @effect-diagnostics-next-line preferSchemaOverJson:off
715
1013
  arguments: JSON.stringify(part.params),
716
1014
  ...(Predicate.isNotNull(id) ? { id } : {}),
717
1015
  ...(Predicate.isNotNull(status) ? { status } : {})
@@ -757,7 +1055,6 @@ const prepareMessages = Effect.fnUntraced(
757
1055
  messages.push({
758
1056
  type: "function_call_output",
759
1057
  call_id: part.id,
760
- // @effect-diagnostics-next-line preferSchemaOverJson:off
761
1058
  output: typeof part.result === "string" ? part.result : JSON.stringify(part.result),
762
1059
  ...(Predicate.isNotNull(status) ? { status } : {})
763
1060
  })
@@ -782,7 +1079,7 @@ const buildHttpRequestDetails = (
782
1079
  method: request.method,
783
1080
  url: request.url,
784
1081
  urlParams: Array.from(request.urlParams),
785
- hash: request.hash,
1082
+ hash: Option.getOrUndefined(request.hash),
786
1083
  headers: Redactable.redact(request.headers) as Record<string, string>
787
1084
  })
788
1085
 
@@ -834,6 +1131,11 @@ const makeResponse = Effect.fnUntraced(
834
1131
  const message = choice?.message
835
1132
 
836
1133
  if (message !== undefined) {
1134
+ const reasoning = message.reasoning ?? message.reasoning_content
1135
+ if (Predicate.isNotNullish(reasoning) && reasoning.length > 0) {
1136
+ parts.push({ type: "reasoning", text: reasoning })
1137
+ }
1138
+
837
1139
  if (
838
1140
  message.content !== undefined && Predicate.isNotNull(message.content) && message.content.length > 0
839
1141
  ) {
@@ -907,6 +1209,8 @@ const makeStreamResponse = Effect.fnUntraced(
907
1209
  let metadataEmitted = false
908
1210
  let textStarted = false
909
1211
  let textId = ""
1212
+ let reasoningStarted = false
1213
+ let reasoningId = ""
910
1214
  let hasToolCalls = false
911
1215
  const activeToolCalls: Record<number, ActiveToolCall> = {}
912
1216
 
@@ -915,6 +1219,14 @@ const makeStreamResponse = Effect.fnUntraced(
915
1219
  const parts: Array<Response.StreamPartEncoded> = []
916
1220
 
917
1221
  if (event === "[DONE]") {
1222
+ if (reasoningStarted) {
1223
+ parts.push({
1224
+ type: "reasoning-end",
1225
+ id: reasoningId,
1226
+ metadata: { openai: { ...makeItemIdMetadata(reasoningId) } }
1227
+ })
1228
+ }
1229
+
918
1230
  if (textStarted) {
919
1231
  parts.push({
920
1232
  type: "text-end",
@@ -972,6 +1284,7 @@ const makeStreamResponse = Effect.fnUntraced(
972
1284
  if (!metadataEmitted) {
973
1285
  metadataEmitted = true
974
1286
  textId = `${event.id}_message`
1287
+ reasoningId = `${event.id}_reasoning`
975
1288
  parts.push({
976
1289
  type: "response-metadata",
977
1290
  id: event.id,
@@ -986,7 +1299,29 @@ const makeStreamResponse = Effect.fnUntraced(
986
1299
  return parts
987
1300
  }
988
1301
 
1302
+ const reasoningDelta = choice.delta?.reasoning ?? choice.delta?.reasoning_content
1303
+ if (Predicate.isNotNullish(reasoningDelta) && reasoningDelta.length > 0) {
1304
+ if (!reasoningStarted) {
1305
+ reasoningStarted = true
1306
+ parts.push({
1307
+ type: "reasoning-start",
1308
+ id: reasoningId,
1309
+ metadata: { openai: { ...makeItemIdMetadata(reasoningId) } }
1310
+ })
1311
+ }
1312
+ parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningDelta })
1313
+ }
1314
+
989
1315
  if (choice.delta?.content !== undefined && Predicate.isNotNull(choice.delta.content)) {
1316
+ if (reasoningStarted) {
1317
+ reasoningStarted = false
1318
+ parts.push({
1319
+ type: "reasoning-end",
1320
+ id: reasoningId,
1321
+ metadata: { openai: { ...makeItemIdMetadata(reasoningId) } }
1322
+ })
1323
+ }
1324
+
990
1325
  if (!textStarted) {
991
1326
  textStarted = true
992
1327
  parts.push({
@@ -1002,11 +1337,13 @@ const makeStreamResponse = Effect.fnUntraced(
1002
1337
  hasToolCalls = hasToolCalls || choice.delta.tool_calls.length > 0
1003
1338
  choice.delta.tool_calls.forEach((deltaTool, indexInChunk) => {
1004
1339
  const toolIndex = deltaTool.index ?? indexInChunk
1005
- const toolId = deltaTool.id ?? `${event.id}_tool_${toolIndex}`
1340
+ const activeToolCall = activeToolCalls[toolIndex]
1341
+ const toolId = activeToolCall?.id ?? deltaTool.id ?? `${event.id}_tool_${toolIndex}`
1006
1342
  const providerToolName = deltaTool.function?.name
1007
- const toolName = toolNameMapper.getCustomName(providerToolName ?? "unknown_tool")
1343
+ const toolName = Predicate.isNotNullish(providerToolName)
1344
+ ? toolNameMapper.getCustomName(providerToolName)
1345
+ : activeToolCall?.name ?? toolNameMapper.getCustomName("unknown_tool")
1008
1346
  const argumentsDelta = deltaTool.function?.arguments ?? ""
1009
- const activeToolCall = activeToolCalls[toolIndex]
1010
1347
 
1011
1348
  if (Predicate.isUndefined(activeToolCall)) {
1012
1349
  activeToolCalls[toolIndex] = {
@@ -1124,7 +1461,7 @@ const unsupportedSchemaError = (error: unknown, method: string): AiError.AiError
1124
1461
  })
1125
1462
  })
1126
1463
 
1127
- const tryJsonSchema = <S extends Schema.Top>(schema: S, method: string) =>
1464
+ const tryJsonSchema = <S extends Schema.Constraint>(schema: S, method: string) =>
1128
1465
  Effect.try({
1129
1466
  try: () => Tool.getJsonSchemaFromSchema(schema, { transformer: toCodecOpenAI }),
1130
1467
  catch: (error) => unsupportedSchemaError(error, method)
@@ -1169,7 +1506,7 @@ const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Too
1169
1506
 
1170
1507
  // Convert the tools in the toolkit to the provider-defined format
1171
1508
  for (const tool of allowedTools) {
1172
- if (Tool.isUserDefined(tool)) {
1509
+ if (Tool.isUserDefined(tool) || Tool.isDynamic(tool)) {
1173
1510
  const strict = Tool.getStrictMode(tool) ?? config.strictJsonSchema ?? true
1174
1511
  const parameters = yield* tryToolJsonSchema(tool, "prepareTools")
1175
1512
  tools.push({
@@ -1220,6 +1557,7 @@ const toChatCompletionsRequest = (payload: CreateResponse): CreateResponseReques
1220
1557
  const toolChoice = toChatToolChoice(payload.tool_choice)
1221
1558
 
1222
1559
  return {
1560
+ ...extractCustomRequestProperties(payload),
1223
1561
  model: payload.model ?? "",
1224
1562
  messages: messages.length > 0 ? messages : [{ role: "user", content: "" }],
1225
1563
  ...(payload.temperature !== undefined ? { temperature: payload.temperature } : undefined),
@@ -1231,12 +1569,54 @@ const toChatCompletionsRequest = (payload: CreateResponse): CreateResponseReques
1231
1569
  ? { parallel_tool_calls: payload.parallel_tool_calls }
1232
1570
  : undefined),
1233
1571
  ...(payload.service_tier !== undefined ? { service_tier: payload.service_tier } : undefined),
1572
+ ...(payload.reasoning !== undefined ? { reasoning: payload.reasoning } : undefined),
1234
1573
  ...(responseFormat !== undefined ? { response_format: responseFormat } : undefined),
1235
1574
  ...(tools.length > 0 ? { tools } : undefined),
1236
1575
  ...(toolChoice !== undefined ? { tool_choice: toolChoice } : undefined)
1237
1576
  }
1238
1577
  }
1239
1578
 
1579
+ const createResponseKnownProperties = new Set<string>([
1580
+ "metadata",
1581
+ "top_logprobs",
1582
+ "temperature",
1583
+ "top_p",
1584
+ "user",
1585
+ "safety_identifier",
1586
+ "prompt_cache_key",
1587
+ "service_tier",
1588
+ "prompt_cache_retention",
1589
+ "previous_response_id",
1590
+ "model",
1591
+ "reasoning",
1592
+ "background",
1593
+ "max_output_tokens",
1594
+ "max_tool_calls",
1595
+ "text",
1596
+ "tools",
1597
+ "tool_choice",
1598
+ "truncation",
1599
+ "input",
1600
+ "include",
1601
+ "parallel_tool_calls",
1602
+ "store",
1603
+ "instructions",
1604
+ "stream",
1605
+ "conversation",
1606
+ "modalities",
1607
+ "seed"
1608
+ ])
1609
+
1610
+ const extractCustomRequestProperties = (payload: CreateResponse): Record<string, unknown> => {
1611
+ const customProperties: Record<string, unknown> = {}
1612
+ for (const [key, value] of Object.entries(payload)) {
1613
+ if (!createResponseKnownProperties.has(key)) {
1614
+ customProperties[key] = value
1615
+ }
1616
+ }
1617
+ return customProperties
1618
+ }
1619
+
1240
1620
  const toChatResponseFormat = (
1241
1621
  format: TextResponseFormatConfiguration | undefined
1242
1622
  ): CreateResponseRequestJson["response_format"] | undefined => {
@@ -1401,7 +1781,7 @@ const toAssistantChatMessageContent = (
1401
1781
  readonly type: string
1402
1782
  readonly [x: string]: unknown
1403
1783
  }>
1404
- ): string | null => {
1784
+ ): string => {
1405
1785
  let text = ""
1406
1786
  for (const part of content) {
1407
1787
  if (part.type === "output_text" && typeof part.text === "string") {
@@ -1411,7 +1791,7 @@ const toAssistantChatMessageContent = (
1411
1791
  text += part.refusal
1412
1792
  }
1413
1793
  }
1414
- return text.length > 0 ? text : null
1794
+ return text
1415
1795
  }
1416
1796
 
1417
1797
  const toChatMessageContent = (