@effect/ai-openai-compat 4.0.0-beta.101 → 4.0.0-beta.103

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.
@@ -16,8 +16,9 @@ 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"
22
23
  import * as Stream from "effect/Stream"
23
24
  import type { Span } from "effect/Tracer"
@@ -35,6 +36,7 @@ import * as InternalUtilities from "./internal/utilities.ts"
35
36
  import {
36
37
  type Annotation,
37
38
  type ChatCompletionContentPart,
39
+ type ChatCompletionRequestToolCall,
38
40
  type CreateResponse,
39
41
  type CreateResponse200,
40
42
  type CreateResponse200Sse,
@@ -47,7 +49,8 @@ import {
47
49
  type ReasoningItem,
48
50
  type SummaryTextContent,
49
51
  type TextResponseFormatConfiguration,
50
- type Tool as OpenAiClientTool
52
+ type Tool as OpenAiClientTool,
53
+ type UnknownChatCompletionEvent
51
54
  } from "./OpenAiClient.ts"
52
55
  import { addGenAIAnnotations } from "./OpenAiTelemetry.ts"
53
56
 
@@ -108,7 +111,7 @@ type ModelConfig = Omit<ConfigOptions, "model"> & { readonly [x: string]: unknow
108
111
  *
109
112
  * @see {@link withConfigOverride} for scoping language model request overrides
110
113
  *
111
- * @category context
114
+ * @category services
112
115
  * @since 4.0.0
113
116
  */
114
117
  export class Config extends Context.Service<
@@ -124,7 +127,7 @@ declare module "effect/unstable/ai/Prompt" {
124
127
  /**
125
128
  * OpenAI-compatible options for file prompt parts.
126
129
  *
127
- * @category request
130
+ * @category models
128
131
  * @since 4.0.0
129
132
  */
130
133
  export interface FilePartOptions extends ProviderOptions {
@@ -142,7 +145,7 @@ declare module "effect/unstable/ai/Prompt" {
142
145
  /**
143
146
  * OpenAI-compatible options for reasoning prompt parts.
144
147
  *
145
- * @category request
148
+ * @category models
146
149
  * @since 4.0.0
147
150
  */
148
151
  export interface ReasoningPartOptions extends ProviderOptions {
@@ -166,7 +169,7 @@ declare module "effect/unstable/ai/Prompt" {
166
169
  /**
167
170
  * OpenAI-compatible options for assistant tool-call prompt parts.
168
171
  *
169
- * @category request
172
+ * @category models
170
173
  * @since 4.0.0
171
174
  */
172
175
  export interface ToolCallPartOptions extends ProviderOptions {
@@ -188,7 +191,7 @@ declare module "effect/unstable/ai/Prompt" {
188
191
  /**
189
192
  * OpenAI-compatible options for tool-result prompt parts.
190
193
  *
191
- * @category request
194
+ * @category models
192
195
  * @since 4.0.0
193
196
  */
194
197
  export interface ToolResultPartOptions extends ProviderOptions {
@@ -210,7 +213,7 @@ declare module "effect/unstable/ai/Prompt" {
210
213
  /**
211
214
  * OpenAI-compatible options for text prompt parts.
212
215
  *
213
- * @category request
216
+ * @category models
214
217
  * @since 4.0.0
215
218
  */
216
219
  export interface TextPartOptions extends ProviderOptions {
@@ -238,7 +241,7 @@ declare module "effect/unstable/ai/Response" {
238
241
  /**
239
242
  * OpenAI-compatible metadata attached to a complete text response part.
240
243
  *
241
- * @category response
244
+ * @category models
242
245
  * @since 4.0.0
243
246
  */
244
247
  export interface TextPartMetadata extends ProviderMetadata {
@@ -270,7 +273,7 @@ declare module "effect/unstable/ai/Response" {
270
273
  /**
271
274
  * OpenAI-compatible metadata emitted when a streamed text part starts.
272
275
  *
273
- * @category response
276
+ * @category models
274
277
  * @since 4.0.0
275
278
  */
276
279
  export interface TextStartPartMetadata extends ProviderMetadata {
@@ -288,7 +291,7 @@ declare module "effect/unstable/ai/Response" {
288
291
  /**
289
292
  * OpenAI-compatible metadata emitted when a streamed text part ends.
290
293
  *
291
- * @category response
294
+ * @category models
292
295
  * @since 4.0.0
293
296
  */
294
297
  export interface TextEndPartMetadata extends ProviderMetadata {
@@ -310,7 +313,7 @@ declare module "effect/unstable/ai/Response" {
310
313
  /**
311
314
  * OpenAI-compatible metadata attached to a complete reasoning response part.
312
315
  *
313
- * @category response
316
+ * @category models
314
317
  * @since 4.0.0
315
318
  */
316
319
  export interface ReasoningPartMetadata extends ProviderMetadata {
@@ -332,7 +335,7 @@ declare module "effect/unstable/ai/Response" {
332
335
  /**
333
336
  * OpenAI-compatible metadata emitted when a streamed reasoning part starts.
334
337
  *
335
- * @category response
338
+ * @category models
336
339
  * @since 4.0.0
337
340
  */
338
341
  export interface ReasoningStartPartMetadata extends ProviderMetadata {
@@ -354,7 +357,7 @@ declare module "effect/unstable/ai/Response" {
354
357
  /**
355
358
  * OpenAI-compatible metadata emitted for a streamed reasoning delta.
356
359
  *
357
- * @category response
360
+ * @category models
358
361
  * @since 4.0.0
359
362
  */
360
363
  export interface ReasoningDeltaPartMetadata extends ProviderMetadata {
@@ -372,7 +375,7 @@ declare module "effect/unstable/ai/Response" {
372
375
  /**
373
376
  * OpenAI-compatible metadata emitted when a streamed reasoning part ends.
374
377
  *
375
- * @category response
378
+ * @category models
376
379
  * @since 4.0.0
377
380
  */
378
381
  export interface ReasoningEndPartMetadata extends ProviderMetadata {
@@ -394,7 +397,7 @@ declare module "effect/unstable/ai/Response" {
394
397
  /**
395
398
  * OpenAI-compatible metadata attached to tool-call response parts.
396
399
  *
397
- * @category response
400
+ * @category models
398
401
  * @since 4.0.0
399
402
  */
400
403
  export interface ToolCallPartMetadata extends ProviderMetadata {
@@ -412,7 +415,7 @@ declare module "effect/unstable/ai/Response" {
412
415
  /**
413
416
  * OpenAI-compatible metadata attached to document source citations.
414
417
  *
415
- * @category response
418
+ * @category models
416
419
  * @since 4.0.0
417
420
  */
418
421
  export interface DocumentSourcePartMetadata extends ProviderMetadata {
@@ -468,7 +471,7 @@ declare module "effect/unstable/ai/Response" {
468
471
  /**
469
472
  * OpenAI-compatible metadata attached to URL source citations.
470
473
  *
471
- * @category response
474
+ * @category models
472
475
  * @since 4.0.0
473
476
  */
474
477
  export interface UrlSourcePartMetadata extends ProviderMetadata {
@@ -494,7 +497,7 @@ declare module "effect/unstable/ai/Response" {
494
497
  /**
495
498
  * OpenAI-compatible metadata attached to finish response parts.
496
499
  *
497
- * @category response
500
+ * @category models
498
501
  * @since 4.0.0
499
502
  */
500
503
  export interface FinishPartMetadata extends ProviderMetadata {
@@ -628,6 +631,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
628
631
  const [rawResponse, response] = yield* client.createResponse(request)
629
632
  annotateResponse(options.span, rawResponse)
630
633
  return yield* makeResponse({
634
+ options,
631
635
  rawResponse,
632
636
  response,
633
637
  toolNameMapper
@@ -642,6 +646,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
642
646
  annotateRequest(options.span, request)
643
647
  const [response, stream] = yield* client.createResponseStream(request)
644
648
  return yield* makeStreamResponse({
649
+ options,
645
650
  stream,
646
651
  response,
647
652
  toolNameMapper
@@ -898,7 +903,7 @@ const prepareMessages = Effect.fnUntraced(
898
903
  }
899
904
 
900
905
  case "assistant": {
901
- const reasoningMessages: Record<string, DeepMutable<ReasoningItem>> = {}
906
+ const reasoningMessages: Record<string, DeepMutable<ReasoningItem>> = Object.create(null)
902
907
 
903
908
  for (const part of message.content) {
904
909
  switch (part.type) {
@@ -1096,6 +1101,11 @@ const buildHttpResponseDetails = (
1096
1101
 
1097
1102
  type ResponseStreamEvent = CreateResponse200Sse
1098
1103
 
1104
+ const isUnknownChatCompletionEvent = (
1105
+ event: ResponseStreamEvent
1106
+ ): event is UnknownChatCompletionEvent =>
1107
+ typeof event !== "string" && "_tag" in event && event._tag === "UnknownChatCompletionEvent"
1108
+
1099
1109
  type ActiveToolCall = {
1100
1110
  readonly id: string
1101
1111
  name: string
@@ -1104,10 +1114,12 @@ type ActiveToolCall = {
1104
1114
 
1105
1115
  const makeResponse = Effect.fnUntraced(
1106
1116
  function*<Tools extends ReadonlyArray<Tool.Any>>({
1117
+ options,
1107
1118
  rawResponse,
1108
1119
  response,
1109
1120
  toolNameMapper
1110
1121
  }: {
1122
+ readonly options: LanguageModel.ProviderOptions
1111
1123
  readonly rawResponse: CreateResponse200
1112
1124
  readonly response: HttpClientResponse.HttpClientResponse
1113
1125
  readonly toolNameMapper: Tool.NameMapper<Tools>
@@ -1146,9 +1158,9 @@ const makeResponse = Effect.fnUntraced(
1146
1158
  for (const [index, toolCall] of message.tool_calls.entries()) {
1147
1159
  const toolId = toolCall.id ?? `${rawResponse.id}_tool_${index}`
1148
1160
  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),
1161
+ const toolParamsJson = toolCall.function?.arguments ?? "{}"
1162
+ const toolParams = yield* Effect.try({
1163
+ try: () => Tool.unsafeSecureJsonParse(toolParamsJson),
1152
1164
  catch: (cause) =>
1153
1165
  AiError.make({
1154
1166
  module: "OpenAiLanguageModel",
@@ -1160,6 +1172,7 @@ const makeResponse = Effect.fnUntraced(
1160
1172
  })
1161
1173
  })
1162
1174
  })
1175
+ const params = yield* transformToolCallParams(options.tools, toolName, toolParams)
1163
1176
  hasToolCalls = true
1164
1177
  parts.push({
1165
1178
  type: "tool-call",
@@ -1192,10 +1205,12 @@ const makeResponse = Effect.fnUntraced(
1192
1205
 
1193
1206
  const makeStreamResponse = Effect.fnUntraced(
1194
1207
  function*<Tools extends ReadonlyArray<Tool.Any>>({
1208
+ options,
1195
1209
  stream,
1196
1210
  response,
1197
1211
  toolNameMapper
1198
1212
  }: {
1213
+ readonly options: LanguageModel.ProviderOptions
1199
1214
  readonly stream: Stream.Stream<ResponseStreamEvent, AiError.AiError>
1200
1215
  readonly response: HttpClientResponse.HttpClientResponse
1201
1216
  readonly toolNameMapper: Tool.NameMapper<Tools>
@@ -1237,7 +1252,7 @@ const makeStreamResponse = Effect.fnUntraced(
1237
1252
 
1238
1253
  for (const toolCall of Object.values(activeToolCalls)) {
1239
1254
  const toolParams = toolCall.arguments.length > 0 ? toolCall.arguments : "{}"
1240
- const params = yield* Effect.try({
1255
+ const parsedParams = yield* Effect.try({
1241
1256
  try: () => Tool.unsafeSecureJsonParse(toolParams),
1242
1257
  catch: (cause) =>
1243
1258
  AiError.make({
@@ -1250,6 +1265,7 @@ const makeStreamResponse = Effect.fnUntraced(
1250
1265
  })
1251
1266
  })
1252
1267
  })
1268
+ const params = yield* transformToolCallParams(options.tools, toolCall.name, parsedParams)
1253
1269
  parts.push({ type: "tool-params-end", id: toolCall.id })
1254
1270
  parts.push({
1255
1271
  type: "tool-call",
@@ -1274,6 +1290,12 @@ const makeStreamResponse = Effect.fnUntraced(
1274
1290
  return parts
1275
1291
  }
1276
1292
 
1293
+ // Keep unknown events available to direct client consumers; this layer
1294
+ // cannot translate provider-specific data into portable stream parts.
1295
+ if (isUnknownChatCompletionEvent(event)) {
1296
+ return parts
1297
+ }
1298
+
1277
1299
  if (event.service_tier !== undefined) {
1278
1300
  serviceTier = event.service_tier
1279
1301
  }
@@ -1461,6 +1483,12 @@ const unsupportedSchemaError = (error: unknown, method: string): AiError.AiError
1461
1483
  })
1462
1484
  })
1463
1485
 
1486
+ const tryCodecTransform = <S extends Schema.Constraint>(schema: S, method: string) =>
1487
+ Effect.try({
1488
+ try: () => toCodecOpenAI(schema),
1489
+ catch: (error) => unsupportedSchemaError(error, method)
1490
+ })
1491
+
1464
1492
  const tryJsonSchema = <S extends Schema.Constraint>(schema: S, method: string) =>
1465
1493
  Effect.try({
1466
1494
  try: () => Tool.getJsonSchemaFromSchema(schema, { transformer: toCodecOpenAI }),
@@ -1473,6 +1501,42 @@ const tryToolJsonSchema = <T extends Tool.Any>(tool: T, method: string) =>
1473
1501
  catch: (error) => unsupportedSchemaError(error, method)
1474
1502
  })
1475
1503
 
1504
+ const transformToolCallParams = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Tool.Any>>(
1505
+ tools: Tools,
1506
+ toolName: string,
1507
+ toolParams: unknown
1508
+ ): Effect.fn.Return<unknown, AiError.AiError> {
1509
+ const tool = tools.find((tool) => tool.name === toolName)
1510
+
1511
+ if (Predicate.isUndefined(tool)) {
1512
+ return yield* AiError.make({
1513
+ module: "OpenAiLanguageModel",
1514
+ method: "makeResponse",
1515
+ reason: new AiError.ToolNotFoundError({
1516
+ toolName,
1517
+ availableTools: tools.map((tool) => tool.name)
1518
+ })
1519
+ })
1520
+ }
1521
+
1522
+ const { codec } = yield* tryCodecTransform(tool.parametersSchema, "makeResponse")
1523
+ const transform = Schema.decodeEffect(codec)
1524
+
1525
+ return yield* (
1526
+ transform(toolParams) as Effect.Effect<unknown, Schema.SchemaError>
1527
+ ).pipe(Effect.mapError((error) =>
1528
+ AiError.make({
1529
+ module: "OpenAiLanguageModel",
1530
+ method: "makeResponse",
1531
+ reason: new AiError.ToolParameterValidationError({
1532
+ toolName,
1533
+ toolParams,
1534
+ description: error.issue.toString()
1535
+ })
1536
+ })
1537
+ ))
1538
+ })
1539
+
1476
1540
  const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Tool.Any>>({
1477
1541
  config,
1478
1542
  options,
@@ -1611,7 +1675,7 @@ const extractCustomRequestProperties = (payload: CreateResponse): Record<string,
1611
1675
  const customProperties: Record<string, unknown> = {}
1612
1676
  for (const [key, value] of Object.entries(payload)) {
1613
1677
  if (!createResponseKnownProperties.has(key)) {
1614
- customProperties[key] = value
1678
+ Rec.assignProperty(customProperties, key, value)
1615
1679
  }
1616
1680
  }
1617
1681
  return customProperties
@@ -1723,7 +1787,24 @@ const toChatMessages = (
1723
1787
  const messages: Array<CreateResponseRequestJson["messages"][number]> = []
1724
1788
 
1725
1789
  for (const item of input) {
1726
- messages.push(...toChatMessagesFromItem(item))
1790
+ if (Predicate.hasProperty(item, "type") && item.type === "function_call") {
1791
+ const previous = messages.at(-1)
1792
+ const toolCall = toChatToolCall(item)
1793
+ if (previous?.role === "assistant" && previous.tool_calls !== undefined) {
1794
+ messages[messages.length - 1] = {
1795
+ ...previous,
1796
+ tool_calls: [...previous.tool_calls, toolCall]
1797
+ }
1798
+ } else {
1799
+ messages.push({
1800
+ role: "assistant",
1801
+ content: null,
1802
+ tool_calls: [toolCall]
1803
+ })
1804
+ }
1805
+ } else {
1806
+ messages.push(...toChatMessagesFromItem(item))
1807
+ }
1727
1808
  }
1728
1809
 
1729
1810
  return messages
@@ -1751,14 +1832,7 @@ const toChatMessagesFromItem = (
1751
1832
  return [{
1752
1833
  role: "assistant",
1753
1834
  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
- }]
1835
+ tool_calls: [toChatToolCall(item)]
1762
1836
  }]
1763
1837
  }
1764
1838
 
@@ -1776,6 +1850,17 @@ const toChatMessagesFromItem = (
1776
1850
  }
1777
1851
  }
1778
1852
 
1853
+ const toChatToolCall = (
1854
+ item: Extract<InputItem, { readonly type: "function_call" }>
1855
+ ): ChatCompletionRequestToolCall => ({
1856
+ id: item.call_id,
1857
+ type: "function",
1858
+ function: {
1859
+ name: item.name,
1860
+ arguments: item.arguments
1861
+ }
1862
+ })
1863
+
1779
1864
  const toAssistantChatMessageContent = (
1780
1865
  content: ReadonlyArray<{
1781
1866
  readonly type: string
@@ -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
  }