@effect/ai-openai-compat 4.0.2 → 4.0.4

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.
@@ -32,23 +32,20 @@ import * as Schema from "effect/Schema"
32
32
  import * as AST from "effect/SchemaAST"
33
33
  import * as Stream from "effect/Stream"
34
34
  import type { Span } from "effect/Tracer"
35
- import type { DeepMutable, Simplify } from "effect/Types"
35
+ import type { Simplify } from "effect/Types"
36
36
  import * as InternalUtilities from "./internal/utilities.ts"
37
37
  import {
38
38
  type Annotation,
39
39
  type ChatCompletionContentPart,
40
+ type ChatCompletionRequestMessage,
40
41
  type ChatCompletionRequestToolCall,
41
42
  type CreateResponse,
42
43
  type CreateResponse200,
43
44
  type CreateResponse200Sse,
44
45
  type CreateResponseRequestJson,
45
- type IncludeEnum,
46
46
  type InputContent,
47
- type InputItem,
48
47
  type MessageStatus,
49
48
  OpenAiClient,
50
- type ReasoningItem,
51
- type SummaryTextContent,
52
49
  type TextResponseFormatConfiguration,
53
50
  type Tool as OpenAiClientTool,
54
51
  type UnknownChatCompletionEvent
@@ -66,7 +63,7 @@ type ImageDetail = "auto" | "low" | "high"
66
63
 
67
64
  type ConfigOptions = Simplify<
68
65
  & Partial<
69
- Omit<CreateResponse, "input" | "tools" | "tool_choice" | "stream" | "text">
66
+ Omit<CreateResponse, "input" | "tools" | "tool_choice" | "stream" | "text" | "store" | "conversation">
70
67
  >
71
68
  & {
72
69
  /**
@@ -167,6 +164,12 @@ declare module "effect/ai/Prompt" {
167
164
  * parameter.
168
165
  */
169
166
  readonly encryptedContent?: string | null
167
+ /**
168
+ * The chat message field the reasoning was returned under. Replayed
169
+ * reasoning is sent back under the same field, defaulting to
170
+ * `reasoning_content`.
171
+ */
172
+ readonly reasoningField?: "reasoning" | "reasoning_content" | null
170
173
  } | null
171
174
  }
172
175
 
@@ -190,6 +193,10 @@ declare module "effect/ai/Prompt" {
190
193
  * The status to send for the tool-call item.
191
194
  */
192
195
  readonly status?: MessageStatus | null
196
+ /**
197
+ * Provider-specific extra content to echo back with the tool call.
198
+ */
199
+ readonly extraContent?: Schema.JsonObject | null
193
200
  } | null
194
201
  }
195
202
 
@@ -340,6 +347,10 @@ declare module "effect/ai/Response" {
340
347
  * Encrypted reasoning content that can be sent back in later requests.
341
348
  */
342
349
  readonly encryptedContent?: string | null
350
+ /**
351
+ * The chat message field the provider returned the reasoning under.
352
+ */
353
+ readonly reasoningField?: "reasoning" | "reasoning_content" | null
343
354
  } | null
344
355
  }
345
356
 
@@ -363,6 +374,10 @@ declare module "effect/ai/Response" {
363
374
  * Encrypted reasoning content that can be sent back in later requests.
364
375
  */
365
376
  readonly encryptedContent?: string | null
377
+ /**
378
+ * The chat message field the provider returned the reasoning under.
379
+ */
380
+ readonly reasoningField?: "reasoning" | "reasoning_content" | null
366
381
  } | null
367
382
  }
368
383
 
@@ -424,6 +439,10 @@ declare module "effect/ai/Response" {
424
439
  * The OpenAI item ID associated with the tool call.
425
440
  */
426
441
  readonly itemId?: string | null
442
+ /**
443
+ * Provider-specific extra content returned with the tool call.
444
+ */
445
+ readonly extraContent?: Schema.JsonObject | null
427
446
  } | null
428
447
  }
429
448
 
@@ -604,17 +623,16 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
604
623
  readonly config: typeof Config.Service
605
624
  readonly options: LanguageModel.ProviderOptions
606
625
  readonly toolNameMapper: Tool.NameMapper<Tools>
