@effect/ai-openai-compat 4.0.3 → 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
 
@@ -344,6 +347,10 @@ declare module "effect/ai/Response" {
344
347
  * Encrypted reasoning content that can be sent back in later requests.
345
348
  */
346
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
347
354
  } | null
348
355
  }
349
356
 
@@ -367,6 +374,10 @@ declare module "effect/ai/Response" {
367
374
  * Encrypted reasoning content that can be sent back in later requests.
368
375
  */
369
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
370
381
  } | null
371
382
  }
372
383
 
@@ -612,17 +623,16 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
612
623
  readonly config: typeof Config.Service
613
624
  readonly options: LanguageModel.ProviderOptions
614
625
  readonly toolNameMapper: Tool.NameMapper<Tools>
615
- }): Effect.fn.Return<CreateResponseRequestJson, AiError.AiError> {
616
- const include = new Set<IncludeEnum>()
617
- const capabilities = getModelCapabilities(config.model!)
626
+ }): Effect.fn.Return<{
627
+ readonly request: CreateResponseRequestJson
628
+ readonly toolCodecs: ToolCodecs
629
+ }, AiError.AiError> {
618
630
  const messages = yield* prepareMessages({
619
631
  config,
620
632
  options,
621
- capabilities,
622
- include,
623
633
  toolNameMapper
624
634
  })
625
- const { toolChoice, tools } = yield* prepareTools({
635
+ const { toolChoice, toolCodecs, tools } = yield* prepareTools({
626
636
  config,
627
637
  options,
628
638
  toolNameMapper
@@ -634,8 +644,6 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
634
644
  const { fileIdPrefixes: _fip, strictJsonSchema: _sjs, ...apiConfig } = config
635
645
  const request: CreateResponse = {
636
646
  ...apiConfig,
637
- input: messages,
638
- include: include.size > 0 ? Array.from(include) : null,
639
647
  text: {
640
648
  verbosity: config.text?.verbosity ?? null,
641
649
  format: responseFormat
@@ -643,7 +651,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
643
651
  ...(tools !== undefined ? { tools } : undefined),
644
652
  ...(toolChoice !== undefined ? { tool_choice: toolChoice } : undefined)
645
653
  }
646
- return toChatCompletionsRequest(request)
654
+ return { request: toChatCompletionsRequest(request, messages), toolCodecs }
647
655
  }
648
656
  )
649
657
 
@@ -653,7 +661,7 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
653
661
  function*(options) {
654
662
  const config = yield* makeConfig
655
663
  const toolNameMapper = new Tool.NameMapper(options.tools)
656
- const request = yield* makeRequest({ config, options, toolNameMapper })
664
+ const { request, toolCodecs } = yield* makeRequest({ config, options, toolNameMapper })
657
665
  annotateRequest(options.span, request)
658
666
  const [rawResponse, response] = yield* client.createResponse(request)
659
667
  annotateResponse(options.span, rawResponse)
@@ -661,7 +669,8 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
661
669
  options,
662
670
  rawResponse,
663
671
  response,
664
- toolNameMapper
672
+ toolNameMapper,
673
+ toolCodecs
665
674
  })
666
675
  }
667
676
  ),
@@ -669,14 +678,15 @@ export const make = Effect.fnUntraced(function*({ model, config: providerConfig
669
678
  function*(options) {
670
679
  const config = yield* makeConfig
671
680
  const toolNameMapper = new Tool.NameMapper(options.tools)
672
- const request = yield* makeRequest({ config, options, toolNameMapper })
681
+ const { request, toolCodecs } = yield* makeRequest({ config, options, toolNameMapper })
673
682
  annotateRequest(options.span, request)
674
683
  const [response, stream] = yield* client.createResponseStream(request)
675
684
  return yield* makeStreamResponse({
676
685
  options,
677
686
  stream,
678
687
  response,
679
- toolNameMapper
688
+ toolNameMapper,
689
+ toolCodecs
680
690
  })
681
691
  },
682
692
  (effect, options) =>
@@ -840,27 +850,13 @@ const prepareMessages = Effect.fnUntraced(
840
850
  function*<Tools extends ReadonlyArray<Tool.Any>>({
841
851
  config,
842
852
  options,
843
- capabilities,
844
- include,
845
853
  toolNameMapper
846
854
  }: {
847
855
  readonly config: typeof Config.Service
848
856
  readonly options: LanguageModel.ProviderOptions
849
- readonly include: Set<IncludeEnum>
850
- readonly capabilities: ModelCapabilities
851
857
  readonly toolNameMapper: Tool.NameMapper<Tools>
852
- }): Effect.fn.Return<ReadonlyArray<InputItem>, AiError.AiError> {
853
- const hasConversation = Predicate.isNotNullish(config.conversation)
854
-
855
- // Handle Included Features
856
- if (config.top_logprobs !== undefined) {
857
- include.add("message.output_text.logprobs")
858
- }
859
- if (config.store === false && capabilities.isReasoningModel) {
860
- include.add("reasoning.encrypted_content")
861
- }
862
-
863
- const messages: Array<InputItem> = []
858
+ }): Effect.fn.Return<ReadonlyArray<ChatCompletionRequestMessage>, AiError.AiError> {
859
+ const messages: Array<ChatCompletionRequestMessage> = []
864
860
 
865
861
  for (const message of options.prompt.content) {
866
862
  switch (message.role) {
@@ -929,157 +925,62 @@ const prepareMessages = Effect.fnUntraced(
929
925
  }
930
926
  }
931
927
 
932
- messages.push({ role: "user", content })
928
+ messages.push({ role: "user", content: toChatMessageContent(content) })
933
929
 
934
930
  break
935
931
  }
936
932
 
937
933
  case "assistant": {
938
- 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> = []
939
938
 
940
939
  for (const part of message.content) {
941
940
  switch (part.type) {
942
941
  case "text": {
943
- const id = getItemId(part)
944
-
945
- // When in conversation mode, skip items that already exist in the
946
- // conversation context to avoid "Duplicate item found" errors
947
- if (hasConversation && Predicate.isNotNull(id)) {
948
- break
949
- }
950
-
951
- if (config.store === true && Predicate.isNotNull(id)) {
952
- messages.push({ type: "item_reference", id })
953
- break
954
- }
955
-
956
- messages.push({
957
- id: id!,
958
- type: "message",
959
- role: "assistant",
960
- status: part.options.openai?.status ?? "completed",
961
- content: [{
962
- type: "output_text",
963
- text: part.text,
964
- annotations: part.options.openai?.annotations ?? [],
965
- logprobs: []
966
- }]
967
- })
968
-
942
+ content = (content ?? "") + part.text
969
943
  break
970
944
  }
971
945
 
972
946
  case "reasoning": {
973
- const id = getItemId(part)
974
- const encryptedContent = getEncryptedContent(part)
975
-
976
- if (hasConversation && Predicate.isNotNull(id)) {
977
- break
978
- }
979
-
980
- if (Predicate.isNotNull(id)) {
981
- const message = reasoningMessages[id]
982
-
983
- if (config.store === true) {
984
- // Use item references to refer to reasoning (single reference)
985
- // when the first part is encountered
986
- if (Predicate.isUndefined(message)) {
987
- messages.push({ type: "item_reference", id })
988
-
989
- // Store unused reasoning message to mark its id as used
990
- reasoningMessages[id] = {
991
- type: "reasoning",
992
- id,
993
- summary: []
994
- }
995
- }
996
- } else {
997
- const summaryParts: Array<SummaryTextContent> = []
998
-
999
- if (part.text.length > 0) {
1000
- summaryParts.push({ type: "summary_text", text: part.text })
1001
- }
1002
-
1003
- if (Predicate.isUndefined(message)) {
1004
- reasoningMessages[id] = {
1005
- type: "reasoning",
1006
- id,
1007
- summary: summaryParts,
1008
- encrypted_content: encryptedContent ?? null
1009
- }
1010
-
1011
- messages.push(reasoningMessages[id])
1012
- } else {
1013
- message.summary.push(...summaryParts)
1014
-
1015
- // Update encrypted content to enable setting it in the
1016
- // last summary part
1017
- if (Predicate.isNotNull(encryptedContent)) {
1018
- message.encrypted_content = encryptedContent
1019
- }
1020
- }
1021
- }
1022
- }
1023
-
947
+ reasoning += part.text
948
+ reasoningField ??= part.options.openai?.reasoningField ?? undefined
1024
949
  break
1025
950
  }
1026
951
 
1027
952
  case "tool-call": {
1028
- const id = getItemId(part)
1029
- const status = getStatus(part)
1030
-
1031
- if (hasConversation && Predicate.isNotNull(id)) {
1032
- break
1033
- }
1034
-
1035
- if (config.store && Predicate.isNotNull(id)) {
1036
- messages.push({ type: "item_reference", id })
1037
- break
1038
- }
1039
-
1040
953
  if (part.providerExecuted) {
1041
954
  break
1042
955
  }
1043
956
 
1044
- const toolName = toolNameMapper.getProviderName(part.name)
1045
957
  const extraContent = getExtraContent(part)
1046
958
 
1047
- messages.push({
1048
- type: "function_call",
1049
- name: toolName,
1050
- call_id: part.id,
1051
- arguments: JSON.stringify(part.params),
1052
- ...(Predicate.isNotNull(extraContent) ? { extra_content: extraContent } : {}),
1053
- ...(Predicate.isNotNull(id) ? { id } : {}),
1054
- ...(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)
1055
967
  })
1056
-
1057
968
  break
1058
969
  }
1059
-
1060
- // Assistant tool-result parts are always provider executed
1061
- case "tool-result": {
1062
- // Skip execution denied results - these have no corresponding
1063
- // item in OpenAI's store
1064
- if (
1065
- Predicate.hasProperty(part.result, "type") &&
1066
- part.result.type === "execution-denied"
1067
- ) {
1068
- break
1069
- }
1070
-
1071
- if (hasConversation) {
1072
- break
1073
- }
1074
-
1075
- if (config.store === true) {
1076
- const id = getItemId(part) ?? part.id
1077
- messages.push({ type: "item_reference", id })
1078
- }
1079
- }
1080
970
  }
1081
971
  }
1082
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
+
1083
984
  break
1084
985
  }
1085
986
 
@@ -1089,13 +990,10 @@ const prepareMessages = Effect.fnUntraced(
1089
990
  continue
1090
991
  }
1091
992
 
1092
- const status = getStatus(part)
1093
-
1094
993
  messages.push({
1095
- type: "function_call_output",
1096
- call_id: part.id,
1097
- output: typeof part.result === "string" ? part.result : JSON.stringify(part.result),
1098
- ...(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)
1099
997
  })
1100
998
  }
1101
999
 
@@ -1152,12 +1050,14 @@ const makeResponse = Effect.fnUntraced(
1152
1050
  options,
1153
1051
  rawResponse,
1154
1052
  response,
1155
- toolNameMapper
1053
+ toolNameMapper,
1054
+ toolCodecs
1156
1055
  }: {
1157
1056
  readonly options: LanguageModel.ProviderOptions
1158
1057
  readonly rawResponse: CreateResponse200
1159
1058
  readonly response: HttpClientResponse.HttpClientResponse
1160
1059
  readonly toolNameMapper: Tool.NameMapper<Tools>
1060
+ readonly toolCodecs: ToolCodecs
1161
1061
  }): Effect.fn.Return<
1162
1062
  Array<Response.PartEncoded>,
1163
1063
  AiError.AiError
@@ -1178,9 +1078,10 @@ const makeResponse = Effect.fnUntraced(
1178
1078
  const message = choice?.message
1179
1079
 
1180
1080
  if (message !== undefined) {
1181
- const reasoning = message.reasoning ?? message.reasoning_content
1182
- if (Predicate.isNotNullish(reasoning) && reasoning.length > 0) {
1183
- 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 } } })
1184
1085
  }
1185
1086
 
1186
1087
  if (
@@ -1206,7 +1107,7 @@ const makeResponse = Effect.fnUntraced(
1206
1107
  })
1207
1108
  })
