@llumiverse/drivers 1.0.0-dev.20260202.145450Z → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/lib/cjs/adobe/firefly.js +120 -0
  2. package/lib/cjs/adobe/firefly.js.map +1 -0
  3. package/lib/cjs/azure/azure_foundry.js +432 -0
  4. package/lib/cjs/azure/azure_foundry.js.map +1 -0
  5. package/lib/cjs/bedrock/converse.js +359 -0
  6. package/lib/cjs/bedrock/converse.js.map +1 -0
  7. package/lib/cjs/bedrock/index.js +1441 -0
  8. package/lib/cjs/bedrock/index.js.map +1 -0
  9. package/lib/cjs/bedrock/nova-image-payload.js +207 -0
  10. package/lib/cjs/bedrock/nova-image-payload.js.map +1 -0
  11. package/lib/cjs/bedrock/payloads.js +3 -0
  12. package/lib/cjs/bedrock/payloads.js.map +1 -0
  13. package/lib/cjs/bedrock/s3.js +107 -0
  14. package/lib/cjs/bedrock/s3.js.map +1 -0
  15. package/lib/cjs/bedrock/twelvelabs.js +87 -0
  16. package/lib/cjs/bedrock/twelvelabs.js.map +1 -0
  17. package/lib/cjs/groq/index.js +326 -0
  18. package/lib/cjs/groq/index.js.map +1 -0
  19. package/lib/cjs/huggingface_ie.js +201 -0
  20. package/lib/cjs/huggingface_ie.js.map +1 -0
  21. package/lib/cjs/index.js +31 -0
  22. package/lib/cjs/index.js.map +1 -0
  23. package/lib/cjs/mistral/index.js +176 -0
  24. package/lib/cjs/mistral/index.js.map +1 -0
  25. package/lib/cjs/mistral/types.js +83 -0
  26. package/lib/cjs/mistral/types.js.map +1 -0
  27. package/lib/cjs/openai/azure_openai.js +72 -0
  28. package/lib/cjs/openai/azure_openai.js.map +1 -0
  29. package/lib/cjs/openai/index.js +1100 -0
  30. package/lib/cjs/openai/index.js.map +1 -0
  31. package/lib/cjs/openai/openai.js +21 -0
  32. package/lib/cjs/openai/openai.js.map +1 -0
  33. package/lib/cjs/openai/openai_compatible.js +63 -0
  34. package/lib/cjs/openai/openai_compatible.js.map +1 -0
  35. package/lib/cjs/openai/openai_format.js +131 -0
  36. package/lib/cjs/openai/openai_format.js.map +1 -0
  37. package/lib/cjs/package.json +3 -0
  38. package/lib/cjs/replicate.js +275 -0
  39. package/lib/cjs/replicate.js.map +1 -0
  40. package/lib/cjs/test-driver/TestErrorCompletionStream.js +20 -0
  41. package/lib/cjs/test-driver/TestErrorCompletionStream.js.map +1 -0
  42. package/lib/cjs/test-driver/TestValidationErrorCompletionStream.js +24 -0
  43. package/lib/cjs/test-driver/TestValidationErrorCompletionStream.js.map +1 -0
  44. package/lib/cjs/test-driver/index.js +109 -0
  45. package/lib/cjs/test-driver/index.js.map +1 -0
  46. package/lib/cjs/test-driver/utils.js +30 -0
  47. package/lib/cjs/test-driver/utils.js.map +1 -0
  48. package/lib/cjs/togetherai/index.js +126 -0
  49. package/lib/cjs/togetherai/index.js.map +1 -0
  50. package/lib/cjs/togetherai/interfaces.js +3 -0
  51. package/lib/cjs/togetherai/interfaces.js.map +1 -0
  52. package/lib/cjs/vertexai/debug.js +12 -0
  53. package/lib/cjs/vertexai/debug.js.map +1 -0
  54. package/lib/cjs/vertexai/embeddings/embeddings-image.js +27 -0
  55. package/lib/cjs/vertexai/embeddings/embeddings-image.js.map +1 -0
  56. package/lib/cjs/vertexai/embeddings/embeddings-text.js +23 -0
  57. package/lib/cjs/vertexai/embeddings/embeddings-text.js.map +1 -0
  58. package/lib/cjs/vertexai/index.js +635 -0
  59. package/lib/cjs/vertexai/index.js.map +1 -0
  60. package/lib/cjs/vertexai/models/claude.js +842 -0
  61. package/lib/cjs/vertexai/models/claude.js.map +1 -0
  62. package/lib/cjs/vertexai/models/gemini.js +1110 -0
  63. package/lib/cjs/vertexai/models/gemini.js.map +1 -0
  64. package/lib/cjs/vertexai/models/imagen.js +303 -0
  65. package/lib/cjs/vertexai/models/imagen.js.map +1 -0
  66. package/lib/cjs/vertexai/models/llama.js +183 -0
  67. package/lib/cjs/vertexai/models/llama.js.map +1 -0
  68. package/lib/cjs/vertexai/models.js +35 -0
  69. package/lib/cjs/vertexai/models.js.map +1 -0
  70. package/lib/cjs/watsonx/index.js +161 -0
  71. package/lib/cjs/watsonx/index.js.map +1 -0
  72. package/lib/cjs/watsonx/interfaces.js +3 -0
  73. package/lib/cjs/watsonx/interfaces.js.map +1 -0
  74. package/lib/cjs/xai/index.js +65 -0
  75. package/lib/cjs/xai/index.js.map +1 -0
  76. package/lib/esm/adobe/firefly.js +116 -0
  77. package/lib/esm/adobe/firefly.js.map +1 -0
  78. package/lib/esm/azure/azure_foundry.js +426 -0
  79. package/lib/esm/azure/azure_foundry.js.map +1 -0
  80. package/lib/esm/bedrock/converse.js +352 -0
  81. package/lib/esm/bedrock/converse.js.map +1 -0
  82. package/lib/esm/bedrock/index.js +1434 -0
  83. package/lib/esm/bedrock/index.js.map +1 -0
  84. package/lib/esm/bedrock/nova-image-payload.js +203 -0
  85. package/lib/esm/bedrock/nova-image-payload.js.map +1 -0
  86. package/lib/esm/bedrock/payloads.js +2 -0
  87. package/lib/esm/bedrock/payloads.js.map +1 -0
  88. package/lib/esm/bedrock/s3.js +99 -0
  89. package/lib/esm/bedrock/s3.js.map +1 -0
  90. package/lib/esm/bedrock/twelvelabs.js +84 -0
  91. package/lib/esm/bedrock/twelvelabs.js.map +1 -0
  92. package/lib/esm/groq/index.js +319 -0
  93. package/lib/esm/groq/index.js.map +1 -0
  94. package/lib/esm/huggingface_ie.js +197 -0
  95. package/lib/esm/huggingface_ie.js.map +1 -0
  96. package/lib/esm/index.js +15 -0
  97. package/lib/esm/index.js.map +1 -0
  98. package/lib/esm/mistral/index.js +172 -0
  99. package/lib/esm/mistral/index.js.map +1 -0
  100. package/lib/esm/mistral/types.js +80 -0
  101. package/lib/esm/mistral/types.js.map +1 -0
  102. package/lib/esm/openai/azure_openai.js +68 -0
  103. package/lib/esm/openai/azure_openai.js.map +1 -0
  104. package/lib/esm/openai/index.js +1093 -0
  105. package/lib/esm/openai/index.js.map +1 -0
  106. package/lib/esm/openai/openai.js +14 -0
  107. package/lib/esm/openai/openai.js.map +1 -0
  108. package/lib/esm/openai/openai_compatible.js +56 -0
  109. package/lib/esm/openai/openai_compatible.js.map +1 -0
  110. package/lib/esm/openai/openai_format.js +127 -0
  111. package/lib/esm/openai/openai_format.js.map +1 -0
  112. package/lib/esm/replicate.js +268 -0
  113. package/lib/esm/replicate.js.map +1 -0
  114. package/lib/esm/test-driver/TestErrorCompletionStream.js +16 -0
  115. package/lib/esm/test-driver/TestErrorCompletionStream.js.map +1 -0
  116. package/lib/esm/test-driver/TestValidationErrorCompletionStream.js +20 -0
  117. package/lib/esm/test-driver/TestValidationErrorCompletionStream.js.map +1 -0
  118. package/lib/esm/test-driver/index.js +91 -0
  119. package/lib/esm/test-driver/index.js.map +1 -0
  120. package/lib/esm/test-driver/utils.js +25 -0
  121. package/lib/esm/test-driver/utils.js.map +1 -0
  122. package/lib/esm/togetherai/index.js +122 -0
  123. package/lib/esm/togetherai/index.js.map +1 -0
  124. package/lib/esm/togetherai/interfaces.js +2 -0
  125. package/lib/esm/togetherai/interfaces.js.map +1 -0
  126. package/lib/esm/vertexai/debug.js +6 -0
  127. package/lib/esm/vertexai/debug.js.map +1 -0
  128. package/lib/esm/vertexai/embeddings/embeddings-image.js +24 -0
  129. package/lib/esm/vertexai/embeddings/embeddings-image.js.map +1 -0
  130. package/lib/esm/vertexai/embeddings/embeddings-text.js +20 -0
  131. package/lib/esm/vertexai/embeddings/embeddings-text.js.map +1 -0
  132. package/lib/esm/vertexai/index.js +630 -0
  133. package/lib/esm/vertexai/index.js.map +1 -0
  134. package/lib/esm/vertexai/models/claude.js +833 -0
  135. package/lib/esm/vertexai/models/claude.js.map +1 -0
  136. package/lib/esm/vertexai/models/gemini.js +1104 -0
  137. package/lib/esm/vertexai/models/gemini.js.map +1 -0
  138. package/lib/esm/vertexai/models/imagen.js +299 -0
  139. package/lib/esm/vertexai/models/imagen.js.map +1 -0
  140. package/lib/esm/vertexai/models/llama.js +179 -0
  141. package/lib/esm/vertexai/models/llama.js.map +1 -0
  142. package/lib/esm/vertexai/models.js +32 -0
  143. package/lib/esm/vertexai/models.js.map +1 -0
  144. package/lib/esm/watsonx/index.js +157 -0
  145. package/lib/esm/watsonx/index.js.map +1 -0
  146. package/lib/esm/watsonx/interfaces.js +2 -0
  147. package/lib/esm/watsonx/interfaces.js.map +1 -0
  148. package/lib/esm/xai/index.js +58 -0
  149. package/lib/esm/xai/index.js.map +1 -0
  150. package/lib/types/adobe/firefly.d.ts +30 -0
  151. package/lib/types/adobe/firefly.d.ts.map +1 -0
  152. package/lib/types/azure/azure_foundry.d.ts +52 -0
  153. package/lib/types/azure/azure_foundry.d.ts.map +1 -0
  154. package/lib/types/bedrock/converse.d.ts +8 -0
  155. package/lib/types/bedrock/converse.d.ts.map +1 -0
  156. package/lib/types/bedrock/index.d.ts +135 -0
  157. package/lib/types/bedrock/index.d.ts.map +1 -0
  158. package/lib/types/bedrock/nova-image-payload.d.ts +74 -0
  159. package/lib/types/bedrock/nova-image-payload.d.ts.map +1 -0
  160. package/lib/types/bedrock/payloads.d.ts +12 -0
  161. package/lib/types/bedrock/payloads.d.ts.map +1 -0
  162. package/lib/types/bedrock/s3.d.ts +23 -0
  163. package/lib/types/bedrock/s3.d.ts.map +1 -0
  164. package/lib/types/bedrock/twelvelabs.d.ts +50 -0
  165. package/lib/types/bedrock/twelvelabs.d.ts.map +1 -0
  166. package/lib/types/groq/index.d.ts +27 -0
  167. package/lib/types/groq/index.d.ts.map +1 -0
  168. package/lib/types/huggingface_ie.d.ts +35 -0
  169. package/lib/types/huggingface_ie.d.ts.map +1 -0
  170. package/lib/types/index.d.ts +15 -0
  171. package/lib/types/index.d.ts.map +1 -0
  172. package/lib/types/mistral/index.d.ts +25 -0
  173. package/lib/types/mistral/index.d.ts.map +1 -0
  174. package/lib/types/mistral/types.d.ts +127 -0
  175. package/lib/types/mistral/types.d.ts.map +1 -0
  176. package/lib/types/openai/azure_openai.d.ts +25 -0
  177. package/lib/types/openai/azure_openai.d.ts.map +1 -0
  178. package/lib/types/openai/index.d.ts +126 -0
  179. package/lib/types/openai/index.d.ts.map +1 -0
  180. package/lib/types/openai/openai.d.ts +15 -0
  181. package/lib/types/openai/openai.d.ts.map +1 -0
  182. package/lib/types/openai/openai_compatible.d.ts +31 -0
  183. package/lib/types/openai/openai_compatible.d.ts.map +1 -0
  184. package/lib/types/openai/openai_format.d.ts +21 -0
  185. package/lib/types/openai/openai_format.d.ts.map +1 -0
  186. package/lib/types/replicate.d.ts +48 -0
  187. package/lib/types/replicate.d.ts.map +1 -0
  188. package/lib/types/test-driver/TestErrorCompletionStream.d.ts +9 -0
  189. package/lib/types/test-driver/TestErrorCompletionStream.d.ts.map +1 -0
  190. package/lib/types/test-driver/TestValidationErrorCompletionStream.d.ts +9 -0
  191. package/lib/types/test-driver/TestValidationErrorCompletionStream.d.ts.map +1 -0
  192. package/lib/types/test-driver/index.d.ts +24 -0
  193. package/lib/types/test-driver/index.d.ts.map +1 -0
  194. package/lib/types/test-driver/utils.d.ts +5 -0
  195. package/lib/types/test-driver/utils.d.ts.map +1 -0
  196. package/lib/types/togetherai/index.d.ts +23 -0
  197. package/lib/types/togetherai/index.d.ts.map +1 -0
  198. package/lib/types/togetherai/interfaces.d.ts +96 -0
  199. package/lib/types/togetherai/interfaces.d.ts.map +1 -0
  200. package/lib/types/vertexai/debug.d.ts +2 -0
  201. package/lib/types/vertexai/debug.d.ts.map +1 -0
  202. package/lib/types/vertexai/embeddings/embeddings-image.d.ts +11 -0
  203. package/lib/types/vertexai/embeddings/embeddings-image.d.ts.map +1 -0
  204. package/lib/types/vertexai/embeddings/embeddings-text.d.ts +10 -0
  205. package/lib/types/vertexai/embeddings/embeddings-text.d.ts.map +1 -0
  206. package/lib/types/vertexai/index.d.ts +79 -0
  207. package/lib/types/vertexai/index.d.ts.map +1 -0
  208. package/lib/types/vertexai/models/claude.d.ts +103 -0
  209. package/lib/types/vertexai/models/claude.d.ts.map +1 -0
  210. package/lib/types/vertexai/models/gemini.d.ts +78 -0
  211. package/lib/types/vertexai/models/gemini.d.ts.map +1 -0
  212. package/lib/types/vertexai/models/imagen.d.ts +75 -0
  213. package/lib/types/vertexai/models/imagen.d.ts.map +1 -0
  214. package/lib/types/vertexai/models/llama.d.ts +20 -0
  215. package/lib/types/vertexai/models/llama.d.ts.map +1 -0
  216. package/lib/types/vertexai/models.d.ts +20 -0
  217. package/lib/types/vertexai/models.d.ts.map +1 -0
  218. package/lib/types/watsonx/index.d.ts +27 -0
  219. package/lib/types/watsonx/index.d.ts.map +1 -0
  220. package/lib/types/watsonx/interfaces.d.ts +65 -0
  221. package/lib/types/watsonx/interfaces.d.ts.map +1 -0
  222. package/lib/types/xai/index.d.ts +18 -0
  223. package/lib/types/xai/index.d.ts.map +1 -0
  224. package/package.json +18 -18
  225. package/src/bedrock/converse.ts +85 -10
  226. package/src/bedrock/error-handling.test.ts +352 -0
  227. package/src/bedrock/index.ts +293 -16
  228. package/src/groq/index.ts +9 -4
  229. package/src/mistral/index.ts +25 -22
  230. package/src/mistral/types.ts +0 -5
  231. package/src/openai/error-handling.test.ts +567 -0
  232. package/src/openai/index.ts +513 -33
  233. package/src/openai/openai_compatible.ts +7 -0
  234. package/src/openai/openai_format.ts +1 -1
  235. package/src/vertexai/index.ts +61 -13
  236. package/src/vertexai/models/claude-error-handling.test.ts +432 -0
  237. package/src/vertexai/models/claude.ts +287 -10
  238. package/src/vertexai/models/gemini-error-handling.test.ts +353 -0
  239. package/src/vertexai/models/gemini.ts +329 -52
  240. package/src/vertexai/models.ts +7 -2