607
- }): Effect.fn.Return<CreateResponseRequestJson, AiError.AiError> {
608
- const include = new Set<IncludeEnum>()
609
- const capabilities = getModelCapabilities(config.model!)
626
+ }): Effect.fn.Return<{
627
+ readonly request: CreateResponseRequestJson
628
+ readonly toolCodecs: ToolCodecs
629
+ }, AiError.AiError> {
610
630
  const messages = yield* prepareMessages({
611
631
  config,
612
632
  options,
613
- capabilities,
614
- include,
615
633
  toolNameMapper
616
634
  })
617
- const { toolChoice, tools } = yield* prepareTools({
635
+ const { toolChoice, toolCodecs, tools } = yield* prepareTools({
618
636
  config,
619
637
  options,
620
638
  toolNameMapper
@@ -626,8 +644,6 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
626
644
  const { fileIdPrefixes: _fip, strictJsonSchema: _sjs, ...apiConfig } = config
627
645
  const request: CreateResponse = {
628
646
  ...apiConfig,
629
- input: messages,
630
- include: include.size > 0 ? Array.from(include) : null,
631
647
  text: {
632
648
  verbosity: config.text?.verbosity ?? null,
633
649
  format: responseFormat
@@ -635,7 +651,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
635
651
  ...(tools !== undefined ? { tools } : undefined),
636
652
  ...(toolChoice !== undefined ? { tool_choice: toolChoice } : undefined)
637
653
  }
638
- return toChatCompletionsRequest(request)
654
+ return { request: toChatCompletionsRequest(request, messages), toolCodecs }
639
655
  }
640
656
  )
641
657
 
@@ -645,7 +661,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
645
661
  function*(options) {
646
662
  const config = yield* makeConfig
647
663
  const toolNameMapper = new Tool.NameMapper(options.tools)
648
- const request = yield* makeRequest({ config, options, toolNameMapper })
664
+ const { request, toolCodecs } = yield* makeRequest({ config, options, toolNameMapper })
649
665
  annotateRequest(options.span, request)
650
666
  const [rawResponse, response] = yield* client.createResponse(request)
651
667
  annotateResponse(options.span, rawResponse)
@@ -653,7 +669,8 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
653
669
  options,
654
670
  rawResponse,
655
671
  response,
656
- toolNameMapper
672
+ toolNameMapper,
673
+ toolCodecs
657
674
  })
658
675
  }
659
676
  ),
@@ -661,14 +678,15 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
661
678
  function*(options) {
662
679
  const config = yield* makeConfig
663
680
  const toolNameMapper = new Tool.NameMapper(options.tools)
664
- const request = yield* makeRequest({ config, options, toolNameMapper })
681
+ const { request, toolCodecs } = yield* makeRequest({ config, options, toolNameMapper })
665
682
  annotateRequest(options.span, request)
666
683
  const [response, stream] = yield* client.createResponseStream(request)
667
684
  return yield* makeStreamResponse({
668
685
  options,
669
686
  stream,
670
687
  response,
671
- toolNameMapper
688
+ toolNameMapper,
689
+ toolCodecs
672
690
  })
673
691
  },
674
692
  (effect, options) =>
@@ -832,27 +850,13 @@ const prepareMessages = Effect.fnUntraced(
832
850
  function*<Tools extends ReadonlyArray<Tool.Any>>({
833
851
  config,
834
852
  options,
835
- capabilities,
836
- include,
837
853
  toolNameMapper
838
854
  }: {
839
855
  readonly config: typeof Config.Service
840
856
  readonly options: LanguageModel.ProviderOptions
841
- readonly include: Set<IncludeEnum>
842
- readonly capabilities: ModelCapabilities
843
857
  readonly toolNameMapper: Tool.NameMapper<Tools>
844
- }): Effect.fn.Return<ReadonlyArray<InputItem>, AiError.AiError> {
845
- const hasConversation = Predicate.isNotNullish(config.conversation)
846
-
847
- // Handle Included Features
848
- if (config.top_logprobs !== undefined) {
849
- include.add("message.output_text.logprobs")
850
- }
851
- if (config.store === false && capabilities.isReasoningModel) {
852
- include.add("reasoning.encrypted_content")
853
- }
854
-
855
- const messages: Array<InputItem> = []
858
+ }): Effect.fn.Return<ReadonlyArray<ChatCompletionRequestMessage>, AiError.AiError> {
859
+ const messages: Array<ChatCompletionRequestMessage> = []
856
860
 
857
861
  for (const message of options.prompt.content) {
858
862
  switch (message.role) {
@@ -921,155 +925,62 @@ const prepareMessages = Effect.fnUntraced(
921
925
  }
922
926
  }
923
927
 
924
- messages.push({ role: "user", content })
928
+ messages.push({ role: "user", content: toChatMessageContent(content) })
925
929
 
926
930
  break
927
931
  }
928
932
 
929
933
  case "assistant": {
930
- const reasoningMessages: Record<string, DeepMutable<ReasoningItem>> = Object.create(null)
934
+ let content: string | null = null
935
+ let reasoning = ""
936
+ let reasoningField: ReasoningField | undefined
937
+ const toolCalls: Array<ChatCompletionRequestToolCall> = []
931
938
 
932
939
  for (const part of message.content) {
933
940
  switch (part.type) {
934
941
  case "text": {
935
- const id = getItemId(part)
936
-
937
- // When in conversation mode, skip items that already exist in the
938
- // conversation context to avoid "Duplicate item found" errors
939
- if (hasConversation && Predicate.isNotNull(id)) {
940
- break
941
- }
942
-
943
- if (config.store === true && Predicate.isNotNull(id)) {
944
- messages.push({ type: "item_reference", id })
945
- break
946
- }
947
-
948
- messages.push({
949
- id: id!,
950
- type: "message",
951
- role: "assistant",
952
- status: part.options.openai?.status ?? "completed",
953
- content: [{
954
- type: "output_text",
955
- text: part.text,
956
- annotations: part.options.openai?.annotations ?? [],
957
- logprobs: []
958
- }]
959
- })
960
-
942
+ content = (content ?? "") + part.text
961
943
  break
962
944
  }
963
945
 
964
946
  case "reasoning": {
965
- const id = getItemId(part)
966
- const encryptedContent = getEncryptedContent(part)
967
-
968
- if (hasConversation && Predicate.isNotNull(id)) {
969
- break
970
- }
971
-
972
- if (Predicate.isNotNull(id)) {
973
- const message = reasoningMessages[id]
974
-
975
- if (config.store === true) {
976
- // Use item references to refer to reasoning (single reference)
977
- // when the first part is encountered
978
- if (Predicate.isUndefined(message)) {
979
- messages.push({ type: "item_reference", id })
980
-
981
- // Store unused reasoning message to mark its id as used
982
- reasoningMessages[id] = {
983
- type: "reasoning",
984
- id,
985
- summary: []
986
- }
987
- }
988
- } else {
989
- const summaryParts: Array<SummaryTextContent> = []
990
-
991
- if (part.text.length > 0) {
992
- summaryParts.push({ type: "summary_text", text: part.text })
993
- }
994
-
995
- if (Predicate.isUndefined(message)) {
996
- reasoningMessages[id] = {
997
- type: "reasoning",
998
- id,
999
- summary: summaryParts,
1000
- encrypted_content: encryptedContent ?? null
1001
- }
1002
-
1003
- messages.push(reasoningMessages[id])
1004
- } else {
1005
- message.summary.push(...summaryParts)
1006
-
1007
- // Update encrypted content to enable setting it in the
1008
- // last summary part
1009
- if (Predicate.isNotNull(encryptedContent)) {
1010
- message.encrypted_content = encryptedContent
1011
- }
1012
- }
1013
- }
1014
- }
1015
-
947
+ reasoning += part.text
948
+ reasoningField ??= part.options.openai?.reasoningField ?? undefined
1016
949
  break
1017
950
  }
1018
951
 
1019
952
  case "tool-call": {
1020
- const id = getItemId(part)
1021
- const status = getStatus(part)
1022
-
1023
- if (hasConversation && Predicate.isNotNull(id)) {
1024
- break
1025
- }
1026
-
1027
- if (config.store && Predicate.isNotNull(id)) {
1028
- messages.push({ type: "item_reference", id })
1029
- break
1030
- }
1031
-
1032
953
  if (part.providerExecuted) {
1033
954
  break
1034
955
  }
1035
956
 
1036
- const toolName = toolNameMapper.getProviderName(part.name)
957
+ const extraContent = getExtraContent(part)
1037
958
 
1038
- messages.push({
1039
- type: "function_call",
1040
- name: toolName,
1041
- call_id: part.id,
1042
- arguments: JSON.stringify(part.params),
1043
- ...(Predicate.isNotNull(id) ? { id } : {}),
1044
- ...(Predicate.isNotNull(status) ? { status } : {})
959
+ toolCalls.push({
960
+ id: part.id,
961
+ type: "function",
962
+ function: {
963
+ name: toolNameMapper.getProviderName(part.name),
964
+ arguments: JSON.stringify(part.params)
965
+ },
966
+ ...(Predicate.isNotNull(extraContent) ? { extra_content: extraContent } : undefined)
1045
967
  })
1046
-
1047
968
  break
1048
969
  }
1049
-
1050
- // Assistant tool-result parts are always provider executed
1051
- case "tool-result": {
1052
- // Skip execution denied results - these have no corresponding
1053
- // item in OpenAI's store
1054
- if (
1055
- Predicate.hasProperty(part.result, "type") &&
1056
- part.result.type === "execution-denied"
1057
- ) {
1058
- break
1059
- }
1060
-
1061
- if (hasConversation) {
1062
- break
1063
- }
1064
-
1065
- if (config.store === true) {
1066
- const id = getItemId(part) ?? part.id
1067
- messages.push({ type: "item_reference", id })
1068
- }
1069
- }
1070
970
  }
1071
971
  }
1072
972
 
973
+ // Text, reasoning and tool calls from one prompt message are sent as a
974
+ // single chat message so reasoning stays attached to its tool calls
975
+ if (content !== null || toolCalls.length > 0) {
976
+ messages.push({
977
+ role: "assistant",
978
+ content,
979
+ ...(reasoning.length > 0 ? { [reasoningField ?? "reasoning_content"]: reasoning } : undefined),
980
+ ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : undefined)
981
+ })
982
+ }
983
+
1073
984
  break
1074
985
  }
1075
986
 
@@ -1079,13 +990,10 @@ const prepareMessages = Effect.fnUntraced(
1079
990
  continue
1080
991
  }
1081
992
 
1082
- const status = getStatus(part)
1083
-
1084
993
  messages.push({
1085
- type: "function_call_output",
1086
- call_id: part.id,
1087
- output: typeof part.result === "string" ? part.result : JSON.stringify(part.result),
1088
- ...(Predicate.isNotNull(status) ? { status } : {})
994
+ role: "tool",
995
+ tool_call_id: part.id,
996
+ content: typeof part.result === "string" ? part.result : JSON.stringify(part.result)
1089
997
  })
1090
998
  }
1091
999
 
@@ -1134,6 +1042,7 @@ type ActiveToolCall = {
1134
1042
  readonly id: string
1135
1043
  name: string
1136
1044
  arguments: string
1045
+ extraContent: Schema.JsonObject | undefined
1137
1046
  }
1138
1047
 
1139
1048
  const makeResponse = Effect.fnUntraced(
@@ -1141,12 +1050,14 @@ const makeResponse = Effect.fnUntraced(
1141
1050
  options,
1142
1051
  rawResponse,
1143
1052
  response,
1144
- toolNameMapper
1053
+ toolNameMapper,
1054
+ toolCodecs
1145
1055
  }: {
1146
1056
  readonly options: LanguageModel.ProviderOptions
1147
1057
  readonly rawResponse: CreateResponse200
1148
1058
  readonly response: HttpClientResponse.HttpClientResponse
1149
1059
  readonly toolNameMapper: Tool.NameMapper<Tools>
1060
+ readonly toolCodecs: ToolCodecs
1150
1061
  }): Effect.fn.Return<
1151
1062
  Array<Response.PartEncoded>,
1152
1063
  AiError.AiError
@@ -1167,9 +1078,10 @@ const makeResponse = Effect.fnUntraced(
1167
1078
  const message = choice?.message
1168
1079
 
1169
1080
  if (message !== undefined) {
1170
- const reasoning = message.reasoning ?? message.reasoning_content
1171
- if (Predicate.isNotNullish(reasoning) && reasoning.length > 0) {
1172
- parts.push({ type: "reasoning", text: reasoning })
1081
+ const reasoningField = getResponseReasoningField(message)
1082
+ const reasoning = reasoningField !== undefined ? message[reasoningField] : undefined
1083
+ if (reasoningField !== undefined && Predicate.isNotNullish(reasoning) && reasoning.length > 0) {
1084
+ parts.push({ type: "reasoning", text: reasoning, metadata: { openai: { reasoningField } } })
1173
1085
  }
1174
1086
 
1175
1087
  if (
@@ -1195,14 +1107,19 @@ const makeResponse = Effect.fnUntraced(
1195
1107
  })
1196
1108
  })
1197
1109
  })
1198
- const params = yield* transformToolCallParams(options.tools, toolName, toolParams)
1110
+ const params = yield* transformToolCallParams(options, toolName, toolParams, toolCodecs)
1199
1111
  hasToolCalls = true
1200
1112
  parts.push({
1201
1113
  type: "tool-call",
1202
1114
  id: toolId,
1203
1115
  name: toolName,
1204
1116
  params,
1205
- metadata: { openai: { ...makeItemIdMetadata(toolCall.id) } }
1117
+ metadata: {
1118
+ openai: {
1119
+ ...makeItemIdMetadata(toolCall.id),
1120
+ ...makeExtraContentMetadata(toolCall.extra_content ?? undefined)
1121
+ }
1122
+ }
1206
1123
  })
1207
1124
  }
