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

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 (105) hide show
  1. package/AGENTS.md +381 -0
  2. package/CLAUDE.md +381 -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/50_http-client/10_basics.ts +102 -0
  52. package/ai-docs/src/50_http-client/index.md +3 -0
  53. package/ai-docs/src/51_http-server/10_basics.ts +116 -0
  54. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  55. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  56. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  57. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +91 -0
  58. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +12 -0
  59. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  60. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +36 -0
  61. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +71 -0
  62. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +62 -0
  63. package/ai-docs/src/51_http-server/index.md +3 -0
  64. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  65. package/ai-docs/src/60_child-process/index.md +3 -0
  66. package/ai-docs/src/70_cli/10_basics.ts +136 -0
  67. package/ai-docs/src/70_cli/index.md +5 -0
  68. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  69. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  70. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  71. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  72. package/ai-docs/src/71_ai/index.md +5 -0
  73. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  74. package/ai-docs/src/80_cluster/index.md +4 -0
  75. package/ai-docs/src/index.md +10 -0
  76. package/ai-docs/tsconfig.json +24 -0
  77. package/dist/OpenAiClient.d.ts +63 -53
  78. package/dist/OpenAiClient.d.ts.map +1 -1
  79. package/dist/OpenAiClient.js +31 -23
  80. package/dist/OpenAiClient.js.map +1 -1
  81. package/dist/OpenAiConfig.d.ts +1 -1
  82. package/dist/OpenAiConfig.js.map +1 -1
  83. package/dist/OpenAiEmbeddingModel.d.ts +1 -1
  84. package/dist/OpenAiEmbeddingModel.js +1 -1
  85. package/dist/OpenAiEmbeddingModel.js.map +1 -1
  86. package/dist/OpenAiLanguageModel.d.ts +17 -17
  87. package/dist/OpenAiLanguageModel.d.ts.map +1 -1
  88. package/dist/OpenAiLanguageModel.js +80 -16
  89. package/dist/OpenAiLanguageModel.js.map +1 -1
  90. package/dist/OpenAiTelemetry.d.ts +1 -1
  91. package/dist/OpenAiTelemetry.d.ts.map +1 -1
  92. package/dist/OpenAiTelemetry.js.map +1 -1
  93. package/dist/index.js.map +1 -1
  94. package/dist/internal/errors.js +9 -1
  95. package/dist/internal/errors.js.map +1 -1
  96. package/dist/internal/utilities.js +1 -1
  97. package/dist/internal/utilities.js.map +1 -1
  98. package/package.json +9 -7
  99. package/src/OpenAiClient.ts +124 -98
  100. package/src/OpenAiConfig.ts +1 -1
  101. package/src/OpenAiEmbeddingModel.ts +1 -1
  102. package/src/OpenAiLanguageModel.ts +122 -34
  103. package/src/OpenAiTelemetry.ts +1 -1
  104. package/src/internal/errors.ts +13 -1
  105. 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 {
@@ -628,6 +634,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
628
634
  const [rawResponse, response] = yield* client.createResponse(request)
629
635
  annotateResponse(options.span, rawResponse)
630
636
  return yield* makeResponse({
637
+ options,
631
638
  rawResponse,
632
639
  response,
633
640
  toolNameMapper
@@ -642,6 +649,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
642
649
  annotateRequest(options.span, request)
643
650
  const [response, stream] = yield* client.createResponseStream(request)
644
651
  return yield* makeStreamResponse({
652
+ options,
645
653
  stream,
646
654
  response,
647
655
  toolNameMapper
@@ -898,7 +906,7 @@ const prepareMessages = Effect.fnUntraced(
898
906
  }
899
907
 
900
908
  case "assistant": {
901
- const reasoningMessages: Record<string, DeepMutable<ReasoningItem>> = {}
909
+ const reasoningMessages: Record<string, DeepMutable<ReasoningItem>> = Object.create(null)
902
910
 
903
911
  for (const part of message.content) {
904
912
  switch (part.type) {
@@ -1096,6 +1104,11 @@ const buildHttpResponseDetails = (
1096
1104
 
1097
1105
  type ResponseStreamEvent = CreateResponse200Sse
1098
1106
 
1107
+ const isUnknownChatCompletionEvent = (
1108
+ event: ResponseStreamEvent
1109
+ ): event is UnknownChatCompletionEvent =>
1110
+ typeof event !== "string" && "_tag" in event && event._tag === "UnknownChatCompletionEvent"
1111
+
1099
1112
  type ActiveToolCall = {
1100
1113
  readonly id: string
1101
1114
  name: string
@@ -1104,10 +1117,12 @@ type ActiveToolCall = {
1104
1117
 
1105
1118
  const makeResponse = Effect.fnUntraced(
1106
1119
  function*<Tools extends ReadonlyArray<Tool.Any>>({
1120
+ options,
1107
1121
  rawResponse,
1108
1122
  response,
1109
1123
  toolNameMapper
1110
1124
  }: {
1125
+ readonly options: LanguageModel.ProviderOptions
1111
1126
  readonly rawResponse: CreateResponse200
1112
1127
  readonly response: HttpClientResponse.HttpClientResponse
1113
1128
  readonly toolNameMapper: Tool.NameMapper<Tools>
@@ -1146,9 +1161,9 @@ const makeResponse = Effect.fnUntraced(
1146
1161
  for (const [index, toolCall] of message.tool_calls.entries()) {
1147
1162
  const toolId = toolCall.id ?? `${rawResponse.id}_tool_${index}`
1148
1163
  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),
1164
+ const toolParamsJson = toolCall.function?.arguments ?? "{}"
1165
+ const toolParams = yield* Effect.try({
1166
+ try: () => Tool.unsafeSecureJsonParse(toolParamsJson),
1152
1167
  catch: (cause) =>
1153
1168
  AiError.make({
1154
1169
  module: "OpenAiLanguageModel",
@@ -1160,6 +1175,7 @@ const makeResponse = Effect.fnUntraced(
1160
1175
  })
1161
1176
  })
1162
1177
  })
1178
+ const params = yield* transformToolCallParams(options.tools, toolName, toolParams)
1163
1179
  hasToolCalls = true
1164
1180
  parts.push({
1165
1181
  type: "tool-call",
@@ -1192,10 +1208,12 @@ const makeResponse = Effect.fnUntraced(
1192
1208
 
1193
1209
  const makeStreamResponse = Effect.fnUntraced(
1194
1210
  function*<Tools extends ReadonlyArray<Tool.Any>>({
1211
+ options,
1195
1212
  stream,
1196
1213
  response,
1197
1214
  toolNameMapper
1198
1215
  }: {
1216
+ readonly options: LanguageModel.ProviderOptions
1199
1217
  readonly stream: Stream.Stream<ResponseStreamEvent, AiError.AiError>
1200
1218
  readonly response: HttpClientResponse.HttpClientResponse
1201
1219
  readonly toolNameMapper: Tool.NameMapper<Tools>
@@ -1237,7 +1255,7 @@ const makeStreamResponse = Effect.fnUntraced(
1237
1255
 
1238
1256
  for (const toolCall of Object.values(activeToolCalls)) {
1239
1257
  const toolParams = toolCall.arguments.length > 0 ? toolCall.arguments : "{}"
1240
- const params = yield* Effect.try({
1258
+ const parsedParams = yield* Effect.try({
1241
1259
  try: () => Tool.unsafeSecureJsonParse(toolParams),
1242
1260
  catch: (cause) =>
1243
1261
  AiError.make({
@@ -1250,6 +1268,7 @@ const makeStreamResponse = Effect.fnUntraced(
1250
1268
  })
1251
1269
  })
1252
1270
  })
1271
+ const params = yield* transformToolCallParams(options.tools, toolCall.name, parsedParams)
1253
1272
  parts.push({ type: "tool-params-end", id: toolCall.id })
1254
1273
  parts.push({
1255
1274
  type: "tool-call",
@@ -1274,6 +1293,12 @@ const makeStreamResponse = Effect.fnUntraced(
1274
1293
  return parts
1275
1294
  }
1276
1295
 
1296
+ // Keep unknown events available to direct client consumers; this layer
1297
+ // cannot translate provider-specific data into portable stream parts.
1298
+ if (isUnknownChatCompletionEvent(event)) {
1299
+ return parts
1300
+ }
1301
+
1277
1302
  if (event.service_tier !== undefined) {
1278
1303
  serviceTier = event.service_tier
1279
1304
  }
@@ -1461,6 +1486,12 @@ const unsupportedSchemaError = (error: unknown, method: string): AiError.AiError
1461
1486
  })
1462
1487
  })
1463
1488
 
1489
+ const tryCodecTransform = <S extends Schema.Constraint>(schema: S, method: string) =>
1490
+ Effect.try({
1491
+ try: () => toCodecOpenAI(schema),
1492
+ catch: (error) => unsupportedSchemaError(error, method)
1493
+ })
1494
+
1464
1495
  const tryJsonSchema = <S extends Schema.Constraint>(schema: S, method: string) =>
1465
1496
  Effect.try({
1466
1497
  try: () => Tool.getJsonSchemaFromSchema(schema, { transformer: toCodecOpenAI }),
@@ -1473,6 +1504,42 @@ const tryToolJsonSchema = <T extends Tool.Any>(tool: T, method: string) =>
1473
1504
  catch: (error) => unsupportedSchemaError(error, method)
1474
1505
  })
1475
1506
 
1507
+ const transformToolCallParams = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Tool.Any>>(
1508
+ tools: Tools,
1509
+ toolName: string,
1510
+ toolParams: unknown
1511
+ ): Effect.fn.Return<unknown, AiError.AiError> {
1512
+ const tool = tools.find((tool) => tool.name === toolName)
1513
+
1514
+ if (Predicate.isUndefined(tool)) {
1515
+ return yield* AiError.make({
1516
+ module: "OpenAiLanguageModel",
1517
+ method: "makeResponse",
1518
+ reason: new AiError.ToolNotFoundError({
1519
+ toolName,
1520
+ availableTools: tools.map((tool) => tool.name)
1521
+ })
1522
+ })
1523
+ }
1524
+
1525
+ const { codec } = yield* tryCodecTransform(tool.parametersSchema, "makeResponse")
1526
+ const transform = Schema.decodeEffect(codec)
1527
+
1528
+ return yield* (
1529
+ transform(toolParams) as Effect.Effect<unknown, Schema.SchemaError>
1530
+ ).pipe(Effect.mapError((error) =>
1531
+ AiError.make({
1532
+ module: "OpenAiLanguageModel",
1533
+ method: "makeResponse",
1534
+ reason: new AiError.ToolParameterValidationError({
1535
+ toolName,
1536
+ toolParams,
1537
+ description: formatIssue(error.issue)
1538
+ })
1539
+ })
1540
+ ))
1541
+ })
1542
+
1476
1543
  const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Tool.Any>>({
1477
1544
  config,
1478
1545
  options,
@@ -1611,7 +1678,7 @@ const extractCustomRequestProperties = (payload: CreateResponse): Record<string,
1611
1678
  const customProperties: Record<string, unknown> = {}
1612
1679
  for (const [key, value] of Object.entries(payload)) {
1613
1680
  if (!createResponseKnownProperties.has(key)) {
1614
- customProperties[key] = value
1681
+ Rec.assignProperty(customProperties, key, value)
1615
1682
  }
1616
1683
  }
1617
1684
  return customProperties
@@ -1723,7 +1790,24 @@ const toChatMessages = (
1723
1790
  const messages: Array<CreateResponseRequestJson["messages"][number]> = []
1724
1791
 
1725
1792
  for (const item of input) {
1726
- messages.push(...toChatMessagesFromItem(item))
1793
+ if (Predicate.hasProperty(item, "type") && item.type === "function_call") {
1794
+ const previous = messages.at(-1)
1795
+ const toolCall = toChatToolCall(item)
1796
+ if (previous?.role === "assistant" && previous.tool_calls !== undefined) {
1797
+ messages[messages.length - 1] = {
1798
+ ...previous,
1799
+ tool_calls: [...previous.tool_calls, toolCall]
1800
+ }
1801
+ } else {
1802
+ messages.push({
1803
+ role: "assistant",
1804
+ content: null,
1805
+ tool_calls: [toolCall]
1806
+ })
1807
+ }
1808
+ } else {
1809
+ messages.push(...toChatMessagesFromItem(item))
1810
+ }
1727
1811
  }
1728
1812
 
1729
1813
  return messages
@@ -1751,14 +1835,7 @@ const toChatMessagesFromItem = (
1751
1835
  return [{
1752
1836
  role: "assistant",
1753
1837
  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
- }]
1838
+ tool_calls: [toChatToolCall(item)]
1762
1839
  }]
1763
1840
  }
1764
1841
 
@@ -1776,6 +1853,17 @@ const toChatMessagesFromItem = (
1776
1853
  }
1777
1854
  }
1778
1855
 
1856
+ const toChatToolCall = (
1857
+ item: Extract<InputItem, { readonly type: "function_call" }>
1858
+ ): ChatCompletionRequestToolCall => ({
1859
+ id: item.call_id,
1860
+ type: "function",
1861
+ function: {
1862
+ name: item.name,
1863
+ arguments: item.arguments
1864
+ }
1865
+ })
1866
+
1779
1867
  const toAssistantChatMessageContent = (
1780
1868
  content: ReadonlyArray<{
1781
1869
  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
  }