@effect/ai-openai-compat 4.1.3 → 4.1.5

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.
@@ -545,6 +545,10 @@ declare module "effect/ai/Response" {
545
545
  * The service tier reported by the OpenAI-compatible provider.
546
546
  */
547
547
  readonly serviceTier?: "default" | "auto" | "flex" | "scale" | "priority" | null
548
+ /**
549
+ * The refusal explanation returned instead of content.
550
+ */
551
+ readonly refusal?: string | null
548
552
  } | null
549
553
  }
550
554
  }
@@ -665,6 +669,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
665
669
  const [rawResponse, response] = yield* client.createResponse(request)
666
670
  annotateResponse(options.span, rawResponse)
667
671
  return yield* makeResponse({
672
+ config,
668
673
  options,
669
674
  rawResponse,
670
675
  response,
@@ -681,6 +686,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
681
686
  annotateRequest(options.span, request)
682
687
  const [response, stream] = yield* client.createResponseStream(request)
683
688
  return yield* makeStreamResponse({
689
+ config,
684
690
  options,
685
691
  stream,
686
692
  response,
@@ -802,7 +808,7 @@ export const withConfigOverride: {
802
808
  // =============================================================================
803
809
 
804
810
  const getSystemMessageMode = (model: string): "system" | "developer" =>
805
- model.startsWith("o") ||
811
+ /^o\d/.test(model) ||
806
812
  model.startsWith("gpt-5") ||
807
813
  model.startsWith("codex-") ||
808
814
  model.startsWith("computer-use")
@@ -863,17 +869,28 @@ const prepareMessages = Effect.fnUntraced(
863
869
  } else if (part.mediaType === "application/pdf") {
864
870
  if (typeof part.data === "string" && isFileId(part.data, config)) {
865
871
  content.push({ type: "input_file", file_id: part.data })
866
- }
867
-
868
- if (part.data instanceof URL) {
869
- content.push({ type: "input_file", file_url: part.data.toString() })
870
- }
871
-
872
- if (part.data instanceof Uint8Array) {
873
- const base64 = Base64.encode(part.data)
874
- const fileName = part.fileName ?? `part-${index}.pdf`
875
- const fileData = `data:application/pdf;base64,${base64}`
876
- content.push({ type: "input_file", filename: fileName, file_data: fileData })
872
+ } else if (
873
+ part.data instanceof URL || (typeof part.data === "string" && /^https?:\/\//i.test(part.data))
874
+ ) {
875
+ return yield* AiError.make({
876
+ module: "OpenAiLanguageModel",
877
+ method: "prepareMessages",
878
+ reason: new AiError.InvalidUserInputError({
879
+ description: "Chat Completions does not support PDF URLs. " +
880
+ "Pass PDF bytes, base64 data, or a configured file ID instead."
881
+ })
882
+ })
883
+ } else {
884
+ const fileData = part.data instanceof Uint8Array
885
+ ? `data:application/pdf;base64,${Base64.encode(part.data)}`
886
+ : /^data:/i.test(part.data)
887
+ ? part.data
888
+ : `data:application/pdf;base64,${part.data}`
889
+ content.push({
890
+ type: "input_file",
891
+ filename: part.fileName ?? `part-${index}.pdf`,
892
+ file_data: fileData
893
+ })
877
894
  }
878
895
  } else {
879
896
  return yield* AiError.make({
@@ -1004,12 +1021,14 @@ type ActiveToolCall = {
1004
1021
 
1005
1022
  const makeResponse = Effect.fnUntraced(
1006
1023
  function*<Tools extends ReadonlyArray<Tool.Any>>({
1024
+ config,
1007
1025
  options,
1008
1026
  rawResponse,
1009
1027
  response,
1010
1028
  toolNameMapper,
1011
1029
  toolCodecs
1012
1030
  }: {
1031
+ readonly config: typeof Config.Service
1013
1032
  readonly options: LanguageModel.ProviderOptions
1014
1033
  readonly rawResponse: CreateResponse200
1015
1034
  readonly response: HttpClientResponse.HttpClientResponse
@@ -1046,7 +1065,7 @@ const makeResponse = Effect.fnUntraced(
1046
1065
  parts.push({ type: "text", text: message.content })
1047
1066
  }
1048
1067
 
1049
- if (message.tool_calls !== undefined) {
1068
+ if (Predicate.isNotNullish(message.tool_calls)) {
1050
1069
  for (const [index, toolCall] of message.tool_calls.entries()) {
1051
1070
  const toolId = toolCall.id ?? `${rawResponse.id}_tool_${index}`
1052
1071
  const toolName = toolNameMapper.getCustomName(toolCall.function?.name ?? "unknown_tool")
@@ -1063,7 +1082,7 @@ const makeResponse = Effect.fnUntraced(
1063
1082
  })
1064
1083
  })
1065
1084
  })
1066
- const params = yield* transformToolCallParams(options, toolName, toolParams, toolCodecs)
1085
+ const params = yield* transformToolCallParams(config, options, toolName, toolParams, toolCodecs)
1067
1086
  hasToolCalls = true
1068
1087
  parts.push({
1069
1088
  type: "tool-call",
@@ -1072,7 +1091,7 @@ const makeResponse = Effect.fnUntraced(
1072
1091
  params,
1073
1092
  metadata: {
1074
1093
  "openai-compat": {
1075
- ...makeItemIdMetadata(toolCall.id),
1094
+ ...makeItemIdMetadata(toolCall.id ?? undefined),
1076
1095
  ...makeExtraContentMetadata(toolCall.extra_content ?? undefined)
1077
1096
  }
1078
1097
  }
@@ -1081,18 +1100,24 @@ const makeResponse = Effect.fnUntraced(
1081
1100
  }
1082
1101
  }
1083
1102
 
1084
- const finishReason = InternalUtilities.resolveFinishReason(
1085
- choice?.finish_reason,
1086
- hasToolCalls
1087
- )
1088
- const serviceTier = normalizeServiceTier(rawResponse.service_tier)
1103
+ const refusal = message?.refusal
1104
+ const hasRefusal = Predicate.isNotNullish(refusal) && refusal.length > 0
1105
+ const finishReason = InternalUtilities.resolveFinishReason(choice?.finish_reason, hasToolCalls, hasRefusal)
1106
+ const serviceTier = normalizeServiceTier(rawResponse.service_tier ?? undefined)
1089
1107
 
1090
1108
  parts.push({
1091
1109
  type: "finish",
1092
1110
  reason: finishReason,
1093
1111
  usage: getUsage(rawResponse.usage),
1094
1112
  response: buildHttpResponseDetails(response),
1095
- ...(serviceTier !== undefined && { metadata: { "openai-compat": { serviceTier } } })
1113
+ ...((serviceTier !== undefined || hasRefusal) && {
1114
+ metadata: {
1115
+ "openai-compat": {
1116
+ ...(serviceTier !== undefined && { serviceTier }),
1117
+ ...(hasRefusal && { refusal })
1118
+ }
1119
+ }
1120
+ })
1096
1121
  })
1097
1122
 
1098
1123
  return parts
@@ -1101,12 +1126,14 @@ const makeResponse = Effect.fnUntraced(
1101
1126
 
1102
1127
  const makeStreamResponse = Effect.fnUntraced(
1103
1128
  function*<Tools extends ReadonlyArray<Tool.Any>>({
1129
+ config,
1104
1130
  options,
1105
1131
  stream,
1106
1132
  response,
1107
1133
  toolNameMapper,
1108
1134
  toolCodecs
1109
1135
  }: {
1136
+ readonly config: typeof Config.Service
1110
1137
  readonly options: LanguageModel.ProviderOptions
1111
1138
  readonly stream: Stream.Stream<ResponseStreamEvent, AiError.AiError>
1112
1139
  readonly response: HttpClientResponse.HttpClientResponse
@@ -1119,6 +1146,7 @@ const makeStreamResponse = Effect.fnUntraced(
1119
1146
  let serviceTier: string | undefined = undefined
1120
1147
  let usage: CreateResponse200["usage"] = undefined
1121
1148
  let finishReason: string | null | undefined = undefined
1149
+ let refusal = ""
1122
1150
  let metadataEmitted = false
1123
1151
  let textStarted = false
1124
1152
  let textId = ""
@@ -1162,7 +1190,7 @@ const makeStreamResponse = Effect.fnUntraced(
1162
1190
  })
1163
1191
  })
1164
1192
  })
1165
- const params = yield* transformToolCallParams(options, toolCall.name, parsedParams, toolCodecs)
1193
+ const params = yield* transformToolCallParams(config, options, toolCall.name, parsedParams, toolCodecs)
1166
1194
  parts.push({ type: "tool-params-end", id: toolCall.id })
1167
1195
  parts.push({
1168
1196
  type: "tool-call",
@@ -1180,13 +1208,21 @@ const makeStreamResponse = Effect.fnUntraced(
1180
1208
  }
1181
1209
 
1182
1210
  const normalizedServiceTier = normalizeServiceTier(serviceTier)
1211
+ const hasRefusal = refusal.length > 0
1183
1212
  parts.push({
1184
1213
  type: "finish",
1185
- reason: InternalUtilities.resolveFinishReason(finishReason, hasToolCalls),
1214
+ reason: InternalUtilities.resolveFinishReason(finishReason, hasToolCalls, hasRefusal),
1186
1215
  usage: getUsage(usage),
1187
1216
  response: buildHttpResponseDetails(response),
1188
- ...(normalizedServiceTier !== undefined
1189
- ? { metadata: { "openai-compat": { serviceTier: normalizedServiceTier } } }
1217
+ ...(normalizedServiceTier !== undefined || hasRefusal
1218
+ ? {
1219
+ metadata: {
1220
+ "openai-compat": {
1221
+ ...(normalizedServiceTier !== undefined ? { serviceTier: normalizedServiceTier } : undefined),
1222
+ ...(hasRefusal ? { refusal } : undefined)
1223
+ }
1224
+ }
1225
+ }
1190
1226
  : undefined)
1191
1227
  })
1192
1228
  return parts
@@ -1198,7 +1234,7 @@ const makeStreamResponse = Effect.fnUntraced(
1198
1234
  return parts
1199
1235
  }
1200
1236
 
1201
- if (event.service_tier !== undefined) {
1237
+ if (Predicate.isNotNullish(event.service_tier)) {
1202
1238
  serviceTier = event.service_tier
1203
1239
  }
1204
1240
  if (event.usage !== undefined && Predicate.isNotNull(event.usage)) {
@@ -1259,6 +1295,10 @@ const makeStreamResponse = Effect.fnUntraced(
1259
1295
  parts.push({ type: "text-delta", id: textId, delta: choice.delta.content })
1260
1296
  }
1261
1297
 
1298
+ if (Predicate.isNotNullish(choice.delta?.refusal)) {
1299
+ refusal += choice.delta.refusal
1300
+ }
1301
+
1262
1302
  if (Predicate.isNotNullish(choice.delta?.tool_calls)) {
1263
1303
  hasToolCalls = hasToolCalls || choice.delta.tool_calls.length > 0
1264
1304
  choice.delta.tool_calls.forEach((deltaTool, indexInChunk) => {
@@ -1344,7 +1384,7 @@ const annotateResponse = (span: Span, response: CreateResponse200): void => {
1344
1384
  },
1345
1385
  openai: {
1346
1386
  response: {
1347
- serviceTier: response.service_tier as string | undefined
1387
+ serviceTier: response.service_tier
1348
1388
  }
1349
1389
  }
1350
1390
  })
@@ -1410,10 +1450,14 @@ const toolParametersError = (tool: Tool.Any, error: unknown, method: string): Ai
1410
1450
  method
1411
1451
  )
1412
1452
 
1453
+ const getToolStrictMode = (tool: Tool.Any, config: typeof Config.Service): boolean =>
1454
+ Tool.getStrictMode(tool) ?? config.strictJsonSchema ?? true
1455
+
1413
1456
  type ToolCodec = ReturnType<typeof toCodecOpenAI>["codec"]
1414
1457
  type ToolCodecs = ReadonlyMap<Tool.Any, ToolCodec>
1415
1458
 
1416
1459
  const transformToolCallParams = Effect.fnUntraced(function*(
1460
+ config: typeof Config.Service,
1417
1461
  options: LanguageModel.ProviderOptions,
1418
1462
  toolName: string,
1419
1463
  toolParams: unknown,
@@ -1435,7 +1479,7 @@ const transformToolCallParams = Effect.fnUntraced(function*(
1435
1479
  })
1436
1480
  }
1437
1481
 
1438
- if (Tool.isDynamic(tool) && tool.jsonSchema !== undefined) {
1482
+ if (!getToolStrictMode(tool, config) || (Tool.isDynamic(tool) && tool.jsonSchema !== undefined)) {
1439
1483
  return toolParams
1440
1484
  }
1441
1485
 
@@ -1492,18 +1536,20 @@ const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Too
1492
1536
  // Convert the tools in the toolkit to the provider-defined format
1493
1537
  for (const tool of allowedTools) {
1494
1538
  if (Tool.isUserDefined(tool) || Tool.isDynamic(tool)) {
1495
- const strict = Tool.getStrictMode(tool) ?? config.strictJsonSchema ?? true
1539
+ const strict = getToolStrictMode(tool, config)
1496
1540
  let parameters: ReturnType<typeof Tool.getJsonSchema>
1497
1541
  if (Tool.isDynamic(tool) && tool.jsonSchema !== undefined) {
1498
1542
  parameters = tool.jsonSchema
1499
1543
  } else {
1500
1544
  const prepared = yield* Effect.try({
1501
- try: () => toCodecOpenAI(tool.parametersSchema),
1545
+ try: () => (strict ? toCodecOpenAI : LanguageModel.defaultCodecTransformer)(tool.parametersSchema),
1502
1546
  catch: (error) => toolParametersError(tool, error, "prepareTools")
1503
1547
  })
1504
1548
  parameters = prepared.jsonSchema
1505
- // Reused to normalize this tool's calls in the response.
1506
- toolCodecs.set(tool, prepared.codec)
1549
+ if (strict) {
1550
+ // Reused to normalize this tool's calls in the response.
1551
+ toolCodecs.set(tool, prepared.codec)
1552
+ }
1507
1553
  }
1508
1554
  tools.push({
1509
1555
  type: "function",
@@ -1745,13 +1791,14 @@ const toChatMessageContent = (
1745
1791
  break
1746
1792
  }
1747
1793
  case "input_file": {
1748
- if (part.file_url !== undefined) {
1749
- parts.push({ type: "text", text: part.file_url })
1750
- } else if (part.file_data !== undefined) {
1751
- parts.push({ type: "text", text: part.file_data })
1752
- } else if (part.file_id !== undefined) {
1753
- parts.push({ type: "text", text: `openai://file/${part.file_id}` })
1754
- }
1794
+ parts.push({
1795
+ type: "file",
1796
+ file: {
1797
+ ...(part.filename !== undefined ? { filename: part.filename } : undefined),
1798
+ ...(part.file_data !== undefined ? { file_data: part.file_data } : undefined),
1799
+ ...(Predicate.isNotNullish(part.file_id) ? { file_id: part.file_id } : undefined)
1800
+ }
1801
+ })
1755
1802
  break
1756
1803
  }
1757
1804
  }
@@ -11,8 +11,12 @@ const finishReasonMap: Record<string, Response.FinishReason> = {
11
11
  /** @internal */
12
12
  export const resolveFinishReason = (
13
13
  finishReason: string | null | undefined,
14
- hasToolCalls: boolean
14
+ hasToolCalls: boolean,
15
+ hasRefusal: boolean
15
16
  ): Response.FinishReason => {
17
+ if (hasRefusal && finishReason === "stop") {
18
+ return "content-filter"
19
+ }
16
20
  if (finishReason == null) {
17
21
  return hasToolCalls ? "tool-calls" : "stop"
18
22
  }