@@ -0,0 +1,1093 @@
1
+ import { AbstractDriver, LlumiverseError, ModelType, TrainingJobStatus, getConversationMeta, getModelCapabilities, incrementConversationTurn, modelModalitiesToArray, stripBase64ImagesFromConversation, stripHeartbeatsFromConversation, supportsToolUse, truncateLargeTextInConversation, unwrapConversationArray, } from "@llumiverse/core";
2
+ import { APIConnectionError, APIConnectionTimeoutError, APIError, AuthenticationError, BadRequestError, ConflictError, ContentFilterFinishReasonError, InternalServerError, LengthFinishReasonError, NotFoundError, OpenAIError, PermissionDeniedError, RateLimitError, UnprocessableEntityError, } from 'openai/error';
3
+ import { formatOpenAILikeMultimodalPrompt } from "./openai_format.js";
4
+ // Helper function to convert string to CompletionResult[]
5
+ function textToCompletionResult(text) {
6
+ return text ? [{ type: "text", value: text }] : [];
7
+ }
8
+ //TODO: Do we need a list?, replace with if statements and modernize?
9
+ const supportFineTunning = new Set([
10
+ "gpt-3.5-turbo-1106",
11
+ "gpt-3.5-turbo-0613",
12
+ "babbage-002",
13
+ "davinci-002",
14
+ "gpt-4-0613"
15
+ ]);
16
+ export class BaseOpenAIDriver extends AbstractDriver {
17
+ constructor(opts) {
18
+ super(opts);
19
+ this.formatPrompt = formatOpenAILikeMultimodalPrompt;
20
+ }
21
+ extractDataFromResponse(_options, result) {
22
+ const tokenInfo = mapUsage(result.usage);
23
+ const tools = collectTools(result.output);
24
+ // Collect all parts in order (text and images)
25
+ const allResults = extractCompletionResults(result.output);
26
+ if (allResults.length === 0 && !tools) {
27
+ this.logger.error({ result }, "[OpenAI] Response is not valid");
28
+ throw new Error("Response is not valid: no data");
29
+ }
30
+ return {
31
+ result: allResults,
32
+ token_usage: tokenInfo,
33
+ finish_reason: responseFinishReason(result, tools),
34
+ tool_use: tools,
35
+ };
36
+ }
37
+ async requestTextCompletionStream(prompt, options) {
38
+ if (options.model_options?._option_id !== "openai-text" && options.model_options?._option_id !== "openai-thinking") {
39
+ this.logger.warn({ options: options.model_options }, "Invalid model options");
40
+ }
41
+ // Include conversation history (same as non-streaming)
42
+ // Fix orphaned function_call items (can occur when agent is stopped mid-tool-execution)
43
+ let conversation = fixOrphanedToolUse(updateConversation(options.conversation, prompt));
44
+ const toolDefs = getToolDefinitions(options.tools);
45
+ const useTools = toolDefs ? supportsToolUse(options.model, this.provider, true) : false;
46
+ // When no tools are provided but conversation contains function_call/function_call_output
47
+ // items (e.g. checkpoint summary calls), convert them to text to avoid API errors
48
+ if (!useTools) {
49
+ conversation = convertOpenAIFunctionItemsToText(conversation);
50
+ }
51
+ convertRoles(prompt, options.model);
52
+ const model_options = options.model_options;
53
+ insert_image_detail(prompt, model_options?.image_detail ?? "auto");
54
+ let parsedSchema = undefined;
55
+ let strictMode = false;
56
+ if (options.result_schema && supportsSchema(options.model)) {
57
+ try {
58
+ parsedSchema = openAISchemaFormat(options.result_schema);
59
+ strictMode = true;
60
+ }
61
+ catch (e) {
62
+ parsedSchema = limitedSchemaFormat(options.result_schema);
63
+ strictMode = false;
64
+ }
65
+ }
66
+ const reasoning = model_options?.reasoning_effort ? { effort: model_options.reasoning_effort } : undefined;
67
+ const isReasoningModel = /\b(o1|o3|o4)\b/.test(options.model);
68
+ const stream = await this.service.responses.create({
69
+ stream: true,
70
+ model: options.model,
71
+ input: conversation,
72
+ reasoning,
73
+ temperature: isReasoningModel ? undefined : model_options?.temperature,
74
+ top_p: isReasoningModel ? undefined : model_options?.top_p,
75
+ max_output_tokens: model_options?.max_tokens,
76
+ tools: useTools ? toolDefs : undefined,
77
+ text: parsedSchema ? {
78
+ format: {
79
+ type: "json_schema",
80
+ name: "format_output",
81
+ schema: parsedSchema,
82
+ strict: strictMode,
83
+ }
84
+ } : undefined,
85
+ });
86
+ return mapResponseStream(stream);
87
+ }
88
+ async requestTextCompletion(prompt, options) {
89
+ if (options.model_options?._option_id !== "openai-text" && options.model_options?._option_id !== "openai-thinking") {
90
+ this.logger.warn({ options: options.model_options }, "Invalid model options");
91
+ }
92
+ convertRoles(prompt, options.model);
93
+ const model_options = options.model_options;
94
+ insert_image_detail(prompt, model_options?.image_detail ?? "auto");
95
+ const toolDefs = getToolDefinitions(options.tools);
96
+ const useTools = toolDefs ? supportsToolUse(options.model, this.provider) : false;
97
+ // Fix orphaned function_call items (can occur when agent is stopped mid-tool-execution)
98
+ let conversation = fixOrphanedToolUse(updateConversation(options.conversation, prompt));
99
+ // When no tools are provided but conversation contains function_call/function_call_output
100
+ // items (e.g. checkpoint summary calls), convert them to text to avoid API errors
101
+ if (!useTools) {
102
+ conversation = convertOpenAIFunctionItemsToText(conversation);
103
+ }
104
+ let parsedSchema = undefined;
105
+ let strictMode = false;
106
+ if (options.result_schema && supportsSchema(options.model)) {
107
+ try {
108
+ parsedSchema = openAISchemaFormat(options.result_schema);
109
+ strictMode = true;
110
+ }
111
+ catch (e) {
112
+ parsedSchema = limitedSchemaFormat(options.result_schema);
113
+ strictMode = false;
114
+ }
115
+ }
116
+ const reasoning = model_options?.reasoning_effort ? { effort: model_options.reasoning_effort } : undefined;
117
+ const isReasoningModel = /\b(o1|o3|o4)\b/.test(options.model);
118
+ const res = await this.service.responses.create({
119
+ stream: false,
120
+ model: options.model,
121
+ input: conversation,
122
+ reasoning,
123
+ temperature: isReasoningModel ? undefined : model_options?.temperature,
124
+ top_p: isReasoningModel ? undefined : model_options?.top_p,
125
+ max_output_tokens: model_options?.max_tokens, //TODO: use max_tokens for older models, currently relying on OpenAI to handle it
126
+ tools: useTools ? toolDefs : undefined,
127
+ text: parsedSchema ? {
128
+ format: {
129
+ type: "json_schema",
130
+ name: "format_output",
131
+ schema: parsedSchema,
132
+ strict: strictMode,
133
+ }
134
+ } : undefined,
135
+ });
136
+ const completion = this.extractDataFromResponse(options, res);
137
+ if (options.include_original_response) {
138
+ completion.original_response = res;
139
+ }
140
+ conversation = updateConversation(conversation, createAssistantMessageFromCompletion(completion));
141
+ // Increment turn counter for deferred stripping
142
+ conversation = incrementConversationTurn(conversation);
143
+ // Strip large base64 image data based on options.stripImagesAfterTurns
144
+ const currentTurn = getConversationMeta(conversation).turnNumber;
145
+ const stripOptions = {
146
+ keepForTurns: options.stripImagesAfterTurns ?? Infinity,
147
+ currentTurn,
148
+ textMaxTokens: options.stripTextMaxTokens
149
+ };
150
+ let processedConversation = stripBase64ImagesFromConversation(conversation, stripOptions);
151
+ // Truncate large text content if configured
152
+ processedConversation = truncateLargeTextInConversation(processedConversation, stripOptions);
153
+ // Strip old heartbeat status messages
154
+ processedConversation = stripHeartbeatsFromConversation(processedConversation, {
155
+ keepForTurns: options.stripHeartbeatsAfterTurns ?? 1,
156
+ currentTurn,
157
+ });
158
+ completion.conversation = processedConversation;
159
+ return completion;
160
+ }
161
+ canStream(_options) {
162
+ // Image generation models don't support streaming
163
+ if (_options.model.includes("dall-e")
164
+ || _options.model.includes("gpt-image")
165
+ || _options.model.includes("chatgpt-image")) {
166
+ return Promise.resolve(false);
167
+ }
168
+ if (_options.model.includes("o1")
169
+ && !(_options.model.includes("mini") || _options.model.includes("preview"))) {
170
+ //o1 full does not support streaming
171
+ //TODO: Update when OpenAI adds support for streaming, last check 16/02/2025
172
+ return Promise.resolve(false);
173
+ }
174
+ return Promise.resolve(true);
175
+ }
176
+ /**
177
+ * Build conversation context after streaming completion.
178
+ * Reconstructs the assistant message from accumulated results and applies stripping.
179
+ */
180
+ buildStreamingConversation(prompt, result, toolUse, options) {
181
+ // Build assistant message from accumulated CompletionResult[]
182
+ const completionResults = result;
183
+ const textContent = completionResultsToText(completionResults);
184
+ // Start with the conversation from options or the prompt
185
+ let conversation = updateConversation(options.conversation, prompt);
186
+ // Add assistant message as EasyInputMessage
187
+ if (textContent) {
188
+ const assistantMessage = {
189
+ role: 'assistant',
190
+ content: textContent,
191
+ };
192
+ conversation = updateConversation(conversation, [assistantMessage]);
193
+ }
194
+ // Add function calls as separate items (Response API format)
195
+ if (toolUse && toolUse.length > 0) {
196
+ const functionCalls = toolUse.map(t => ({
197
+ type: 'function_call',
198
+ call_id: t.id,
199
+ name: t.tool_name,
200
+ arguments: typeof t.tool_input === 'string' ? t.tool_input : JSON.stringify(t.tool_input ?? {}),
201
+ }));
202
+ conversation = updateConversation(conversation, functionCalls);
203
+ }
204
+ // Increment turn counter
205
+ conversation = incrementConversationTurn(conversation);
206
+ // Apply stripping based on options
207
+ const currentTurn = getConversationMeta(conversation).turnNumber;
208
+ const stripOptions = {
209
+ keepForTurns: options.stripImagesAfterTurns ?? Infinity,
210
+ currentTurn,
211
+ textMaxTokens: options.stripTextMaxTokens
212
+ };
213
+ let processedConversation = stripBase64ImagesFromConversation(conversation, stripOptions);
214
+ processedConversation = truncateLargeTextInConversation(processedConversation, stripOptions);
215
+ processedConversation = stripHeartbeatsFromConversation(processedConversation, {
216
+ keepForTurns: options.stripHeartbeatsAfterTurns ?? 1,
217
+ currentTurn,
218
+ });
219
+ return processedConversation;
220
+ }
221
+ createTrainingPrompt(options) {
222
+ if (options.model.includes("gpt")) {
223
+ return super.createTrainingPrompt(options);
224
+ }
225
+ else {
226
+ // babbage, davinci not yet implemented
227
+ throw new Error("Unsupported model for training: " + options.model);
228
+ }
229
+ }
230
+ async startTraining(dataset, options) {
231
+ const url = await dataset.getURL();
232
+ const file = await this.service.files.create({
233
+ file: await fetch(url),
234
+ purpose: "fine-tune",
235
+ });
236
+ const job = await this.service.fineTuning.jobs.create({
237
+ training_file: file.id,
238
+ model: options.model,
239
+ hyperparameters: options.params
240
+ });
241
+ return jobInfo(job);
242
+ }
243
+ async cancelTraining(jobId) {
244
+ const job = await this.service.fineTuning.jobs.cancel(jobId);
245
+ return jobInfo(job);
246
+ }
247
+ async getTrainingJob(jobId) {
248
+ const job = await this.service.fineTuning.jobs.retrieve(jobId);
249
+ return jobInfo(job);
250
+ }
251
+ // ========= management API =============
252
+ async validateConnection() {
253
+ try {
254
+ await this.service.models.list();
255
+ return true;
256
+ }
257
+ catch (error) {
258
+ return false;
259
+ }
260
+ }
261
+ listTrainableModels() {
262
+ return this._listModels((m) => supportFineTunning.has(m.id));
263
+ }
264
+ async listModels() {
265
+ return this._listModels();
266
+ }
267
+ async _listModels(filter) {
268
+ let result = (await this.service.models.list()).data;
269
+ //Some of these use the completions API instead of the chat completions API.
270
+ //Others are for non-text input modalities. Therefore common to both.
271
+ const wordBlacklist = ["embed", "whisper", "transcribe", "audio", "moderation", "tts",
272
+ "realtime", "babbage", "davinci", "codex", "o1-pro", "computer-use", "sora"];
273
+ //OpenAI has very little information, filtering based on name.
274
+ result = result.filter((m) => {
275
+ return !wordBlacklist.some((word) => m.id.includes(word));
276
+ });
277
+ const models = filter ? result.filter(filter) : result;
278
+ const aiModels = models.map((m) => {
279
+ const modelCapability = getModelCapabilities(m.id, "openai");
280
+ let owner = m.owned_by;
281
+ if (owner == "system") {
282
+ owner = "openai";
283
+ }
284
+ // Determine model type based on capabilities
285
+ let modelType = ModelType.Text;
286
+ if (m.id.includes("dall-e") || m.id.includes("gpt-image")) {
287
+ modelType = ModelType.Image;
288
+ }
289
+ return {
290
+ id: m.id,
291
+ name: m.id,
292
+ provider: this.provider,
293
+ owner: owner,
294
+ type: modelType,
295
+ input_modalities: modelModalitiesToArray(modelCapability.input),
296
+ output_modalities: modelModalitiesToArray(modelCapability.output),
297
+ tool_support: modelCapability.tool_support,
298
+ };
299
+ }).sort((a, b) => a.id.localeCompare(b.id));
300
+ return aiModels;
301
+ }
302
+ async generateEmbeddings({ text, image, model = "text-embedding-3-small" }) {
303
+ if (image) {
304
+ throw new Error("Image embeddings not supported by OpenAI");
305
+ }
306
+ if (!text) {
307
+ throw new Error("No text provided");
308
+ }
309
+ const res = await this.service.embeddings.create({
310
+ input: text,
311
+ model: model,
312
+ });
313
+ const embeddings = res.data[0].embedding;
314
+ if (!embeddings || embeddings.length === 0) {
315
+ throw new Error("No embedding found");
316
+ }
317
+ return { values: embeddings, model };
318
+ }
319
+ imageModels = ["dall-e", "gpt-image", "chatgpt-image"];
320
+ /**
321
+ * Determine if a model is specifically an image generation model (not conversational image model)
322
+ */
323
+ isImageModel(model) {
324
+ // DALL-E models are standalone image generation
325
+ // gpt-image models can generate images in conversations, not standalone
326
+ return this.imageModels.some(imageModel => model.includes(imageModel));
327
+ }
328
+ /**
329
+ * Request image generation from standalone Images API
330
+ * Supports: DALL-E 2, DALL-E 3, GPT-image models (for edit/variation)
331
+ */
332
+ async requestImageGeneration(prompt, options) {
333
+ this.logger.debug(`[${this.provider}] Generating image with model ${options.model}`);
334
+ const model_options = options.model_options;
335
+ // Extract prompt text from ResponseInputItem[]
336
+ let promptText = "";
337
+ for (const item of prompt) {
338
+ if ('content' in item && typeof item.content === 'string') {
339
+ promptText += item.content + "\\n";
340
+ }
341
+ else if ('content' in item && Array.isArray(item.content)) {
342
+ // Extract text from content array
343
+ for (const part of item.content) {
344
+ if ('type' in part && part.type === 'input_text' && 'text' in part) {
345
+ promptText += part.text + "\\n";
346
+ }
347
+ }
348
+ }
349
+ }
350
+ promptText = promptText.trim();
351
+ try {
352
+ const generateParams = {
353
+ model: options.model,
354
+ prompt: promptText,
355
+ size: model_options?.size || "1024x1024",
356
+ };
357
+ // Add DALL-E specific options
358
+ if (options.model.includes("dall-e") || model_options?._option_id === "openai-dalle") {
359
+ const dalleOptions = model_options;
360
+ generateParams.n = dalleOptions?.n || 1;
361
+ generateParams.response_format = dalleOptions?.response_format || "b64_json";
362
+ if (options.model.includes("dall-e-3")) {
363
+ generateParams.quality = dalleOptions?.image_quality || "standard";
364
+ if (dalleOptions?.style) {
365
+ generateParams.style = dalleOptions.style;
366
+ }
367
+ }
368
+ }
369
+ else {
370
+ // Default for other models
371
+ generateParams.n = 1;
372
+ }
373
+ const response = await this.service.images.generate(generateParams);
374
+ // Convert response to CompletionResults
375
+ const results = [];
376
+ if (response.data) {
377
+ for (const image of response.data) {
378
+ let imageValue;
379
+ if (image.b64_json) {
380
+ // Base64 format
381
+ imageValue = `data:image/png;base64,${image.b64_json}`;
382
+ }
383
+ else if (image.url) {
384
+ // URL format
385
+ imageValue = image.url;
386
+ }
387
+ else {
388
+ continue;
389
+ }
390
+ results.push({
391
+ type: "image",
392
+ value: imageValue
393
+ });
394
+ }
395
+ }
396
+ return {
397
+ result: results
398
+ };
399
+ }
400
+ catch (error) {
401
+ this.logger.error({ error }, `[${this.provider}] Image generation failed`);
402
+ return {
403
+ result: [],
404
+ error: {
405
+ message: error.message,
406
+ code: error.code || 'GENERATION_FAILED'
407
+ }
408
+ };
409
+ }
410
+ }
411
+ /**
412
+ * Format OpenAI API errors into LlumiverseError with proper status codes and retryability.
413
+ *
414
+ * OpenAI API errors have a specific structure:
415
+ * - APIError.status: HTTP status code (400, 401, 403, 404, 409, 422, 429, 500+)
416
+ * - APIError.error: Error object with type, message, param, code
417
+ * - APIError.requestID: Request ID for support
418
+ * - APIError.code: Error code (e.g., 'invalid_api_key', 'rate_limit_exceeded')
419
+ * - APIError.param: Parameter that caused the error (optional)
420
+ * - APIError.type: Error type (optional)
421
+ *
422
+ * Common error types:
423
+ * - BadRequestError (400): Invalid request parameters
424
+ * - AuthenticationError (401): Invalid API key
425
+ * - PermissionDeniedError (403): Insufficient permissions
426
+ * - NotFoundError (404): Resource not found
427
+ * - ConflictError (409): Resource conflict
428
+ * - UnprocessableEntityError (422): Validation error
429
+ * - RateLimitError (429): Rate limit exceeded
430
+ * - InternalServerError (500+): Server-side errors
431
+ * - APIConnectionError: Connection issues (no status code)
432
+ * - APIConnectionTimeoutError: Request timeout (no status code)
433
+ * - LengthFinishReasonError: Response truncated due to length
434
+ * - ContentFilterFinishReasonError: Content filtered
435
+ *
436
+ * This implementation works for:
437
+ * - OpenAI API
438
+ * - Azure OpenAI
439
+ * - xAI (uses OpenAI-compatible API)
440
+ * - Azure Foundry (OpenAI-compatible)
441
+ * - Other OpenAI-compatible APIs
442
+ *
443
+ * @see https://platform.openai.com/docs/guides/error-codes
444
+ */
445
+ formatLlumiverseError(error, context) {
446
+ // Check if it's an OpenAI API error
447
+ const isOpenAIError = this.isOpenAIApiError(error);
448
+ if (!isOpenAIError) {
449
+ // Not an OpenAI API error, use default handling
450
+ throw error;
451
+ }
452
+ const apiError = error;
453
+ const httpStatusCode = apiError.status;
454
+ // Extract error message
455
+ const message = apiError.message || String(error);
456
+ // Extract additional error details (only available on APIError)
457
+ const errorCode = apiError.code;
458
+ const errorParam = apiError.param;
459
+ const errorType = apiError.type;
460
+ // Build user-facing message with status code
461
+ let userMessage = message;
462
+ // Include status code in message (for end-user visibility)
463
+ if (httpStatusCode) {
464
+ userMessage = `[${httpStatusCode}] ${userMessage}`;
465
+ }
466
+ // Add error code if available and not already in message
467
+ if (errorCode && !userMessage.includes(errorCode)) {
468
+ userMessage += ` (code: ${errorCode})`;
469
+ }
470
+ // Add parameter info if available and helpful
471
+ if (errorParam && !userMessage.toLowerCase().includes(errorParam.toLowerCase())) {
472
+ userMessage += ` [param: ${errorParam}]`;
473
+ }
474
+ // Add request ID if available (useful for OpenAI support)
475
+ if (apiError.requestID) {
476
+ userMessage += ` (Request ID: ${apiError.requestID})`;
477
+ }
478
+ // Determine retryability based on OpenAI error types
479
+ const retryable = this.isOpenAIErrorRetryable(error, httpStatusCode, errorCode, errorType);
480
+ // Use the error constructor name as the error name
481
+ const errorName = error.constructor?.name || 'OpenAIError';
482
+ return new LlumiverseError(`[${context.provider}] ${userMessage}`, retryable, context, error, httpStatusCode, errorName);
483
+ }
484
+ /**
485
+ * Type guard to check if error is an OpenAI API error or OpenAI-specific error.
486
+ */
487
+ isOpenAIApiError(error) {
488
+ return (error !== null &&
489
+ typeof error === 'object' &&
490
+ (error instanceof APIError || error instanceof OpenAIError));
491
+ }
492
+ /**
493
+ * Determine if an OpenAI API error is retryable.
494
+ *
495
+ * Retryable errors:
496
+ * - RateLimitError (429): Rate limit exceeded, retry with backoff
497
+ * - InternalServerError (500+): Server-side errors
498
+ * - APIConnectionTimeoutError: Request timeout
499
+ * - Error codes: 'timeout', 'server_error', 'service_unavailable'
500
+ * - Status codes: 408, 429, 502, 503, 504, 529, 5xx
501
+ *
502
+ * Non-retryable errors:
503
+ * - BadRequestError (400): Invalid request parameters
504
+ * - AuthenticationError (401): Invalid API key
505
+ * - PermissionDeniedError (403): Insufficient permissions
506
+ * - NotFoundError (404): Resource not found
507
+ * - ConflictError (409): Resource conflict
508
+ * - UnprocessableEntityError (422): Validation error
509
+ * - LengthFinishReasonError: Length limit reached
510
+ * - ContentFilterFinishReasonError: Content filtered
511
+ * - Error codes: 'invalid_api_key', 'invalid_request_error', 'model_not_found'
512
+ * - Other 4xx client errors
513
+ *
514
+ * @param error - The error object
515
+ * @param httpStatusCode - The HTTP status code if available
516
+ * @param errorCode - The error code if available
517
+ * @param errorType - The error type if available
518
+ * @returns True if retryable, false if not retryable, undefined if unknown
519
+ */
520
+ isOpenAIErrorRetryable(error, httpStatusCode, errorCode, errorType) {
521
+ // Check specific OpenAI error types by class
522
+ if (error instanceof RateLimitError)
523
+ return true;
524
+ if (error instanceof InternalServerError)
525
+ return true;
526
+ if (error instanceof APIConnectionTimeoutError)
527
+ return true;
528
+ // Non-retryable by error type
529
+ if (error instanceof BadRequestError)
530
+ return false;
531
+ if (error instanceof AuthenticationError)
532
+ return false;
533
+ if (error instanceof PermissionDeniedError)
534
+ return false;
535
+ if (error instanceof NotFoundError)
536
+ return false;
537
+ if (error instanceof ConflictError)
538
+ return false;
539
+ if (error instanceof UnprocessableEntityError)
540
+ return false;
541
+ if (error instanceof LengthFinishReasonError)
542
+ return false;
543
+ if (error instanceof ContentFilterFinishReasonError)
544
+ return false;
545
+ // Check error codes (OpenAI specific)
546
+ if (errorCode) {
547
+ // Retryable error codes
548
+ if (errorCode === 'timeout')
549
+ return true;
550
+ if (errorCode === 'server_error')
551
+ return true;
552
+ if (errorCode === 'service_unavailable')
553
+ return true;
554
+ if (errorCode === 'rate_limit_exceeded')
555
+ return true;
556
+ // Non-retryable error codes
557
+ if (errorCode === 'invalid_api_key')
558
+ return false;
559
+ if (errorCode === 'invalid_request_error')
560
+ return false;
561
+ if (errorCode === 'model_not_found')
562
+ return false;
563
+ if (errorCode === 'insufficient_quota')
564
+ return false;
565
+ if (errorCode === 'invalid_model')
566
+ return false;
567
+ if (errorCode.includes('invalid_'))
568
+ return false;
569
+ }
570
+ // Check error type
571
+ if (errorType === 'invalid_request_error')
572
+ return false;
573
+ if (errorType === 'authentication_error')
574
+ return false;
575
+ // Use HTTP status code
576
+ if (httpStatusCode !== undefined) {
577
+ if (httpStatusCode === 429)
578
+ return true; // Rate limit
579
+ if (httpStatusCode === 408)
580
+ return true; // Request timeout
581
+ if (httpStatusCode === 502)
582
+ return true; // Bad gateway
583
+ if (httpStatusCode === 503)
584
+ return true; // Service unavailable
585
+ if (httpStatusCode === 504)
586
+ return true; // Gateway timeout
587
+ if (httpStatusCode === 529)
588
+ return true; // Overloaded
589
+ if (httpStatusCode >= 500 && httpStatusCode < 600)
590
+ return true; // Server errors
591
+ if (httpStatusCode >= 400 && httpStatusCode < 500)
592
+ return false; // Client errors
593
+ }
594
+ // Connection errors without status codes
595
+ if (error instanceof APIConnectionError && !(error instanceof APIConnectionTimeoutError)) {
596
+ // Generic connection errors might be retryable (network issues)
597
+ return true;
598
+ }
599
+ // Unknown error type - let consumer decide retry strategy
600
+ return undefined;
601
+ }
602
+ }
603
+ function jobInfo(job) {
604
+ //validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`.
605
+ const jobStatus = job.status;
606
+ let status = TrainingJobStatus.running;
607
+ let details;
608
+ if (jobStatus === 'succeeded') {
609
+ status = TrainingJobStatus.succeeded;
610
+ }
611
+ else if (jobStatus === 'failed') {
612
+ status = TrainingJobStatus.failed;
613
+ details = job.error ? `${job.error.code} - ${job.error.message} ${job.error.param ? " [" + job.error.param + "]" : ""}` : "error";
614
+ }
615
+ else if (jobStatus === 'cancelled') {
616
+ status = TrainingJobStatus.cancelled;
617
+ }
618
+ else {
619
+ status = TrainingJobStatus.running;
620
+ details = jobStatus;
621
+ }
622
+ return {
623
+ id: job.id,
624
+ model: job.fine_tuned_model || undefined,
625
+ status,
626
+ details
627
+ };
628
+ }
629
+ function mapUsage(usage) {
630
+ if (!usage) {
631
+ return undefined;
632
+ }
633
+ return {
634
+ prompt: usage.input_tokens,
635
+ result: usage.output_tokens,
636
+ total: usage.total_tokens,
637
+ };
638
+ }
639
+ function completionResultsToText(completionResults) {
640
+ if (!completionResults) {
641
+ return '';
642
+ }
643
+ return completionResults
644
+ .map(r => {
645
+ switch (r.type) {
646
+ case 'text':
647
+ return r.value;
648
+ case 'json':
649
+ return typeof r.value === 'string' ? r.value : JSON.stringify(r.value);
650
+ case 'image':
651
+ // Skip images in conversation - they're in the result
652
+ return '';
653
+ default:
654
+ return String(r.value || '');
655
+ }
656
+ })
657
+ .join('');
658
+ }
659
+ function createAssistantMessageFromCompletion(completion) {
660
+ const textContent = completionResultsToText(completion.result);
661
+ const result = [];
662
+ // Add assistant text message if present
663
+ if (textContent) {
664
+ const assistantMessage = {
665
+ role: 'assistant',
666
+ content: textContent,
667
+ };
668
+ result.push(assistantMessage);
669
+ }
670
+ // Add function calls as separate items (Response API format)
671
+ if (completion.tool_use && completion.tool_use.length > 0) {
672
+ for (const t of completion.tool_use) {
673
+ const functionCall = {
674
+ type: 'function_call',
675
+ call_id: t.id,
676
+ name: t.tool_name,
677
+ arguments: typeof t.tool_input === 'string'
678
+ ? t.tool_input
679
+ : JSON.stringify(t.tool_input ?? {}),
680
+ };
681
+ result.push(functionCall);
682
+ }
683
+ }
684
+ return result;
685
+ }
686
+ function mapResponseStream(stream) {
687
+ const toolCallMetadata = new Map();
688
+ return {
689
+ async *[Symbol.asyncIterator]() {
690
+ for await (const event of stream) {
691
+ if (event.type === 'response.output_item.added' && event.item.type === 'function_call') {
692
+ const syntheticId = `tool_${event.output_index}`;
693
+ const actualId = event.item.id ?? event.item.call_id;
694
+ if (actualId) {
695
+ toolCallMetadata.set(actualId, { syntheticId, name: event.item.name });
696
+ }
697
+ const toolUse = {
698
+ id: syntheticId,
699
+ _actual_id: actualId,
700
+ tool_name: event.item.name,
701
+ tool_input: '',
702
+ };
703
+ yield {
704
+ result: [],
705
+ tool_use: [toolUse],
706
+ };
707
+ }
708
+ else if (event.type === 'response.function_call_arguments.delta') {
709
+ const metadata = toolCallMetadata.get(event.item_id);
710
+ const syntheticId = metadata?.syntheticId ?? `tool_${event.output_index}`;
711
+ const toolUse = {
712
+ id: syntheticId,
713
+ _actual_id: event.item_id,
714
+ tool_name: metadata?.name ?? '',
715
+ tool_input: event.delta,
716
+ };
717
+ yield {
718
+ result: [],
719
+ tool_use: [toolUse],
720
+ };
721
+ }
722
+ // Note: We don't emit response.function_call_arguments.done because the arguments were already
723
+ // streamed via delta events. Emitting it again would duplicate the tool_input content.
724
+ // We only update the metadata to ensure the tool name is captured.
725
+ else if (event.type === 'response.function_call_arguments.done') {
726
+ // Just update metadata, don't yield (arguments already accumulated from delta events)
727
+ const metadata = toolCallMetadata.get(event.item_id);
728
+ const syntheticId = metadata?.syntheticId ?? `tool_${event.output_index}`;
729
+ const tool_name = metadata?.name ?? event.name ?? '';
730
+ if (event.item_id) {
731
+ toolCallMetadata.set(event.item_id, { syntheticId, name: tool_name });
732
+ }
733
+ }
734
+ else if (event.type === 'response.output_text.delta') {
735
+ yield {
736
+ result: textToCompletionResult(event.delta),
737
+ };
738
+ }
739
+ // Note: We don't emit response.output_text.done because the text was already
740
+ // streamed via delta events. Emitting it again would duplicate the content.
741
+ else if (event.type === 'response.completed' || event.type === 'response.incomplete' || event.type === 'response.failed') {
742
+ const finalTools = collectTools(event.response.output);
743
+ yield {
744
+ result: [],
745
+ finish_reason: responseFinishReason(event.response, finalTools),
746
+ token_usage: mapUsage(event.response.usage),
747
+ };
748
+ }
749
+ }
750
+ }
751
+ };
752
+ }
753
+ function insert_image_detail(items, detail_level) {
754
+ if (detail_level === "auto" || detail_level === "low" || detail_level === "high") {
755
+ for (const item of items) {
756
+ // Check if it's an EasyInputMessage or Message with content array
757
+ if ('role' in item && 'content' in item && item.role !== 'assistant') {
758
+ const content = item.content;
759
+ if (Array.isArray(content)) {
760
+ for (const part of content) {
761
+ if (typeof part === 'object' && part.type === 'input_image') {
762
+ part.detail = detail_level;
763
+ }
764
+ }
765
+ }
766
+ }
767
+ }
768
+ }
769
+ return items;
770
+ }
771
+ function convertRoles(items, model) {
772
+ //New openai models use developer role instead of system
773
+ if (model.includes("o1") || model.includes("o3")) {
774
+ if (model.includes("o1-mini") || model.includes("o1-preview")) {
775
+ //o1-mini and o1-preview support neither system nor developer
776
+ for (const item of items) {
777
+ if ('role' in item && item.role === 'system') {
778
+ item.role = 'user';
779
+ }
780
+ }
781
+ }
782
+ else {
783
+ //Models newer than o1 use developer role
784
+ for (const item of items) {
785
+ if ('role' in item && item.role === 'system') {
786
+ item.role = 'developer';
787
+ }
788
+ }
789
+ }
790
+ }
791
+ return items;
792
+ }
793
+ //Structured output support is typically aligned with tool use support
794
+ //Not true for realtime models, which do not support structured output, but do support tool use.
795
+ function supportsSchema(model) {
796
+ const realtimeModel = model.includes("realtime");
797
+ if (realtimeModel) {
798
+ return false;
799
+ }
800
+ return supportsToolUse(model, "openai");
801
+ }
802
+ /**
803
+ * Converts function_call and function_call_output items to text messages in OpenAI conversation.
804
+ * Preserves tool call information while removing structured items that require
805
+ * tools to be defined in the API request.
806
+ */
807
+ export function convertOpenAIFunctionItemsToText(items) {
808
+ const hasFunctionItems = items.some(item => {
809
+ const type = item.type;
810
+ return type === 'function_call' || type === 'function_call_output';
811
+ });
812
+ if (!hasFunctionItems)
813
+ return items;
814
+ return items.map(item => {
815
+ const typed = item;
816
+ if (typed.type === 'function_call') {
817
+ const argsStr = typed.arguments || '';
818
+ const truncated = argsStr.length > 500 ? argsStr.substring(0, 500) + '...' : argsStr;
819
+ return {
820
+ role: 'assistant',
821
+ content: `[Tool call: ${typed.name}(${truncated})]`,
822
+ };
823
+ }
824
+ if (typed.type === 'function_call_output') {
825
+ const output = typed.output || 'No output';
826
+ const truncated = output.length > 500 ? output.substring(0, 500) + '...' : output;
827
+ return {
828
+ role: 'user',
829
+ content: `[Tool result: ${truncated}]`,
830
+ };
831
+ }
832
+ return item;
833
+ });
834
+ }
835
+ function getToolDefinitions(tools) {
836
+ return tools ? tools.map(getToolDefinition) : undefined;
837
+ }
838
+ function getToolDefinition(toolDef) {
839
+ let parsedSchema = undefined;
840
+ let strictMode = false;
841
+ if (toolDef.input_schema) {
842
+ try {
843
+ //TODO: type assertion here is not safe, does not work with satisfies
844
+ parsedSchema = openAISchemaFormat(toolDef.input_schema);
845
+ strictMode = true;
846
+ }
847
+ catch (e) {
848
+ //TODO: type assertion here is not safe, does not work with satisfies
849
+ parsedSchema = limitedSchemaFormat(toolDef.input_schema);
850
+ strictMode = false;
851
+ }
852
+ }
853
+ return {
854
+ type: "function",
855
+ name: toolDef.name,
856
+ description: toolDef.description,
857
+ parameters: parsedSchema ?? null,
858
+ strict: strictMode,
859
+ };
860
+ }
861
+ function updateConversation(conversation, items) {
862
+ if (!items) {
863
+ // Unwrap array if wrapped, otherwise treat as array
864
+ const unwrapped = unwrapConversationArray(conversation);
865
+ return unwrapped ?? (conversation || []);
866
+ }
867
+ if (!conversation) {
868
+ return items;
869
+ }
870
+ // Unwrap array if wrapped, otherwise treat as array
871
+ const unwrapped = unwrapConversationArray(conversation);
872
+ const convArray = unwrapped ?? conversation;
873
+ return [...convArray, ...items];
874
+ }
875
+ export function collectTools(output) {
876
+ if (!output) {
877
+ return undefined;
878
+ }
879
+ const tools = [];
880
+ for (const item of output) {
881
+ if (item.type === 'function_call') {
882
+ const id = item.call_id || item.id;
883
+ if (!id) {
884
+ continue;
885
+ }
886
+ tools.push({
887
+ id,
888
+ tool_name: item.name ?? '',
889
+ tool_input: safeJsonParse(item.arguments),
890
+ });
891
+ }
892
+ }
893
+ return tools.length > 0 ? tools : undefined;
894
+ }
895
+ /**
896
+ * Collect all parts (text and images) from response output in order.
897
+ * This preserves the original ordering of text and image parts.
898
+ */
899
+ function extractCompletionResults(output) {
900
+ if (!output) {
901
+ return [];
902
+ }
903
+ const results = [];
904
+ for (const item of output) {
905
+ if (item.type === 'message') {
906
+ // Extract text from message content
907
+ for (const part of item.content) {
908
+ if (part.type === 'output_text' && part.text) {
909
+ results.push({
910
+ type: "text",
911
+ value: part.text
912
+ });
913
+ }
914
+ }
915
+ }
916
+ else if (item.type === 'image_generation_call' && 'result' in item && item.result) {
917
+ // GPT-image models return base64 encoded images in result field
918
+ const base64Data = item.result;
919
+ // Format as data URL for consistency with other image outputs
920
+ const imageUrl = base64Data.startsWith('data:')
921
+ ? base64Data
922
+ : `data:image/png;base64,${base64Data}`;
923
+ results.push({
924
+ type: "image",
925
+ value: imageUrl
926
+ });
927
+ }
928
+ }
929
+ return results;
930
+ }
931
+ //For strict mode false
932
+ function limitedSchemaFormat(schema) {
933
+ const formattedSchema = { ...schema };
934
+ // Defaults not supported
935
+ delete formattedSchema.default;
936
+ // OpenAI requires type field even in non-strict mode
937
+ // If no type is specified, default to 'object' for properties with format/editor hints,
938
+ // otherwise 'string' as a safe fallback
939
+ if (!formattedSchema.type && formattedSchema.description) {
940
+ // Properties with format: "document" or editor hints are typically objects
941
+ if (formattedSchema.format === 'document' || formattedSchema.editor) {
942
+ formattedSchema.type = 'object';
943
+ }
944
+ else {
945
+ formattedSchema.type = 'string';
946
+ }
947
+ }
948
+ if (formattedSchema?.properties) {
949
+ // Process each property recursively
950
+ for (const propName of Object.keys(formattedSchema.properties)) {
951
+ const property = formattedSchema.properties[propName];
952
+ // Recursively process properties
953
+ formattedSchema.properties[propName] = limitedSchemaFormat(property);
954
+ // Process arrays with items of type object
955
+ if (property?.type === 'array' && property.items && property.items?.type === 'object') {
956
+ formattedSchema.properties[propName] = {
957
+ ...property,
958
+ items: limitedSchemaFormat(property.items),
959
+ };
960
+ }
961
+ }
962
+ }
963
+ return formattedSchema;
964
+ }
965
+ //For strict mode true
966
+ function openAISchemaFormat(schema, nesting = 0) {
967
+ if (nesting > 5) {
968
+ throw new Error("OpenAI schema nesting too deep");
969
+ }
970
+ const formattedSchema = { ...schema };
971
+ // Defaults not supported
972
+ delete formattedSchema.default;
973
+ // Additional properties not supported, required to be set.
974
+ if (formattedSchema?.type === "object") {
975
+ formattedSchema.additionalProperties = false;
976
+ }
977
+ if (formattedSchema?.properties) {
978
+ // Set all properties as required
979
+ formattedSchema.required = Object.keys(formattedSchema.properties);
980
+ // Process each property recursively
981
+ for (const propName of Object.keys(formattedSchema.properties)) {
982
+ const property = formattedSchema.properties[propName];
983
+ // OpenAI strict mode requires all properties to have a type
984
+ if (!property?.type) {
985
+ throw new Error(`Property '${propName}' is missing required 'type' field for OpenAI strict mode`);
986
+ }
987
+ // Recursively process properties
988
+ formattedSchema.properties[propName] = openAISchemaFormat(property, nesting + 1);
989
+ // Process arrays with items of type object
990
+ if (property?.type === 'array' && property.items && property.items?.type === 'object') {
991
+ formattedSchema.properties[propName] = {
992
+ ...property,
993
+ items: openAISchemaFormat(property.items, nesting + 1),
994
+ };
995
+ }
996
+ }
997
+ }
998
+ if (formattedSchema?.type === 'object' && (!formattedSchema?.properties || Object.keys(formattedSchema?.properties ?? {}).length == 0)) {
999
+ //If no properties are defined, then additionalProperties: true was set or the object would be empty.
1000
+ //OpenAI does not support this on structured output/ strict mode.
1001
+ throw new Error("OpenAI does not support empty objects or objects with additionalProperties set to true");
1002
+ }
1003
+ return formattedSchema;
1004
+ }
1005
+ function responseFinishReason(response, tools) {
1006
+ if (tools && tools.length > 0) {
1007
+ return "tool_use";
1008
+ }
1009
+ if (response.status === 'incomplete') {
1010
+ if (response.incomplete_details?.reason === 'max_output_tokens') {
1011
+ return 'length';
1012
+ }
1013
+ return response.incomplete_details?.reason ?? 'incomplete';
1014
+ }
1015
+ if (response.status && response.status !== 'completed') {
1016
+ return response.status;
1017
+ }
1018
+ return 'stop';
1019
+ }
1020
+ /**
1021
+ * Fix orphaned function_call items in the OpenAI Responses API conversation.
1022
+ *
1023
+ * When an agent is stopped mid-tool-execution, the conversation may contain
1024
+ * function_call items without matching function_call_output items. The OpenAI
1025
+ * Responses API requires every function_call to have a matching function_call_output.
1026
+ *
1027
+ * This function detects such cases and injects synthetic function_call_output items
1028
+ * indicating the tools were interrupted, allowing the conversation to continue.
1029
+ */
1030
+ export function fixOrphanedToolUse(items) {
1031
+ if (items.length < 2)
1032
+ return items;
1033
+ // First pass: collect all function_call_output call_ids
1034
+ const outputCallIds = new Set();
1035
+ for (const item of items) {
1036
+ if ('type' in item && item.type === 'function_call_output') {
1037
+ outputCallIds.add(item.call_id);
1038
+ }
1039
+ }
1040
+ // Second pass: build result, injecting synthetic outputs for orphaned function_calls
1041
+ const result = [];
1042
+ const pendingCalls = new Map(); // call_id -> tool name
1043
+ for (const item of items) {
1044
+ if ('type' in item && item.type === 'function_call') {
1045
+ const fc = item;
1046
+ // Only track if there's no matching output anywhere in the conversation
1047
+ if (!outputCallIds.has(fc.call_id)) {
1048
+ pendingCalls.set(fc.call_id, fc.name ?? 'unknown');
1049
+ }
1050
+ result.push(item);
1051
+ }
1052
+ else if ('type' in item && item.type === 'function_call_output') {
1053
+ result.push(item);
1054
+ }
1055
+ else {
1056
+ // Before any non-function item, flush pending orphaned calls
1057
+ if (pendingCalls.size > 0) {
1058
+ for (const [callId, toolName] of pendingCalls) {
1059
+ result.push({
1060
+ type: 'function_call_output',
1061
+ call_id: callId,
1062
+ output: `[Tool interrupted: The user stopped the operation before "${toolName}" could execute.]`,
1063
+ });
1064
+ }
1065
+ pendingCalls.clear();
1066
+ }
1067
+ result.push(item);
1068
+ }
1069
+ }
1070
+ // Handle trailing orphans at the end of the conversation
1071
+ if (pendingCalls.size > 0) {
1072
+ for (const [callId, toolName] of pendingCalls) {
1073
+ result.push({
1074
+ type: 'function_call_output',
1075
+ call_id: callId,
1076
+ output: `[Tool interrupted: The user stopped the operation before "${toolName}" could execute.]`,
1077
+ });
1078
+ }
1079
+ }
1080
+ return result;
1081
+ }
1082
+ function safeJsonParse(value) {
1083
+ if (typeof value !== 'string') {
1084
+ return value;
1085
+ }
1086
+ try {
1087
+ return JSON.parse(value);
1088
+ }
1089
+ catch {
1090
+ return value;
1091
+ }
1092
+ }
1093
+ //# sourceMappingURL=index.js.map