1208
1125
  }
@@ -1231,12 +1148,14 @@ const makeStreamResponse = Effect.fnUntraced(
1231
1148
  options,
1232
1149
  stream,
1233
1150
  response,
1234
- toolNameMapper
1151
+ toolNameMapper,
1152
+ toolCodecs
1235
1153
  }: {
1236
1154
  readonly options: LanguageModel.ProviderOptions
1237
1155
  readonly stream: Stream.Stream<ResponseStreamEvent, AiError.AiError>
1238
1156
  readonly response: HttpClientResponse.HttpClientResponse
1239
1157
  readonly toolNameMapper: Tool.NameMapper<Tools>
1158
+ readonly toolCodecs: ToolCodecs
1240
1159
  }): Effect.fn.Return<
1241
1160
  Stream.Stream<Response.StreamPartEncoded, AiError.AiError>,
1242
1161
  AiError.AiError
@@ -1287,14 +1206,19 @@ const makeStreamResponse = Effect.fnUntraced(
1287
1206
  })
1288
1207
  })
1289
1208
  })
1290
- const params = yield* transformToolCallParams(options.tools, toolCall.name, parsedParams)
1209
+ const params = yield* transformToolCallParams(options, toolCall.name, parsedParams, toolCodecs)
1291
1210
  parts.push({ type: "tool-params-end", id: toolCall.id })