1208
1109
  })
1209
- const params = yield* transformToolCallParams(options.tools, toolName, toolParams)
1110
+ const params = yield* transformToolCallParams(options, toolName, toolParams, toolCodecs)
1210
1111
  hasToolCalls = true
1211
1112
  parts.push({
1212
1113
  type: "tool-call",
@@ -1247,12 +1148,14 @@ const makeStreamResponse = Effect.fnUntraced(
1247
1148
  options,
1248
1149
  stream,
1249
1150
  response,
1250
- toolNameMapper
1151
+ toolNameMapper,
1152
+ toolCodecs
1251
1153
  }: {
1252
1154
  readonly options: LanguageModel.ProviderOptions
1253
1155
  readonly stream: Stream.Stream<ResponseStreamEvent, AiError.AiError>
1254
1156
  readonly response: HttpClientResponse.HttpClientResponse
1255
1157
  readonly toolNameMapper: Tool.NameMapper<Tools>
1158
+ readonly toolCodecs: ToolCodecs
1256
1159
  }): Effect.fn.Return<
1257
1160
  Stream.Stream<Response.StreamPartEncoded, AiError.AiError>,
1258
1161
  AiError.AiError
@@ -1303,7 +1206,7 @@ const makeStreamResponse = Effect.fnUntraced(
1303
1206
  })
