@effect/ai-openai-compat 4.0.0-beta.99 → 4.0.0-rc.109

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 (110) hide show
  1. package/AGENTS.md +395 -0
  2. package/CLAUDE.md +395 -0
  3. package/README.md +14 -0
  4. package/ai-docs/README.md +44 -0
  5. package/ai-docs/package.json +36 -0
  6. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  7. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +39 -0
  8. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  9. package/ai-docs/src/01_effect/01_basics/index.md +5 -0
  10. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  11. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  12. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  13. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  14. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  16. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  17. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  18. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  19. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  20. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  21. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  22. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  23. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  24. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  25. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  26. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  27. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  28. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  29. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  30. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  31. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  32. package/ai-docs/src/03_stream/30_encoding.ts +165 -0
  33. package/ai-docs/src/03_stream/index.md +4 -0
  34. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  35. package/ai-docs/src/04_integration/index.md +5 -0
  36. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  37. package/ai-docs/src/05_batching/index.md +3 -0
  38. package/ai-docs/src/06_schedule/10_schedules.ts +110 -0
  39. package/ai-docs/src/06_schedule/index.md +3 -0
  40. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  41. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  42. package/ai-docs/src/07_datetime/index.md +5 -0
  43. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  44. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  45. package/ai-docs/src/08_observability/index.md +7 -0
  46. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  47. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  48. package/ai-docs/src/09_testing/index.md +1 -0
  49. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  50. package/ai-docs/src/10_predicate/index.md +9 -0
  51. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  52. package/ai-docs/src/40_sql/index.md +6 -0
  53. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  54. package/ai-docs/src/50_http-client/index.md +3 -0
  55. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  56. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  57. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  61. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  63. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  66. package/ai-docs/src/51_http-server/index.md +3 -0
  67. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  68. package/ai-docs/src/60_child-process/index.md +3 -0
  69. package/ai-docs/src/70_cli/10_basics.ts +160 -0
  70. package/ai-docs/src/70_cli/index.md +5 -0
  71. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  72. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  73. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  74. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  75. package/ai-docs/src/71_ai/index.md +5 -0
  76. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  77. package/ai-docs/src/80_cluster/index.md +4 -0
  78. package/ai-docs/src/index.md +10 -0
  79. package/ai-docs/tsconfig.json +24 -0
  80. package/dist/OpenAiClient.d.ts +63 -53
  81. package/dist/OpenAiClient.d.ts.map +1 -1
  82. package/dist/OpenAiClient.js +31 -23
  83. package/dist/OpenAiClient.js.map +1 -1
  84. package/dist/OpenAiConfig.d.ts +1 -1
  85. package/dist/OpenAiConfig.js +1 -1
  86. package/dist/OpenAiConfig.js.map +1 -1
  87. package/dist/OpenAiEmbeddingModel.d.ts +1 -1
  88. package/dist/OpenAiEmbeddingModel.d.ts.map +1 -1
  89. package/dist/OpenAiEmbeddingModel.js +6 -9
  90. package/dist/OpenAiEmbeddingModel.js.map +1 -1
  91. package/dist/OpenAiLanguageModel.d.ts +17 -17
  92. package/dist/OpenAiLanguageModel.d.ts.map +1 -1
  93. package/dist/OpenAiLanguageModel.js +85 -24
  94. package/dist/OpenAiLanguageModel.js.map +1 -1
  95. package/dist/OpenAiTelemetry.d.ts +1 -1
  96. package/dist/OpenAiTelemetry.d.ts.map +1 -1
  97. package/dist/OpenAiTelemetry.js.map +1 -1
  98. package/dist/index.js.map +1 -1
  99. package/dist/internal/errors.js +9 -1
  100. package/dist/internal/errors.js.map +1 -1
  101. package/dist/internal/utilities.js +1 -1
  102. package/dist/internal/utilities.js.map +1 -1
  103. package/package.json +9 -7
  104. package/src/OpenAiClient.ts +124 -98
  105. package/src/OpenAiConfig.ts +2 -2
  106. package/src/OpenAiEmbeddingModel.ts +4 -5
  107. package/src/OpenAiLanguageModel.ts +125 -38
  108. package/src/OpenAiTelemetry.ts +1 -1
  109. package/src/internal/errors.ts +13 -1
  110. package/src/internal/utilities.ts +1 -1