1292
1211
  parts.push({
1293
1212
  type: "tool-call",
1294
1213
  id: toolCall.id,
1295
1214
  name: toolCall.name,
1296
1215
  params,
1297
- metadata: { openai: { ...makeItemIdMetadata(toolCall.id) } }
1216
+ metadata: {
1217
+ openai: {
1218
+ ...makeItemIdMetadata(toolCall.id),
1219
+ ...makeExtraContentMetadata(toolCall.extraContent)
1220
+ }
1221
+ }
1298
1222
  })
1299
1223
  hasToolCalls = true
1300
1224
  }
@@ -1343,20 +1267,23 @@ const makeStreamResponse = Effect.fnUntraced(
1343
1267
  return parts
1344
1268
  }
1345
1269
 
1346
- const reasoningDelta = choice.delta?.reasoning ?? choice.delta?.reasoning_content
1347
- if (Predicate.isNotNullish(reasoningDelta) && reasoningDelta.length > 0) {
1270
+ const reasoningField = Predicate.isNotNullish(choice.delta)
1271
+ ? getResponseReasoningField(choice.delta)
1272
+ : undefined
1273
+ const reasoningDelta = reasoningField !== undefined ? choice.delta?.[reasoningField] : undefined
1274
+ if (reasoningField !== undefined && Predicate.isNotNullish(reasoningDelta) && reasoningDelta.length > 0) {
1348
1275
  if (!reasoningStarted) {
1349
1276
  reasoningStarted = true
1350
1277
  parts.push({
1351
1278
  type: "reasoning-start",
1352
1279
  id: reasoningId,
1353
- metadata: { openai: { ...makeItemIdMetadata(reasoningId) } }
1280
+ metadata: { openai: { ...makeItemIdMetadata(reasoningId), reasoningField } }
1354
1281
  })
1355
1282
  }
1356
1283
  parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningDelta })
1357
1284
  }
1358
1285
 
1359
- if (choice.delta?.content !== undefined && Predicate.isNotNull(choice.delta.content)) {
1286
+ if (Predicate.isNotNullish(choice.delta?.content) && choice.delta.content.length > 0) {
1360
1287
  if (reasoningStarted) {
1361
1288
  reasoningStarted = false
1362
1289
  parts.push({
@@ -1393,12 +1320,16 @@ const makeStreamResponse = Effect.fnUntraced(
1393
1320
  activeToolCalls[toolIndex] = {
1394
1321
  id: toolId,
1395
1322
  name: toolName,
1396
- arguments: argumentsDelta
1323
+ arguments: argumentsDelta,
1324
+ extraContent: deltaTool.extra_content ?? undefined
1397
1325
  }
1398
1326
  parts.push({ type: "tool-params-start", id: toolId, name: toolName })
1399
1327
  } else {
1400
1328
  activeToolCall.name = toolName
1401
1329
  activeToolCall.arguments = `${activeToolCall.arguments}${argumentsDelta}`
1330
+ if (Predicate.isNotNullish(deltaTool.extra_content)) {
1331
+ activeToolCall.extraContent = deltaTool.extra_content
1332
+ }
1402
1333
  }
1403
1334
 
1404
1335
  if (argumentsDelta.length > 0) {
@@ -1516,26 +1447,27 @@ const tryJsonSchema = <S extends Schema.Constraint>(schema: S, method: string) =
1516
1447
  catch: (error) => unsupportedSchemaError(error, method)
1517
1448
  })
1518
1449
 
1519
- const tryToolJsonSchema = <T extends Tool.Any>(tool: T, method: string) =>
1520
- Effect.try({
1521
- try: () => Tool.getJsonSchema(tool, { transformer: toCodecOpenAI }),
1522
- catch: (error) => unsupportedSchemaError(error, method)
1523
- })
1450
+ type ToolCodec = ReturnType<typeof toCodecOpenAI>["codec"]
1451
+ type ToolCodecs = ReadonlyMap<Tool.Any, ToolCodec>
1524
1452
 
1525
- const transformToolCallParams = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Tool.Any>>(
1526
- tools: Tools,
1453
+ const transformToolCallParams = Effect.fnUntraced(function*(
1454
+ options: LanguageModel.ProviderOptions,
1527
1455
  toolName: string,
1528
- toolParams: unknown
1456
+ toolParams: unknown,
1457
+ toolCodecs: ToolCodecs
1529
1458
  ): Effect.fn.Return<unknown, AiError.AiError> {
1530
- const tool = tools.find((tool) => tool.name === toolName)
1459
+ const tool = options.tools.find((tool) => tool.name === toolName)
1531
1460
 
1532
1461
  if (Predicate.isUndefined(tool)) {
1462
+ if (options.toolCallValidation === "deferred") {
1463
+ return toolParams
1464
+ }
1533
1465
  return yield* AiError.make({
1534
1466
  module: "OpenAiLanguageModel",
1535
1467
  method: "makeResponse",
1536
1468
  reason: new AiError.ToolNotFoundError({
1537
1469
  toolName,
1538
- availableTools: tools.map((tool) => tool.name)
1470
+ availableTools: options.tools.map((tool) => tool.name)
1539
1471
  })
1540
1472
  })
1541
1473
  }
@@ -1544,7 +1476,7 @@ const transformToolCallParams = Effect.fnUntraced(function*<Tools extends Readon
1544
1476
  return toolParams
1545
1477
  }
1546
1478
 
1547
- const { codec } = yield* tryCodecTransform(tool.parametersSchema, "makeResponse")
1479
+ const codec = toolCodecs.get(tool) ?? (yield* tryCodecTransform(tool.parametersSchema, "makeResponse")).codec
1548
1480
 
1549
1481
  // Normalize valid parameters; leave invalid ones for Toolkit.
1550
1482
  return yield* (
@@ -1568,10 +1500,13 @@ const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Too
1568
1500
  }): Effect.fn.Return<{
1569
1501
  readonly tools: ReadonlyArray<OpenAiClientTool> | undefined
1570
1502
  readonly toolChoice: OpenAiToolChoice | undefined
1503
+ readonly toolCodecs: ToolCodecs
1571
1504
  }, AiError.AiError> {
1505
+ const toolCodecs = new Map<Tool.Any, ToolCodec>()
1506
+
1572
1507
  // Return immediately if no tools are in the toolkit
1573
1508
  if (options.tools.length === 0) {
1574
- return { tools: undefined, toolChoice: undefined }
1509
+ return { tools: undefined, toolChoice: undefined, toolCodecs }
1575
1510
  }
1576
1511
 
1577
1512
  const tools: Array<OpenAiClientTool> = []
@@ -1592,7 +1527,15 @@ const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Too
1592
1527
  for (const tool of allowedTools) {
1593
1528
  if (Tool.isUserDefined(tool) || Tool.isDynamic(tool)) {
1594
1529
  const strict = Tool.getStrictMode(tool) ?? config.strictJsonSchema ?? true
1595
- const parameters = yield* tryToolJsonSchema(tool, "prepareTools")
1530
+ let parameters: ReturnType<typeof Tool.getJsonSchema>
1531
+ if (Tool.isDynamic(tool) && tool.jsonSchema !== undefined) {
1532
+ parameters = tool.jsonSchema
1533
+ } else {
1534
+ const prepared = yield* tryCodecTransform(tool.parametersSchema, "prepareTools")
1535
+ parameters = prepared.jsonSchema
1536
+ // Reused to normalize this tool's calls in the response.
1537
+ toolCodecs.set(tool, prepared.codec)
1538
+ }
1596
1539
  tools.push({
1597
1540
  type: "function",
1598
1541
  name: tool.name,
@@ -1627,11 +1570,13 @@ const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Too
1627
1570
  }
1628
1571
  }
1629
1572
 
1630
- return { tools, toolChoice }
1573
+ return { tools, toolChoice, toolCodecs }
1631
1574
  })
1632
1575
 
1633
- const toChatCompletionsRequest = (payload: CreateResponse): CreateResponseRequestJson => {
1634
- const messages = toChatMessages(payload.input)
1576
+ const toChatCompletionsRequest = (
1577
+ payload: CreateResponse,
1578
+ messages: ReadonlyArray<ChatCompletionRequestMessage>
1579
+ ): CreateResponseRequestJson => {
1635
1580
  const responseFormat = toChatResponseFormat(payload.text?.format)
1636
1581
  const tools = payload.tools !== undefined
1637
1582
  ? payload.tools.map(toChatTool).filter((tool): tool is NonNullable<ReturnType<typeof toChatTool>> =>
@@ -1793,112 +1738,6 @@ const toChatTool = (
1793
1738
  return undefined
1794
1739
  }
1795
1740
 
1796
- const toChatMessages = (
1797
- input: CreateResponse["input"]
1798
- ): Array<CreateResponseRequestJson["messages"][number]> => {
1799
- if (Predicate.isUndefined(input)) {
1800
- return []
1801
- }
1802
-
1803
- if (typeof input === "string") {
1804
- return [{ role: "user", content: input }]
1805
- }
1806
-
1807
- const messages: Array<CreateResponseRequestJson["messages"][number]> = []
1808
-
1809
- for (const item of input) {
1810
- if (Predicate.hasProperty(item, "type") && item.type === "function_call") {
1811
- const previous = messages.at(-1)
1812
- const toolCall = toChatToolCall(item)
1813
- if (previous?.role === "assistant" && previous.tool_calls !== undefined) {
1814
- messages[messages.length - 1] = {
1815
- ...previous,
1816
- tool_calls: [...previous.tool_calls, toolCall]
1817
- }
1818
- } else {
1819
- messages.push({
1820
- role: "assistant",
1821
- content: null,
1822
- tool_calls: [toolCall]
1823
- })
1824
- }
1825
- } else {
1826
- messages.push(...toChatMessagesFromItem(item))
1827
- }
1828
- }
1829
-
1830
- return messages
1831
- }
1832
-
1833
- const toChatMessagesFromItem = (
1834
- item: InputItem
1835
- ): Array<CreateResponseRequestJson["messages"][number]> => {
1836
- if (Predicate.hasProperty(item, "type") && item.type === "message") {
1837
- return [{
1838
- role: item.role,
1839
- content: toAssistantChatMessageContent(item.content)
1840
- }]
1841
- }
1842
-
1843
- if (Predicate.hasProperty(item, "role")) {
1844
- return [{
1845
- role: item.role,
1846
- content: toChatMessageContent(item.content)
1847
- }]
1848
- }
1849
-
1850
- switch (item.type) {
1851
- case "function_call": {
1852
- return [{
1853
- role: "assistant",
1854
- content: null,
1855
- tool_calls: [toChatToolCall(item)]
1856
- }]
1857
- }
1858
-
1859
- case "function_call_output": {
1860
- return [{
1861
- role: "tool",
1862
- tool_call_id: item.call_id,
1863
- content: stringifyJson(item.output)
1864
- }]
1865
- }
1866
-
1867
- default: {
1868
- return []
1869
- }
1870
- }
1871
- }
1872
-
1873
- const toChatToolCall = (
1874
- item: Extract<InputItem, { readonly type: "function_call" }>
1875
- ): ChatCompletionRequestToolCall => ({
1876
- id: item.call_id,
1877
- type: "function",
1878
- function: {
1879
- name: item.name,
1880
- arguments: item.arguments
1881
- }
1882
- })
1883
-
1884
- const toAssistantChatMessageContent = (
1885
- content: ReadonlyArray<{
1886
- readonly type: string
1887
- readonly [x: string]: unknown
1888
- }>
1889
- ): string => {
1890
- let text = ""
1891
- for (const part of content) {
1892
- if (part.type === "output_text" && typeof part.text === "string") {
1893
- text += part.text
1894
- }
1895
- if (part.type === "refusal" && typeof part.refusal === "string") {
1896
- text += part.refusal
1897
- }
1898
- }
1899
- return text
1900
- }
1901
-
1902
1741
  const toChatMessageContent = (
1903
1742
  content: string | ReadonlyArray<InputContent>
1904
1743
  ): string | ReadonlyArray<ChatCompletionContentPart> => {
@@ -1956,11 +1795,6 @@ const toChatMessageContent = (
1956
1795
  return parts
1957
1796
  }
1958
1797
 
1959
- const stringifyJson = (value: unknown): string =>
1960
- typeof value === "string"
1961
- ? value
1962
- : JSON.stringify(value)
1963
-
1964
1798
  // =============================================================================
1965
1799
  // Utilities
1966
1800
  // =============================================================================
@@ -1968,27 +1802,34 @@ const stringifyJson = (value: unknown): string =>
1968
1802
  const isFileId = (data: string, config: typeof Config.Service): boolean =>
1969
1803
  config.fileIdPrefixes != null && config.fileIdPrefixes.some((prefix) => data.startsWith(prefix))
1970
1804
 
1971
- const getItemId = (
1972
- part:
1973
- | Prompt.TextPart
1974
- | Prompt.ReasoningPart
1975
- | Prompt.ToolCallPart
1976
- | Prompt.ToolResultPart
1977
- ): string | null => part.options.openai?.itemId ?? null
1978
- const getStatus = (
1979
- part:
1980
- | Prompt.TextPart
1981
- | Prompt.ToolCallPart
1982
- | Prompt.ToolResultPart
1983
- ): MessageStatus | null => part.options.openai?.status ?? null
1984
- const getEncryptedContent = (
1985
- part: Prompt.ReasoningPart
1986
- ): string | null => part.options.openai?.encryptedContent ?? null
1805
+ const getExtraContent = (
1806
+ part: Prompt.ToolCallPart
1807
+ ): Schema.JsonObject | null => part.options.openai?.extraContent ?? null
1808
+
1809
+ /**
1810
+ * The chat message field carrying reasoning text. Providers differ: DeepSeek,
1811
+ * Kimi and GLM use `reasoning_content`, while Groq uses `reasoning` and
1812
+ * rejects `reasoning_content` on request messages.
1813
+ */
1814
+ type ReasoningField = "reasoning" | "reasoning_content"
1815
+
1816
+ const getResponseReasoningField = (message: {
1817
+ readonly reasoning?: string | null | undefined
1818
+ readonly reasoning_content?: string | null | undefined
1819
+ }): ReasoningField | undefined =>
1820
+ Predicate.isNotNullish(message.reasoning)
1821
+ ? "reasoning"
1822
+ : Predicate.isNotNullish(message.reasoning_content)
1823
+ ? "reasoning_content"
1824
+ : undefined
1987
1825
 
1988
1826
  const getImageDetail = (part: Prompt.FilePart): ImageDetail => part.options.openai?.imageDetail ?? "auto"
1989
1827
 
1990
1828
  const makeItemIdMetadata = (itemId: string | undefined) => itemId !== undefined ? { itemId } : undefined
1991
1829
 
1830
+ const makeExtraContentMetadata = (extraContent: Schema.JsonObject | undefined) =>
1831
+ extraContent !== undefined ? { extraContent } : undefined
1832
+
1992
1833
  const normalizeServiceTier = (
1993
1834
  serviceTier: string | undefined
1994
1835
  ): "default" | "auto" | "flex" | "scale" | "priority" | null | undefined => {
@@ -2025,54 +1866,6 @@ const prepareResponseFormat = Effect.fnUntraced(function*({ config, options }: {
2025
1866
  return { type: "text" }
2026
1867
  })
2027
1868
 
2028
- interface ModelCapabilities {
2029
- readonly isReasoningModel: boolean
2030
- readonly systemMessageMode: "remove" | "system" | "developer"
2031
- readonly supportsFlexProcessing: boolean
2032
- readonly supportsPriorityProcessing: boolean
2033
- /**
2034
- * Allow temperature, topP, logProbs when reasoningEffort is none.
2035
- */
2036
- readonly supportsNonReasoningParameters: boolean
2037
- }
2038
-
2039
- const getModelCapabilities = (modelId: string): ModelCapabilities => {
2040
- const supportsFlexProcessing = modelId.startsWith("o3") ||
2041
- modelId.startsWith("o4-mini") ||
2042
- (modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"))
2043
-
2044
- const supportsPriorityProcessing = modelId.startsWith("gpt-4") ||
2045
- modelId.startsWith("gpt-5-mini") ||
2046
- (modelId.startsWith("gpt-5") &&
2047
- !modelId.startsWith("gpt-5-nano") &&
2048
- !modelId.startsWith("gpt-5-chat")) ||
2049
- modelId.startsWith("o3") ||
2050
- modelId.startsWith("o4-mini")
2051
-
2052
- // Use allowlist approach: only known reasoning models should use 'developer' role
2053
- // This prevents issues with fine-tuned models, third-party models, and custom models
2054
- const isReasoningModel = modelId.startsWith("o1") ||
2055
- modelId.startsWith("o3") ||
2056
- modelId.startsWith("o4-mini") ||
2057
- modelId.startsWith("codex-mini") ||
2058
- modelId.startsWith("computer-use-preview") ||
2059
- (modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"))
2060
-
2061
- // https://platform.openai.com/docs/guides/latest-model#gpt-5-1-parameter-compatibility
2062
- // GPT-5.1 and GPT-5.2 support temperature, topP, logProbs when reasoningEffort is none
2063
- const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2")
2064
-
2065
- const systemMessageMode = isReasoningModel ? "developer" : "system"
2066
-
2067
- return {
2068
- supportsFlexProcessing,
2069
- supportsPriorityProcessing,
2070
- isReasoningModel,
2071
- systemMessageMode,
2072
- supportsNonReasoningParameters
2073
- }
2074
- }
2075
-
2076
1869
  const getUsage = (usage: CreateResponse200["usage"]): Response.Usage => {
2077
1870
  if (Predicate.isNullish(usage)) {
2078
1871
  return {