1304
1207
  })
1305
1208
  })
1306
- const params = yield* transformToolCallParams(options.tools, toolCall.name, parsedParams)
1209
+ const params = yield* transformToolCallParams(options, toolCall.name, parsedParams, toolCodecs)
1307
1210
  parts.push({ type: "tool-params-end", id: toolCall.id })
1308
1211
  parts.push({
1309
1212
  type: "tool-call",
@@ -1364,14 +1267,17 @@ const makeStreamResponse = Effect.fnUntraced(
1364
1267
  return parts
1365
1268
  }
1366
1269
 
1367
- const reasoningDelta = choice.delta?.reasoning ?? choice.delta?.reasoning_content
1368
- 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) {
1369
1275
  if (!reasoningStarted) {
1370
1276
  reasoningStarted = true
1371
1277
  parts.push({
1372
1278
  type: "reasoning-start",
1373
1279
  id: reasoningId,
1374
- metadata: { openai: { ...makeItemIdMetadata(reasoningId) } }
1280
+ metadata: { openai: { ...makeItemIdMetadata(reasoningId), reasoningField } }
1375
1281
  })
1376
1282
  }
1377
1283
  parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningDelta })
@@ -1541,26 +1447,27 @@ const tryJsonSchema = <S extends Schema.Constraint>(schema: S, method: string) =
1541
1447
  catch: (error) => unsupportedSchemaError(error, method)