@@ -16,9 +16,11 @@ import { dual } from "effect/Function"
16
16
  import * as Layer from "effect/Layer"
17
17
  import * as Option from "effect/Option"
18
18
  import * as Predicate from "effect/Predicate"
19
+ import * as Rec from "effect/Record"
19
20
  import * as Redactable from "effect/Redactable"
20
- import type * as Schema from "effect/Schema"
21
+ import * as Schema from "effect/Schema"
21
22
  import * as AST from "effect/SchemaAST"
23
+ import * as SchemaIssue from "effect/SchemaIssue"
22
24
  import * as Stream from "effect/Stream"
23
25
  import type { Span } from "effect/Tracer"
24
26
  import type { DeepMutable, Simplify } from "effect/Types"
@@ -35,6 +37,7 @@ import * as InternalUtilities from "./internal/utilities.ts"
35
37
  import {
36
38
  type Annotation,
37
39
  type ChatCompletionContentPart,
40
+ type ChatCompletionRequestToolCall,
38
41
  type CreateResponse,
39
42
  type CreateResponse200,
40
43
  type CreateResponse200Sse,
@@ -47,10 +50,13 @@ import {
47
50
  type ReasoningItem,
48
51
  type SummaryTextContent,
49
52
  type TextResponseFormatConfiguration,
50
- type Tool as OpenAiClientTool
53
+ type Tool as OpenAiClientTool,
54
+ type UnknownChatCompletionEvent
51
55
  } from "./OpenAiClient.ts"
52
56
  import { addGenAIAnnotations } from "./OpenAiTelemetry.ts"
53
57
 
58
+ const formatIssue = SchemaIssue.makeFormatterDefault()
59
+
54
60
  /**
55
61
  * Image detail level for vision requests.
56
62
  */
@@ -108,7 +114,7 @@ type ModelConfig = Omit<ConfigOptions, "model"> & { readonly [x: string]: unknow
108
114
  *
109
115
  * @see {@link withConfigOverride} for scoping language model request overrides
110
116
  *
111
- * @category context
117
+ * @category services
112
118
  * @since 4.0.0
113
119
  */
114
120
  export class Config extends Context.Service<
@@ -124,7 +130,7 @@ declare module "effect/unstable/ai/Prompt" {
124
130
  /**
125
131
  * OpenAI-compatible options for file prompt parts.
126
132
  *
127
- * @category request
133
+ * @category models
128
134
  * @since 4.0.0
129
135
  */
130
136
  export interface FilePartOptions extends ProviderOptions {
@@ -142,7 +148,7 @@ declare module "effect/unstable/ai/Prompt" {
142
148
  /**
143
149
  * OpenAI-compatible options for reasoning prompt parts.
144
150
  *
145
- * @category request
151
+ * @category models
146
152
  * @since 4.0.0
147
153
  */
148
154
  export interface ReasoningPartOptions extends ProviderOptions {
@@ -166,7 +172,7 @@ declare module "effect/unstable/ai/Prompt" {
166
172
  /**
167
173
  * OpenAI-compatible options for assistant tool-call prompt parts.
168
174
  *
169
- * @category request
175
+ * @category models
170
176
  * @since 4.0.0
171
177
  */
172
178
  export interface ToolCallPartOptions extends ProviderOptions {
@@ -188,7 +194,7 @@ declare module "effect/unstable/ai/Prompt" {
188
194
  /**
189
195
  * OpenAI-compatible options for tool-result prompt parts.
190
196
  *
191
- * @category request
197
+ * @category models
192
198
  * @since 4.0.0
193
199
  */
194
200
  export interface ToolResultPartOptions extends ProviderOptions {
@@ -210,7 +216,7 @@ declare module "effect/unstable/ai/Prompt" {
210
216
  /**
211
217
  * OpenAI-compatible options for text prompt parts.
212
218
  *
213
- * @category request
219
+ * @category models
214
220
  * @since 4.0.0
215
221
  */
216
222
  export interface TextPartOptions extends ProviderOptions {
@@ -238,7 +244,7 @@ declare module "effect/unstable/ai/Response" {
238
244
  /**
239
245
  * OpenAI-compatible metadata attached to a complete text response part.
240
246
  *
241
- * @category response
247
+ * @category models
242
248
  * @since 4.0.0
243
249
  */
244
250
  export interface TextPartMetadata extends ProviderMetadata {
@@ -270,7 +276,7 @@ declare module "effect/unstable/ai/Response" {
270
276
  /**
271
277
  * OpenAI-compatible metadata emitted when a streamed text part starts.
272
278
  *
273
- * @category response
279
+ * @category models
274
280
  * @since 4.0.0
275
281
  */
276
282
  export interface TextStartPartMetadata extends ProviderMetadata {
@@ -288,7 +294,7 @@ declare module "effect/unstable/ai/Response" {
288
294
  /**
289
295
  * OpenAI-compatible metadata emitted when a streamed text part ends.
290
296
  *
291
- * @category response
297
+ * @category models
292
298
  * @since 4.0.0
293
299
  */
294
300
  export interface TextEndPartMetadata extends ProviderMetadata {
@@ -310,7 +316,7 @@ declare module "effect/unstable/ai/Response" {
310
316
  /**
311
317
  * OpenAI-compatible metadata attached to a complete reasoning response part.
312
318
  *
313
- * @category response
319
+ * @category models
314
320
  * @since 4.0.0
315
321
  */
316
322
  export interface ReasoningPartMetadata extends ProviderMetadata {
@@ -332,7 +338,7 @@ declare module "effect/unstable/ai/Response" {
332
338
  /**
333
339
  * OpenAI-compatible metadata emitted when a streamed reasoning part starts.
334
340
  *
335
- * @category response
341
+ * @category models
336
342
  * @since 4.0.0
337
343
  */
338
344
  export interface ReasoningStartPartMetadata extends ProviderMetadata {
@@ -354,7 +360,7 @@ declare module "effect/unstable/ai/Response" {
354
360
  /**
355
361
  * OpenAI-compatible metadata emitted for a streamed reasoning delta.
356
362
  *
357
- * @category response
363
+ * @category models
358
364
  * @since 4.0.0
359
365
  */
360
366
  export interface ReasoningDeltaPartMetadata extends ProviderMetadata {
@@ -372,7 +378,7 @@ declare module "effect/unstable/ai/Response" {
372
378
  /**
373
379
  * OpenAI-compatible metadata emitted when a streamed reasoning part ends.
374
380
  *
375
- * @category response
381
+ * @category models
376
382
  * @since 4.0.0
377
383
  */
378
384
  export interface ReasoningEndPartMetadata extends ProviderMetadata {
@@ -394,7 +400,7 @@ declare module "effect/unstable/ai/Response" {
394
400
  /**
395
401
  * OpenAI-compatible metadata attached to tool-call response parts.
396
402
  *
397
- * @category response
403
+ * @category models
398
404
  * @since 4.0.0
399
405
  */
400
406
  export interface ToolCallPartMetadata extends ProviderMetadata {
@@ -412,7 +418,7 @@ declare module "effect/unstable/ai/Response" {
412
418
  /**
413
419
  * OpenAI-compatible metadata attached to document source citations.
414
420
  *
415
- * @category response
421
+ * @category models
416
422
  * @since 4.0.0
417
423
  */
418
424
  export interface DocumentSourcePartMetadata extends ProviderMetadata {
@@ -468,7 +474,7 @@ declare module "effect/unstable/ai/Response" {
468
474
  /**
469
475
  * OpenAI-compatible metadata attached to URL source citations.
470
476
  *
471
- * @category response
477
+ * @category models
472
478
  * @since 4.0.0
473
479
  */
474
480
  export interface UrlSourcePartMetadata extends ProviderMetadata {
@@ -494,7 +500,7 @@ declare module "effect/unstable/ai/Response" {
494
500
  /**
495
501
  * OpenAI-compatible metadata attached to finish response parts.
496
502
  *
497
- * @category response
503
+ * @category models
498
504
  * @since 4.0.0
499
505
  */
500
506
  export interface FinishPartMetadata extends ProviderMetadata {
@@ -572,10 +578,9 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
572
578
  }): Effect.fn.Return<LanguageModel.Service, never, OpenAiClient> {
573
579
  const client = yield* OpenAiClient
574
580
 
575
- const makeConfig = Effect.gen(function*() {
576
- const services = yield* Effect.context<never>()
577
- return { model, ...providerConfig, ...services.mapUnsafe.get(Config.key) }
578
- })
581
+ const makeConfig = Effect.contextWith((services: Context.Context<never>) =>
582
+ Effect.succeed({ model, ...providerConfig, ...Context.getOrUndefined(services, Config) })
583
+ )
579
584
 
580
585
  const makeRequest = Effect.fnUntraced(
581
586
  function*<Tools extends ReadonlyArray<Tool.Any>>({ config, options, toolNameMapper }: {
@@ -628,6 +633,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
628
633
  const [rawResponse, response] = yield* client.createResponse(request)
629
634
  annotateResponse(options.span, rawResponse)
630
635
  return yield* makeResponse({
636
+ options,
631
637
  rawResponse,
632
638
  response,
633
639
  toolNameMapper
@@ -642,6 +648,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
642
648
  annotateRequest(options.span, request)
643
649
  const [response, stream] = yield* client.createResponseStream(request)
644
650
  return yield* makeStreamResponse({
651
+ options,
645
652
  stream,
646
653
  response,
647
654
  toolNameMapper
@@ -898,7 +905,7 @@ const prepareMessages = Effect.fnUntraced(
898
905
  }
899
906
 
900
907
  case "assistant": {
901
- const reasoningMessages: Record<string, DeepMutable<ReasoningItem>> = {}
908
+ const reasoningMessages: Record<string, DeepMutable<ReasoningItem>> = Object.create(null)
902
909
 
903
910
  for (const part of message.content) {
904
911
  switch (part.type) {
@@ -1096,6 +1103,11 @@ const buildHttpResponseDetails = (
1096
1103
 
1097
1104
  type ResponseStreamEvent = CreateResponse200Sse
1098
1105
 
1106
+ const isUnknownChatCompletionEvent = (
1107
+ event: ResponseStreamEvent
1108
+ ): event is UnknownChatCompletionEvent =>
1109
+ typeof event !== "string" && "_tag" in event && event._tag === "UnknownChatCompletionEvent"
1110
+
1099
1111
  type ActiveToolCall = {
1100
1112
  readonly id: string
1101
1113
  name: string
@@ -1104,10 +1116,12 @@ type ActiveToolCall = {
1104
1116
 
1105
1117
  const makeResponse = Effect.fnUntraced(
1106
1118
  function*<Tools extends ReadonlyArray<Tool.Any>>({
1119
+ options,
1107
1120
  rawResponse,
1108
1121
  response,
1109
1122
  toolNameMapper
1110
1123
  }: {
1124
+ readonly options: LanguageModel.ProviderOptions
1111
1125
  readonly rawResponse: CreateResponse200
1112
1126
  readonly response: HttpClientResponse.HttpClientResponse
1113
1127
  readonly toolNameMapper: Tool.NameMapper<Tools>
@@ -1146,9 +1160,9 @@ const makeResponse = Effect.fnUntraced(
1146
1160
  for (const [index, toolCall] of message.tool_calls.entries()) {
1147
1161
  const toolId = toolCall.id ?? `${rawResponse.id}_tool_${index}`
1148
1162
  const toolName = toolNameMapper.getCustomName(toolCall.function?.name ?? "unknown_tool")
1149
- const toolParams = toolCall.function?.arguments ?? "{}"
1150
- const params = yield* Effect.try({
1151
- try: () => Tool.unsafeSecureJsonParse(toolParams),
1163
+ const toolParamsJson = toolCall.function?.arguments ?? "{}"
1164
+ const toolParams = yield* Effect.try({
1165
+ try: () => Tool.unsafeSecureJsonParse(toolParamsJson),
1152
1166
  catch: (cause) =>
1153
1167
  AiError.make({
1154
1168
  module: "OpenAiLanguageModel",
@@ -1160,6 +1174,7 @@ const makeResponse = Effect.fnUntraced(
1160
1174
  })
1161
1175
  })
1162
1176
  })
1177
+ const params = yield* transformToolCallParams(options.tools, toolName, toolParams)
1163
1178
  hasToolCalls = true
1164
1179
  parts.push({
1165
1180
  type: "tool-call",
@@ -1192,10 +1207,12 @@ const makeResponse = Effect.fnUntraced(
1192
1207
 
1193
1208
  const makeStreamResponse = Effect.fnUntraced(
1194
1209
  function*<Tools extends ReadonlyArray<Tool.Any>>({
1210
+ options,
1195
1211
  stream,
1196
1212
  response,
1197
1213
  toolNameMapper
1198
1214
  }: {
1215
+ readonly options: LanguageModel.ProviderOptions
1199
1216
  readonly stream: Stream.Stream<ResponseStreamEvent, AiError.AiError>
1200
1217
  readonly response: HttpClientResponse.HttpClientResponse
1201
1218
  readonly toolNameMapper: Tool.NameMapper<Tools>
@@ -1237,7 +1254,7 @@ const makeStreamResponse = Effect.fnUntraced(
1237
1254
 
1238
1255
  for (const toolCall of Object.values(activeToolCalls)) {
1239
1256
  const toolParams = toolCall.arguments.length > 0 ? toolCall.arguments : "{}"
1240
- const params = yield* Effect.try({
1257
+ const parsedParams = yield* Effect.try({
1241
1258
  try: () => Tool.unsafeSecureJsonParse(toolParams),
1242
1259
  catch: (cause) =>
1243
1260
  AiError.make({
@@ -1250,6 +1267,7 @@ const makeStreamResponse = Effect.fnUntraced(
1250
1267
  })
1251
1268
  })
1252
1269
  })
1270
+ const params = yield* transformToolCallParams(options.tools, toolCall.name, parsedParams)
1253
1271
  parts.push({ type: "tool-params-end", id: toolCall.id })
1254
1272
  parts.push({
1255
1273
  type: "tool-call",
@@ -1274,6 +1292,12 @@ const makeStreamResponse = Effect.fnUntraced(
1274
1292
  return parts
1275
1293
  }
1276
1294
 
1295
+ // Keep unknown events available to direct client consumers; this layer
1296
+ // cannot translate provider-specific data into portable stream parts.
1297
+ if (isUnknownChatCompletionEvent(event)) {
1298
+ return parts
1299
+ }
1300
+
1277
1301
  if (event.service_tier !== undefined) {
1278
1302
  serviceTier = event.service_tier
1279
1303
  }
@@ -1461,6 +1485,12 @@ const unsupportedSchemaError = (error: unknown, method: string): AiError.AiError
1461
1485
  })
1462
1486
  })
1463
1487
 
1488
+ const tryCodecTransform = <S extends Schema.Constraint>(schema: S, method: string) =>
1489
+ Effect.try({
1490
+ try: () => toCodecOpenAI(schema),
1491
+ catch: (error) => unsupportedSchemaError(error, method)
1492
+ })
1493
+
1464
1494
  const tryJsonSchema = <S extends Schema.Constraint>(schema: S, method: string) =>
1465
1495
  Effect.try({
1466
1496
  try: () => Tool.getJsonSchemaFromSchema(schema, { transformer: toCodecOpenAI }),
@@ -1473,6 +1503,42 @@ const tryToolJsonSchema = <T extends Tool.Any>(tool: T, method: string) =>
1473
1503
  catch: (error) => unsupportedSchemaError(error, method)
1474
1504
  })
1475
1505
 
1506
+ const transformToolCallParams = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Tool.Any>>(
1507
+ tools: Tools,
1508
+ toolName: string,
1509
+ toolParams: unknown
1510
+ ): Effect.fn.Return<unknown, AiError.AiError> {
1511
+ const tool = tools.find((tool) => tool.name === toolName)
1512
+
1513
+ if (Predicate.isUndefined(tool)) {
1514
+ return yield* AiError.make({
1515
+ module: "OpenAiLanguageModel",
1516
+ method: "makeResponse",
1517
+ reason: new AiError.ToolNotFoundError({
1518
+ toolName,
1519
+ availableTools: tools.map((tool) => tool.name)
1520
+ })
1521
+ })
1522
+ }
1523
+
1524
+ const { codec } = yield* tryCodecTransform(tool.parametersSchema, "makeResponse")
1525
+ const transform = Schema.decodeEffect(codec)
1526
+
1527
+ return yield* (
1528
+ transform(toolParams) as Effect.Effect<unknown, Schema.SchemaError>
1529
+ ).pipe(Effect.mapError((error) =>
1530
+ AiError.make({
1531
+ module: "OpenAiLanguageModel",
1532
+ method: "makeResponse",
1533
+ reason: new AiError.ToolParameterValidationError({
1534
+ toolName,
1535
+ toolParams,
1536
+ description: formatIssue(error.issue)
1537
+ })
1538
+ })
1539
+ ))
1540
+ })
1541
+
1476
1542
  const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Tool.Any>>({
1477
1543
  config,
1478
1544
  options,
@@ -1611,7 +1677,7 @@ const extractCustomRequestProperties = (payload: CreateResponse): Record<string,
1611
1677
  const customProperties: Record<string, unknown> = {}
1612
1678
  for (const [key, value] of Object.entries(payload)) {
1613
1679
  if (!createResponseKnownProperties.has(key)) {
1614
- customProperties[key] = value
1680
+ Rec.assignProperty(customProperties, key, value)
1615
1681
  }
1616
1682
  }
1617
1683
  return customProperties
@@ -1723,7 +1789,24 @@ const toChatMessages = (
1723
1789
  const messages: Array<CreateResponseRequestJson["messages"][number]> = []
1724
1790
 
1725
1791
  for (const item of input) {
1726
- messages.push(...toChatMessagesFromItem(item))
1792
+ if (Predicate.hasProperty(item, "type") && item.type === "function_call") {
1793
+ const previous = messages.at(-1)
1794
+ const toolCall = toChatToolCall(item)
1795
+ if (previous?.role === "assistant" && previous.tool_calls !== undefined) {
1796
+ messages[messages.length - 1] = {
1797
+ ...previous,
1798
+ tool_calls: [...previous.tool_calls, toolCall]
1799
+ }
1800
+ } else {
1801
+ messages.push({
1802
+ role: "assistant",
1803
+ content: null,
1804
+ tool_calls: [toolCall]
1805
+ })
1806
+ }
1807
+ } else {
1808
+ messages.push(...toChatMessagesFromItem(item))
1809
+ }
1727
1810
  }
1728
1811
 
1729
1812
  return messages
@@ -1751,14 +1834,7 @@ const toChatMessagesFromItem = (
1751
1834
  return [{
1752
1835
  role: "assistant",
1753
1836
  content: null,
1754
- tool_calls: [{
1755
- id: item.call_id,
1756
- type: "function",
1757
- function: {
1758
- name: item.name,
1759
- arguments: item.arguments
1760
- }
1761
- }]
1837
+ tool_calls: [toChatToolCall(item)]
1762
1838
  }]
1763
1839
  }
1764
1840
 
@@ -1776,6 +1852,17 @@ const toChatMessagesFromItem = (
1776
1852
  }
1777
1853
  }
1778
1854
 
1855
+ const toChatToolCall = (
1856
+ item: Extract<InputItem, { readonly type: "function_call" }>
1857
+ ): ChatCompletionRequestToolCall => ({
1858
+ id: item.call_id,
1859
+ type: "function",
1860
+ function: {
1861
+ name: item.name,
1862
+ arguments: item.arguments
1863
+ }
1864
+ })
1865
+
1779
1866
  const toAssistantChatMessageContent = (
1780
1867
  content: ReadonlyArray<{
1781
1868
  readonly type: string
@@ -28,7 +28,7 @@ import * as Telemetry from "effect/unstable/ai/Telemetry"
28
28
  export type OpenAiTelemetryAttributes = Simplify<
29
29
  & Telemetry.GenAITelemetryAttributes
30
30
  & Telemetry.AttributesWithPrefix<RequestAttributes, "gen_ai.openai.request">
31
- & Telemetry.AttributesWithPrefix<ResponseAttributes, "gen_ai.openai.request">
31
+ & Telemetry.AttributesWithPrefix<ResponseAttributes, "gen_ai.openai.response">
32
32
  >
33
33
 
34
34
  /**
@@ -10,6 +10,7 @@ import * as SchemaTransformation from "effect/SchemaTransformation"
10
10
  import * as String from "effect/String"
11
11
  import * as AiError from "effect/unstable/ai/AiError"
12
12
  import type * as Response from "effect/unstable/ai/Response"
13
+ import type * as Sse from "effect/unstable/encoding/Sse"
13
14
  import type * as HttpClientError from "effect/unstable/http/HttpClientError"
14
15
  import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest"
15
16
  import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse"
@@ -22,7 +23,7 @@ export const OpenAiErrorBody = Schema.Struct({
22
23
  type: Schema.optional(Schema.NullOr(Schema.String)),
23
24
  status: Schema.optional(Schema.NullOr(Schema.String)),
24
25
  param: Schema.optional(Schema.NullOr(Schema.String)),
25
- code: Schema.optional(Schema.NullOr(Schema.Union([Schema.String, Schema.Number])))
26
+ code: Schema.optional(Schema.NullOr(Schema.Union([Schema.String, Schema.Finite])))
26
27
  })
27
28
  })
28
29
  const OpenAiErrorBodyJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Union([
@@ -49,6 +50,17 @@ export const mapSchemaError = dual<
49
50
  reason: AiError.InvalidOutputError.fromSchemaError(error)
50
51
  }))
51
52
 
53
+ /** @internal */
54
+ export const mapSseError = dual<
55
+ (method: string) => (error: Sse.SseError) => AiError.AiError,
56
+ (error: Sse.SseError, method: string) => AiError.AiError
57
+ >(2, (error, method) =>
58
+ AiError.make({
59
+ module: "OpenAiClient",
60
+ method,
61
+ reason: new AiError.InvalidOutputError({ description: error.message })
62
+ }))
63
+
52
64
  /** @internal */
53
65
  export const mapHttpClientError = dual<
54
66
  (method: string) => (error: HttpClientError.HttpClientError) => Effect.Effect<never, AiError.AiError>,
@@ -16,7 +16,7 @@ export const resolveFinishReason = (
16
16
  if (finishReason == null) {
17
17
  return hasToolCalls ? "tool-calls" : "stop"
18
18
  }
19
- const reason = finishReasonMap[finishReason]
19
+ const reason = Object.hasOwn(finishReasonMap, finishReason) ? finishReasonMap[finishReason] : undefined
20
20
  if (reason == null) {
21
21
  return hasToolCalls ? "tool-calls" : "unknown"
22
22
  }