1542
1448
  })
1543
1449
 
1544
- const tryToolJsonSchema = <T extends Tool.Any>(tool: T, method: string) =>
1545
- Effect.try({
1546
- try: () => Tool.getJsonSchema(tool, { transformer: toCodecOpenAI }),
1547
- catch: (error) => unsupportedSchemaError(error, method)
1548
- })
1450
+ type ToolCodec = ReturnType<typeof toCodecOpenAI>["codec"]
1451
+ type ToolCodecs = ReadonlyMap<Tool.Any, ToolCodec>
1549
1452
 
1550
- const transformToolCallParams = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Tool.Any>>(
1551
- tools: Tools,
1453
+ const transformToolCallParams = Effect.fnUntraced(function*(
1454
+ options: LanguageModel.ProviderOptions,
1552
1455
  toolName: string,
1553
- toolParams: unknown
1456
+ toolParams: unknown,
1457
+ toolCodecs: ToolCodecs
1554
1458
  ): Effect.fn.Return<unknown, AiError.AiError> {
1555
- const tool = tools.find((tool) => tool.name === toolName)
1459
+ const tool = options.tools.find((tool) => tool.name === toolName)
1556
1460
 
1557
1461
  if (Predicate.isUndefined(tool)) {
1462
+ if (options.toolCallValidation === "deferred") {
1463
+ return toolParams
1464
+ }
1558
1465
  return yield* AiError.make({
1559
1466
  module: "OpenAiLanguageModel",
1560
1467
  method: "makeResponse",
1561
1468
  reason: new AiError.ToolNotFoundError({
1562
1469
  toolName,
1563
- availableTools: tools.map((tool) => tool.name)
1470
+ availableTools: options.tools.map((tool) => tool.name)
1564
1471
  })
1565
1472
  })
1566
1473
  }
@@ -1569,7 +1476,7 @@ const transformToolCallParams = Effect.fnUntraced(function*<Tools extends Readon
1569
1476
  return toolParams
1570
1477
  }
1571
1478
 
1572
- const { codec } = yield* tryCodecTransform(tool.parametersSchema, "makeResponse")
1479
+ const codec = toolCodecs.get(tool) ?? (yield* tryCodecTransform(tool.parametersSchema, "makeResponse")).codec
1573
1480
 
1574
1481
  // Normalize valid parameters; leave invalid ones for Toolkit.
1575
1482
  return yield* (
@@ -1593,10 +1500,13 @@ const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Too
1593
1500
  }): Effect.fn.Return<{
1594
1501
  readonly tools: ReadonlyArray<OpenAiClientTool> | undefined
1595
1502
  readonly toolChoice: OpenAiToolChoice | undefined
1503
+ readonly toolCodecs: ToolCodecs
1596
1504
  }, AiError.AiError> {
1505
+ const toolCodecs = new Map<Tool.Any, ToolCodec>()
1506
+
1597
1507
  // Return immediately if no tools are in the toolkit
1598
1508
  if (options.tools.length === 0) {
1599
- return { tools: undefined, toolChoice: undefined }
1509
+ return { tools: undefined, toolChoice: undefined, toolCodecs }
1600
1510
  }
1601
1511
 
1602
1512
  const tools: Array<OpenAiClientTool> = []
@@ -1617,7 +1527,15 @@ const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Too
1617
1527
  for (const tool of allowedTools) {
1618
1528
  if (Tool.isUserDefined(tool) || Tool.isDynamic(tool)) {
1619
1529
  const strict = Tool.getStrictMode(tool) ?? config.strictJsonSchema ?? true
1620
- 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
+ }
1621
1539
  tools.push({
1622
1540
  type: "function",
1623
1541
  name: tool.name,
@@ -1652,11 +1570,13 @@ const prepareTools = Effect.fnUntraced(function*<Tools extends ReadonlyArray<Too
1652
1570
  }
1653
1571
  }
1654
1572
 
1655
- return { tools, toolChoice }
1573
+ return { tools, toolChoice, toolCodecs }
1656
1574
  })
1657
1575
 
1658
- const toChatCompletionsRequest = (payload: CreateResponse): CreateResponseRequestJson => {
1659
- const messages = toChatMessages(payload.input)
1576
+ const toChatCompletionsRequest = (
1577
+ payload: CreateResponse,
1578
+ messages: ReadonlyArray<ChatCompletionRequestMessage>
1579
+ ): CreateResponseRequestJson => {
1660
1580
  const responseFormat = toChatResponseFormat(payload.text?.format)
1661
1581
  const tools = payload.tools !== undefined
1662
1582
  ? payload.tools.map(toChatTool).filter((tool): tool is NonNullable<ReturnType<typeof toChatTool>> =>
@@ -1818,113 +1738,6 @@ const toChatTool = (
1818
1738
  return undefined
1819
1739
  }
1820
1740
 
1821
- const toChatMessages = (
1822
- input: CreateResponse["input"]
1823
- ): Array<CreateResponseRequestJson["messages"][number]> => {
1824
- if (Predicate.isUndefined(input)) {
1825
- return []
1826
- }
1827
-
1828
- if (typeof input === "string") {
1829
- return [{ role: "user", content: input }]
1830
- }
1831
-
1832
- const messages: Array<CreateResponseRequestJson["messages"][number]> = []
1833
-
1834
- for (const item of input) {
1835
- if (Predicate.hasProperty(item, "type") && item.type === "function_call") {
1836
- const previous = messages.at(-1)
1837
- const toolCall = toChatToolCall(item)
1838
- if (previous?.role === "assistant" && previous.tool_calls !== undefined) {
1839
- messages[messages.length - 1] = {
1840
- ...previous,
1841
- tool_calls: [...previous.tool_calls, toolCall]
1842
- }
1843
- } else {
1844
- messages.push({
1845
- role: "assistant",
1846
- content: null,
1847
- tool_calls: [toolCall]
1848
- })
1849
- }
1850
- } else {
1851
- messages.push(...toChatMessagesFromItem(item))
1852
- }
1853
- }
1854
-
1855
- return messages
1856
- }
1857
-
1858
- const toChatMessagesFromItem = (
1859
- item: InputItem
1860
- ): Array<CreateResponseRequestJson["messages"][number]> => {
1861
- if (Predicate.hasProperty(item, "type") && item.type === "message") {
1862
- return [{
1863
- role: item.role,
1864
- content: toAssistantChatMessageContent(item.content)
1865
- }]
1866
- }
1867
-
1868
- if (Predicate.hasProperty(item, "role")) {
1869
- return [{
1870
- role: item.role,
1871
- content: toChatMessageContent(item.content)
1872
- }]
1873
- }
1874
-
1875
- switch (item.type) {
1876
- case "function_call": {
1877
- return [{
1878
- role: "assistant",
1879
- content: null,
1880
- tool_calls: [toChatToolCall(item)]
1881
- }]
1882
- }
1883
-
1884
- case "function_call_output": {
1885
- return [{
1886
- role: "tool",
1887
- tool_call_id: item.call_id,
1888
- content: stringifyJson(item.output)
1889
- }]
1890
- }
1891
-
1892
- default: {
1893
- return []
1894
- }
1895
- }
1896
- }
1897
-
1898
- const toChatToolCall = (
1899
- item: Extract<InputItem, { readonly type: "function_call" }>
1900
- ): ChatCompletionRequestToolCall => ({
1901
- id: item.call_id,
1902
- type: "function",
1903
- function: {
1904
- name: item.name,
1905
- arguments: item.arguments
1906
- },
1907
- ...(item.extra_content !== undefined ? { extra_content: item.extra_content } : undefined)
1908
- })
1909
-
1910
- const toAssistantChatMessageContent = (
1911
- content: ReadonlyArray<{
1912
- readonly type: string
1913
- readonly [x: string]: unknown
1914
- }>
1915
- ): string => {
1916
- let text = ""
1917
- for (const part of content) {
1918
- if (part.type === "output_text" && typeof part.text === "string") {
1919
- text += part.text
1920
- }
1921
- if (part.type === "refusal" && typeof part.refusal === "string") {
1922
- text += part.refusal
1923
- }
1924
- }
1925
- return text
1926
- }
1927
-
1928
1741
  const toChatMessageContent = (
1929
1742
  content: string | ReadonlyArray<InputContent>
1930
1743
  ): string | ReadonlyArray<ChatCompletionContentPart> => {
@@ -1982,11 +1795,6 @@ const toChatMessageContent = (
1982
1795
  return parts
1983
1796
  }
1984
1797
 
1985
- const stringifyJson = (value: unknown): string =>
1986
- typeof value === "string"
1987
- ? value
1988
- : JSON.stringify(value)
1989
-
1990
1798
  // =============================================================================
1991
1799
  // Utilities
1992
1800
  // =============================================================================
@@ -1994,26 +1802,27 @@ const stringifyJson = (value: unknown): string =>
1994
1802
  const isFileId = (data: string, config: typeof Config.Service): boolean =>
1995
1803
  config.fileIdPrefixes != null && config.fileIdPrefixes.some((prefix) => data.startsWith(prefix))
1996
1804
 
1997
- const getItemId = (
1998
- part:
1999
- | Prompt.TextPart
2000
- | Prompt.ReasoningPart
2001
- | Prompt.ToolCallPart
2002
- | Prompt.ToolResultPart
2003
- ): string | null => part.options.openai?.itemId ?? null
2004
- const getStatus = (
2005
- part:
2006
- | Prompt.TextPart
2007
- | Prompt.ToolCallPart
2008
- | Prompt.ToolResultPart
2009
- ): MessageStatus | null => part.options.openai?.status ?? null
2010
- const getEncryptedContent = (
2011
- part: Prompt.ReasoningPart
2012
- ): string | null => part.options.openai?.encryptedContent ?? null
2013
1805
  const getExtraContent = (
2014
1806
  part: Prompt.ToolCallPart
2015
1807
  ): Schema.JsonObject | null => part.options.openai?.extraContent ?? null
2016
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
1825
+
2017
1826
  const getImageDetail = (part: Prompt.FilePart): ImageDetail => part.options.openai?.imageDetail ?? "auto"
2018
1827
 
2019
1828
  const makeItemIdMetadata = (itemId: string | undefined) => itemId !== undefined ? { itemId } : undefined
@@ -2057,54 +1866,6 @@ const prepareResponseFormat = Effect.fnUntraced(function*({ config, options }: {
2057
1866
  return { type: "text" }
2058
1867
  })
2059
1868
 
2060
- interface ModelCapabilities {
2061
- readonly isReasoningModel: boolean
2062
- readonly systemMessageMode: "remove" | "system" | "developer"
2063
- readonly supportsFlexProcessing: boolean
2064
- readonly supportsPriorityProcessing: boolean
2065
- /**
2066
- * Allow temperature, topP, logProbs when reasoningEffort is none.
2067
- */
2068
- readonly supportsNonReasoningParameters: boolean
2069
- }
2070
-
2071
- const getModelCapabilities = (modelId: string): ModelCapabilities => {
2072
- const supportsFlexProcessing = modelId.startsWith("o3") ||
2073
- modelId.startsWith("o4-mini") ||
2074
- (modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"))
2075
-
2076
- const supportsPriorityProcessing = modelId.startsWith("gpt-4") ||
2077
- modelId.startsWith("gpt-5-mini") ||
2078
- (modelId.startsWith("gpt-5") &&
2079
- !modelId.startsWith("gpt-5-nano") &&
2080
- !modelId.startsWith("gpt-5-chat")) ||
2081
- modelId.startsWith("o3") ||
2082
- modelId.startsWith("o4-mini")
2083
-
2084
- // Use allowlist approach: only known reasoning models should use 'developer' role
2085
- // This prevents issues with fine-tuned models, third-party models, and custom models
2086
- const isReasoningModel = modelId.startsWith("o1") ||
2087
- modelId.startsWith("o3") ||
2088
- modelId.startsWith("o4-mini") ||
2089
- modelId.startsWith("codex-mini") ||
2090
- modelId.startsWith("computer-use-preview") ||
2091
- (modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat"))
2092
-
2093
- // https://platform.openai.com/docs/guides/latest-model#gpt-5-1-parameter-compatibility
2094
- // GPT-5.1 and GPT-5.2 support temperature, topP, logProbs when reasoningEffort is none
2095
- const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2")
2096
-
2097
- const systemMessageMode = isReasoningModel ? "developer" : "system"
2098
-
2099
- return {
2100
- supportsFlexProcessing,
2101
- supportsPriorityProcessing,
2102
- isReasoningModel,
2103
- systemMessageMode,
2104
- supportsNonReasoningParameters
2105
- }
2106
- }
2107
-
2108
1869
  const getUsage = (usage: CreateResponse200["usage"]): Response.Usage => {
2109
1870
  if (Predicate.isNullish(usage)) {
2110
1871
  return {