@llumiverse/drivers 0.25.0 → 0.25.1-dev.20260210.145152Z

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 (224) 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 +285 -0
  6. package/lib/cjs/bedrock/converse.js.map +1 -0
  7. package/lib/cjs/bedrock/index.js +1091 -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 +323 -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 +173 -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 +665 -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 +62 -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 +576 -0
  59. package/lib/cjs/vertexai/index.js.map +1 -0
  60. package/lib/cjs/vertexai/models/claude.js +485 -0
  61. package/lib/cjs/vertexai/models/claude.js.map +1 -0
  62. package/lib/cjs/vertexai/models/gemini.js +871 -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 +278 -0
  81. package/lib/esm/bedrock/converse.js.map +1 -0
  82. package/lib/esm/bedrock/index.js +1087 -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 +316 -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 +169 -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 +660 -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 +55 -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 +571 -0
  133. package/lib/esm/vertexai/index.js.map +1 -0
  134. package/lib/esm/vertexai/models/claude.js +479 -0
  135. package/lib/esm/vertexai/models/claude.js.map +1 -0
  136. package/lib/esm/vertexai/models/gemini.js +866 -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 +9 -0
  155. package/lib/types/bedrock/converse.d.ts.map +1 -0
  156. package/lib/types/bedrock/index.d.ts +68 -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 +132 -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 +31 -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 +26 -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 +65 -0
  207. package/lib/types/vertexai/index.d.ts.map +1 -0
  208. package/lib/types/vertexai/models/claude.d.ts +28 -0
  209. package/lib/types/vertexai/models/claude.d.ts.map +1 -0
  210. package/lib/types/vertexai/models/gemini.d.ts +18 -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 +15 -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 +3 -3
@@ -0,0 +1,660 @@
1
+ import { AbstractDriver, ModelType, TrainingJobStatus, getConversationMeta, getModelCapabilities, incrementConversationTurn, modelModalitiesToArray, stripBase64ImagesFromConversation, supportsToolUse, truncateLargeTextInConversation, unwrapConversationArray, } from "@llumiverse/core";
2
+ import { formatOpenAILikeMultimodalPrompt } from "./openai_format.js";
3
+ // Helper function to convert string to CompletionResult[]
4
+ function textToCompletionResult(text) {
5
+ return text ? [{ type: "text", value: text }] : [];
6
+ }
7
+ //TODO: Do we need a list?, replace with if statements and modernize?
8
+ const supportFineTunning = new Set([
9
+ "gpt-3.5-turbo-1106",
10
+ "gpt-3.5-turbo-0613",
11
+ "babbage-002",
12
+ "davinci-002",
13
+ "gpt-4-0613"
14
+ ]);
15
+ export class BaseOpenAIDriver extends AbstractDriver {
16
+ constructor(opts) {
17
+ super(opts);
18
+ this.formatPrompt = formatOpenAILikeMultimodalPrompt;
19
+ }
20
+ extractDataFromResponse(_options, result) {
21
+ const tokenInfo = mapUsage(result.usage);
22
+ const tools = collectTools(result.output);
23
+ const data = extractTextFromResponse(result);
24
+ if (!data && !tools) {
25
+ this.logger.error({ result }, "[OpenAI] Response is not valid");
26
+ throw new Error("Response is not valid: no data");
27
+ }
28
+ return {
29
+ result: textToCompletionResult(data || ''),
30
+ token_usage: tokenInfo,
31
+ finish_reason: responseFinishReason(result, tools),
32
+ tool_use: tools,
33
+ };
34
+ }
35
+ async requestTextCompletionStream(prompt, options) {
36
+ if (options.model_options?._option_id !== "openai-text" && options.model_options?._option_id !== "openai-thinking") {
37
+ this.logger.warn({ options: options.model_options }, "Invalid model options");
38
+ }
39
+ // Include conversation history (same as non-streaming)
40
+ const conversation = updateConversation(options.conversation, prompt);
41
+ const toolDefs = getToolDefinitions(options.tools);
42
+ const useTools = toolDefs ? supportsToolUse(options.model, this.provider, true) : false;
43
+ convertRoles(prompt, options.model);
44
+ const model_options = options.model_options;
45
+ insert_image_detail(prompt, model_options?.image_detail ?? "auto");
46
+ let parsedSchema = undefined;
47
+ let strictMode = false;
48
+ if (options.result_schema && supportsSchema(options.model)) {
49
+ try {
50
+ parsedSchema = openAISchemaFormat(options.result_schema);
51
+ strictMode = true;
52
+ }
53
+ catch (e) {
54
+ parsedSchema = limitedSchemaFormat(options.result_schema);
55
+ strictMode = false;
56
+ }
57
+ }
58
+ const reasoning = model_options?.reasoning_effort ? { effort: model_options.reasoning_effort } : undefined;
59
+ const stream = await this.service.responses.create({
60
+ stream: true,
61
+ model: options.model,
62
+ input: conversation,
63
+ reasoning,
64
+ temperature: model_options?.temperature,
65
+ top_p: model_options?.top_p,
66
+ max_output_tokens: model_options?.max_tokens,
67
+ tools: useTools ? toolDefs : undefined,
68
+ text: parsedSchema ? {
69
+ format: {
70
+ type: "json_schema",
71
+ name: "format_output",
72
+ schema: parsedSchema,
73
+ strict: strictMode,
74
+ }
75
+ } : undefined,
76
+ });
77
+ return mapResponseStream(stream);
78
+ }
79
+ async requestTextCompletion(prompt, options) {
80
+ if (options.model_options?._option_id !== "openai-text" && options.model_options?._option_id !== "openai-thinking") {
81
+ this.logger.warn({ options: options.model_options }, "Invalid model options");
82
+ }
83
+ convertRoles(prompt, options.model);
84
+ const model_options = options.model_options;
85
+ insert_image_detail(prompt, model_options?.image_detail ?? "auto");
86
+ const toolDefs = getToolDefinitions(options.tools);
87
+ const useTools = toolDefs ? supportsToolUse(options.model, this.provider) : false;
88
+ let conversation = updateConversation(options.conversation, prompt);
89
+ let parsedSchema = undefined;
90
+ let strictMode = false;
91
+ if (options.result_schema && supportsSchema(options.model)) {
92
+ try {
93
+ parsedSchema = openAISchemaFormat(options.result_schema);
94
+ strictMode = true;
95
+ }
96
+ catch (e) {
97
+ parsedSchema = limitedSchemaFormat(options.result_schema);
98
+ strictMode = false;
99
+ }
100
+ }
101
+ const reasoning = model_options?.reasoning_effort ? { effort: model_options.reasoning_effort } : undefined;
102
+ const res = await this.service.responses.create({
103
+ stream: false,
104
+ model: options.model,
105
+ input: conversation,
106
+ reasoning,
107
+ temperature: model_options?.temperature,
108
+ top_p: model_options?.top_p,
109
+ max_output_tokens: model_options?.max_tokens, //TODO: use max_tokens for older models, currently relying on OpenAI to handle it
110
+ tools: useTools ? toolDefs : undefined,
111
+ text: parsedSchema ? {
112
+ format: {
113
+ type: "json_schema",
114
+ name: "format_output",
115
+ schema: parsedSchema,
116
+ strict: strictMode,
117
+ }
118
+ } : undefined,
119
+ });
120
+ const completion = this.extractDataFromResponse(options, res);
121
+ if (options.include_original_response) {
122
+ completion.original_response = res;
123
+ }
124
+ conversation = updateConversation(conversation, createAssistantMessageFromCompletion(completion));
125
+ // Increment turn counter for deferred stripping
126
+ conversation = incrementConversationTurn(conversation);
127
+ // Strip large base64 image data based on options.stripImagesAfterTurns
128
+ const currentTurn = getConversationMeta(conversation).turnNumber;
129
+ const stripOptions = {
130
+ keepForTurns: options.stripImagesAfterTurns ?? Infinity,
131
+ currentTurn,
132
+ textMaxTokens: options.stripTextMaxTokens
133
+ };
134
+ let processedConversation = stripBase64ImagesFromConversation(conversation, stripOptions);
135
+ // Truncate large text content if configured
136
+ processedConversation = truncateLargeTextInConversation(processedConversation, stripOptions);
137
+ completion.conversation = processedConversation;
138
+ return completion;
139
+ }
140
+ canStream(_options) {
141
+ if (_options.model.includes("o1")
142
+ && !(_options.model.includes("mini") || _options.model.includes("preview"))) {
143
+ //o1 full does not support streaming
144
+ //TODO: Update when OpenAI adds support for streaming, last check 16/02/2025
145
+ return Promise.resolve(false);
146
+ }
147
+ return Promise.resolve(true);
148
+ }
149
+ /**
150
+ * Build conversation context after streaming completion.
151
+ * Reconstructs the assistant message from accumulated results and applies stripping.
152
+ */
153
+ buildStreamingConversation(prompt, result, toolUse, options) {
154
+ // Build assistant message from accumulated CompletionResult[]
155
+ const completionResults = result;
156
+ const textContent = completionResultsToText(completionResults);
157
+ // Start with the conversation from options or the prompt
158
+ let conversation = updateConversation(options.conversation, prompt);
159
+ // Add assistant message as EasyInputMessage
160
+ if (textContent) {
161
+ const assistantMessage = {
162
+ role: 'assistant',
163
+ content: textContent,
164
+ };
165
+ conversation = updateConversation(conversation, [assistantMessage]);
166
+ }
167
+ // Add function calls as separate items (Response API format)
168
+ if (toolUse && toolUse.length > 0) {
169
+ const functionCalls = toolUse.map(t => ({
170
+ type: 'function_call',
171
+ call_id: t.id,
172
+ name: t.tool_name,
173
+ arguments: typeof t.tool_input === 'string' ? t.tool_input : JSON.stringify(t.tool_input ?? {}),
174
+ }));
175
+ conversation = updateConversation(conversation, functionCalls);
176
+ }
177
+ // Increment turn counter
178
+ conversation = incrementConversationTurn(conversation);
179
+ // Apply stripping based on options
180
+ const currentTurn = getConversationMeta(conversation).turnNumber;
181
+ const stripOptions = {
182
+ keepForTurns: options.stripImagesAfterTurns ?? Infinity,
183
+ currentTurn,
184
+ textMaxTokens: options.stripTextMaxTokens
185
+ };
186
+ let processedConversation = stripBase64ImagesFromConversation(conversation, stripOptions);
187
+ processedConversation = truncateLargeTextInConversation(processedConversation, stripOptions);
188
+ return processedConversation;
189
+ }
190
+ createTrainingPrompt(options) {
191
+ if (options.model.includes("gpt")) {
192
+ return super.createTrainingPrompt(options);
193
+ }
194
+ else {
195
+ // babbage, davinci not yet implemented
196
+ throw new Error("Unsupported model for training: " + options.model);
197
+ }
198
+ }
199
+ async startTraining(dataset, options) {
200
+ const url = await dataset.getURL();
201
+ const file = await this.service.files.create({
202
+ file: await fetch(url),
203
+ purpose: "fine-tune",
204
+ });
205
+ const job = await this.service.fineTuning.jobs.create({
206
+ training_file: file.id,
207
+ model: options.model,
208
+ hyperparameters: options.params
209
+ });
210
+ return jobInfo(job);
211
+ }
212
+ async cancelTraining(jobId) {
213
+ const job = await this.service.fineTuning.jobs.cancel(jobId);
214
+ return jobInfo(job);
215
+ }
216
+ async getTrainingJob(jobId) {
217
+ const job = await this.service.fineTuning.jobs.retrieve(jobId);
218
+ return jobInfo(job);
219
+ }
220
+ // ========= management API =============
221
+ async validateConnection() {
222
+ try {
223
+ await this.service.models.list();
224
+ return true;
225
+ }
226
+ catch (error) {
227
+ return false;
228
+ }
229
+ }
230
+ listTrainableModels() {
231
+ return this._listModels((m) => supportFineTunning.has(m.id));
232
+ }
233
+ async listModels() {
234
+ return this._listModels();
235
+ }
236
+ async _listModels(filter) {
237
+ let result = (await this.service.models.list()).data;
238
+ //Some of these use the completions API instead of the chat completions API.
239
+ //Others are for non-text input modalities. Therefore common to both.
240
+ const wordBlacklist = ["embed", "whisper", "transcribe", "audio", "moderation", "tts",
241
+ "realtime", "dall-e", "babbage", "davinci", "codex", "o1-pro", "computer-use", "sora"];
242
+ //OpenAI has very little information, filtering based on name.
243
+ result = result.filter((m) => {
244
+ return !wordBlacklist.some((word) => m.id.includes(word));
245
+ });
246
+ const models = filter ? result.filter(filter) : result;
247
+ const aiModels = models.map((m) => {
248
+ const modelCapability = getModelCapabilities(m.id, "openai");
249
+ let owner = m.owned_by;
250
+ if (owner == "system") {
251
+ owner = "openai";
252
+ }
253
+ return {
254
+ id: m.id,
255
+ name: m.id,
256
+ provider: this.provider,
257
+ owner: owner,
258
+ type: m.object === "model" ? ModelType.Text : ModelType.Unknown,
259
+ can_stream: true,
260
+ is_multimodal: m.id.includes("gpt-4"),
261
+ input_modalities: modelModalitiesToArray(modelCapability.input),
262
+ output_modalities: modelModalitiesToArray(modelCapability.output),
263
+ tool_support: modelCapability.tool_support,
264
+ };
265
+ }).sort((a, b) => a.id.localeCompare(b.id));
266
+ return aiModels;
267
+ }
268
+ async generateEmbeddings({ text, image, model = "text-embedding-3-small" }) {
269
+ if (image) {
270
+ throw new Error("Image embeddings not supported by OpenAI");
271
+ }
272
+ if (!text) {
273
+ throw new Error("No text provided");
274
+ }
275
+ const res = await this.service.embeddings.create({
276
+ input: text,
277
+ model: model,
278
+ });
279
+ const embeddings = res.data[0].embedding;
280
+ if (!embeddings || embeddings.length === 0) {
281
+ throw new Error("No embedding found");
282
+ }
283
+ return { values: embeddings, model };
284
+ }
285
+ }
286
+ function jobInfo(job) {
287
+ //validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`.
288
+ const jobStatus = job.status;
289
+ let status = TrainingJobStatus.running;
290
+ let details;
291
+ if (jobStatus === 'succeeded') {
292
+ status = TrainingJobStatus.succeeded;
293
+ }
294
+ else if (jobStatus === 'failed') {
295
+ status = TrainingJobStatus.failed;
296
+ details = job.error ? `${job.error.code} - ${job.error.message} ${job.error.param ? " [" + job.error.param + "]" : ""}` : "error";
297
+ }
298
+ else if (jobStatus === 'cancelled') {
299
+ status = TrainingJobStatus.cancelled;
300
+ }
301
+ else {
302
+ status = TrainingJobStatus.running;
303
+ details = jobStatus;
304
+ }
305
+ return {
306
+ id: job.id,
307
+ model: job.fine_tuned_model || undefined,
308
+ status,
309
+ details
310
+ };
311
+ }
312
+ function mapUsage(usage) {
313
+ if (!usage) {
314
+ return undefined;
315
+ }
316
+ return {
317
+ prompt: usage.input_tokens,
318
+ result: usage.output_tokens,
319
+ total: usage.total_tokens,
320
+ };
321
+ }
322
+ function completionResultsToText(completionResults) {
323
+ if (!completionResults) {
324
+ return '';
325
+ }
326
+ return completionResults
327
+ .map(r => {
328
+ switch (r.type) {
329
+ case 'text':
330
+ return r.value;
331
+ case 'json':
332
+ return typeof r.value === 'string' ? r.value : JSON.stringify(r.value);
333
+ case 'image':
334
+ // Skip images in conversation - they're in the result
335
+ return '';
336
+ default:
337
+ return String(r.value || '');
338
+ }
339
+ })
340
+ .join('');
341
+ }
342
+ function createAssistantMessageFromCompletion(completion) {
343
+ const textContent = completionResultsToText(completion.result);
344
+ const result = [];
345
+ // Add assistant text message if present
346
+ if (textContent) {
347
+ const assistantMessage = {
348
+ role: 'assistant',
349
+ content: textContent,
350
+ };
351
+ result.push(assistantMessage);
352
+ }
353
+ // Add function calls as separate items (Response API format)
354
+ if (completion.tool_use && completion.tool_use.length > 0) {
355
+ for (const t of completion.tool_use) {
356
+ const functionCall = {
357
+ type: 'function_call',
358
+ call_id: t.id,
359
+ name: t.tool_name,
360
+ arguments: typeof t.tool_input === 'string'
361
+ ? t.tool_input
362
+ : JSON.stringify(t.tool_input ?? {}),
363
+ };
364
+ result.push(functionCall);
365
+ }
366
+ }
367
+ return result;
368
+ }
369
+ function mapResponseStream(stream) {
370
+ const toolCallMetadata = new Map();
371
+ return {
372
+ async *[Symbol.asyncIterator]() {
373
+ for await (const event of stream) {
374
+ if (event.type === 'response.output_item.added' && event.item.type === 'function_call') {
375
+ const syntheticId = `tool_${event.output_index}`;
376
+ const actualId = event.item.id ?? event.item.call_id;
377
+ if (actualId) {
378
+ toolCallMetadata.set(actualId, { syntheticId, name: event.item.name });
379
+ }
380
+ const toolUse = {
381
+ id: syntheticId,
382
+ _actual_id: actualId,
383
+ tool_name: event.item.name,
384
+ tool_input: '',
385
+ };
386
+ yield {
387
+ result: [],
388
+ tool_use: [toolUse],
389
+ };
390
+ }
391
+ else if (event.type === 'response.function_call_arguments.delta') {
392
+ const metadata = toolCallMetadata.get(event.item_id);
393
+ const syntheticId = metadata?.syntheticId ?? `tool_${event.output_index}`;
394
+ const toolUse = {
395
+ id: syntheticId,
396
+ _actual_id: event.item_id,
397
+ tool_name: metadata?.name ?? '',
398
+ tool_input: event.delta,
399
+ };
400
+ yield {
401
+ result: [],
402
+ tool_use: [toolUse],
403
+ };
404
+ }
405
+ // Note: We don't emit response.function_call_arguments.done because the arguments were already
406
+ // streamed via delta events. Emitting it again would duplicate the tool_input content.
407
+ // We only update the metadata to ensure the tool name is captured.
408
+ else if (event.type === 'response.function_call_arguments.done') {
409
+ // Just update metadata, don't yield (arguments already accumulated from delta events)
410
+ const metadata = toolCallMetadata.get(event.item_id);
411
+ const syntheticId = metadata?.syntheticId ?? `tool_${event.output_index}`;
412
+ const tool_name = metadata?.name ?? event.name ?? '';
413
+ if (event.item_id) {
414
+ toolCallMetadata.set(event.item_id, { syntheticId, name: tool_name });
415
+ }
416
+ }
417
+ else if (event.type === 'response.output_text.delta') {
418
+ yield {
419
+ result: textToCompletionResult(event.delta),
420
+ };
421
+ }
422
+ // Note: We don't emit response.output_text.done because the text was already
423
+ // streamed via delta events. Emitting it again would duplicate the content.
424
+ else if (event.type === 'response.completed' || event.type === 'response.incomplete' || event.type === 'response.failed') {
425
+ const finalTools = collectTools(event.response.output);
426
+ yield {
427
+ result: [],
428
+ finish_reason: responseFinishReason(event.response, finalTools),
429
+ token_usage: mapUsage(event.response.usage),
430
+ };
431
+ }
432
+ }
433
+ }
434
+ };
435
+ }
436
+ function insert_image_detail(items, detail_level) {
437
+ if (detail_level === "auto" || detail_level === "low" || detail_level === "high") {
438
+ for (const item of items) {
439
+ // Check if it's an EasyInputMessage or Message with content array
440
+ if ('role' in item && 'content' in item && item.role !== 'assistant') {
441
+ const content = item.content;
442
+ if (Array.isArray(content)) {
443
+ for (const part of content) {
444
+ if (typeof part === 'object' && part.type === 'input_image') {
445
+ part.detail = detail_level;
446
+ }
447
+ }
448
+ }
449
+ }
450
+ }
451
+ }
452
+ return items;
453
+ }
454
+ function convertRoles(items, model) {
455
+ //New openai models use developer role instead of system
456
+ if (model.includes("o1") || model.includes("o3")) {
457
+ if (model.includes("o1-mini") || model.includes("o1-preview")) {
458
+ //o1-mini and o1-preview support neither system nor developer
459
+ for (const item of items) {
460
+ if ('role' in item && item.role === 'system') {
461
+ item.role = 'user';
462
+ }
463
+ }
464
+ }
465
+ else {
466
+ //Models newer than o1 use developer role
467
+ for (const item of items) {
468
+ if ('role' in item && item.role === 'system') {
469
+ item.role = 'developer';
470
+ }
471
+ }
472
+ }
473
+ }
474
+ return items;
475
+ }
476
+ //Structured output support is typically aligned with tool use support
477
+ //Not true for realtime models, which do not support structured output, but do support tool use.
478
+ function supportsSchema(model) {
479
+ const realtimeModel = model.includes("realtime");
480
+ if (realtimeModel) {
481
+ return false;
482
+ }
483
+ return supportsToolUse(model, "openai");
484
+ }
485
+ function getToolDefinitions(tools) {
486
+ return tools ? tools.map(getToolDefinition) : undefined;
487
+ }
488
+ function getToolDefinition(toolDef) {
489
+ let parsedSchema = undefined;
490
+ let strictMode = false;
491
+ if (toolDef.input_schema) {
492
+ try {
493
+ parsedSchema = openAISchemaFormat(toolDef.input_schema);
494
+ strictMode = true;
495
+ }
496
+ catch (e) {
497
+ parsedSchema = limitedSchemaFormat(toolDef.input_schema);
498
+ strictMode = false;
499
+ }
500
+ }
501
+ return {
502
+ type: "function",
503
+ name: toolDef.name,
504
+ description: toolDef.description,
505
+ parameters: parsedSchema ?? null,
506
+ strict: strictMode,
507
+ };
508
+ }
509
+ function updateConversation(conversation, items) {
510
+ if (!items) {
511
+ // Unwrap array if wrapped, otherwise treat as array
512
+ const unwrapped = unwrapConversationArray(conversation);
513
+ return unwrapped ?? (conversation || []);
514
+ }
515
+ if (!conversation) {
516
+ return items;
517
+ }
518
+ // Unwrap array if wrapped, otherwise treat as array
519
+ const unwrapped = unwrapConversationArray(conversation);
520
+ const convArray = unwrapped ?? conversation;
521
+ return [...convArray, ...items];
522
+ }
523
+ export function collectTools(output) {
524
+ if (!output) {
525
+ return undefined;
526
+ }
527
+ const tools = [];
528
+ for (const item of output) {
529
+ if (item.type === 'function_call') {
530
+ const id = item.call_id || item.id;
531
+ if (!id) {
532
+ continue;
533
+ }
534
+ tools.push({
535
+ id,
536
+ tool_name: item.name ?? '',
537
+ tool_input: safeJsonParse(item.arguments),
538
+ });
539
+ }
540
+ }
541
+ return tools.length > 0 ? tools : undefined;
542
+ }
543
+ //For strict mode false
544
+ function limitedSchemaFormat(schema) {
545
+ const formattedSchema = { ...schema };
546
+ // Defaults not supported
547
+ delete formattedSchema.default;
548
+ // OpenAI requires type field even in non-strict mode
549
+ // If no type is specified, default to 'object' for properties with format/editor hints,
550
+ // otherwise 'string' as a safe fallback
551
+ if (!formattedSchema.type && formattedSchema.description) {
552
+ // Properties with format: "document" or editor hints are typically objects
553
+ if (formattedSchema.format === 'document' || formattedSchema.editor) {
554
+ formattedSchema.type = 'object';
555
+ }
556
+ else {
557
+ formattedSchema.type = 'string';
558
+ }
559
+ }
560
+ if (formattedSchema?.properties) {
561
+ // Process each property recursively
562
+ for (const propName of Object.keys(formattedSchema.properties)) {
563
+ const property = formattedSchema.properties[propName];
564
+ // Recursively process properties
565
+ formattedSchema.properties[propName] = limitedSchemaFormat(property);
566
+ // Process arrays with items of type object
567
+ if (property?.type === 'array' && property.items && property.items?.type === 'object') {
568
+ formattedSchema.properties[propName] = {
569
+ ...property,
570
+ items: limitedSchemaFormat(property.items),
571
+ };
572
+ }
573
+ }
574
+ }
575
+ return formattedSchema;
576
+ }
577
+ //For strict mode true
578
+ function openAISchemaFormat(schema, nesting = 0) {
579
+ if (nesting > 5) {
580
+ throw new Error("OpenAI schema nesting too deep");
581
+ }
582
+ const formattedSchema = { ...schema };
583
+ // Defaults not supported
584
+ delete formattedSchema.default;
585
+ // Additional properties not supported, required to be set.
586
+ if (formattedSchema?.type === "object") {
587
+ formattedSchema.additionalProperties = false;
588
+ }
589
+ if (formattedSchema?.properties) {
590
+ // Set all properties as required
591
+ formattedSchema.required = Object.keys(formattedSchema.properties);
592
+ // Process each property recursively
593
+ for (const propName of Object.keys(formattedSchema.properties)) {
594
+ const property = formattedSchema.properties[propName];
595
+ // OpenAI strict mode requires all properties to have a type
596
+ if (!property?.type) {
597
+ throw new Error(`Property '${propName}' is missing required 'type' field for OpenAI strict mode`);
598
+ }
599
+ // Recursively process properties
600
+ formattedSchema.properties[propName] = openAISchemaFormat(property, nesting + 1);
601
+ // Process arrays with items of type object
602
+ if (property?.type === 'array' && property.items && property.items?.type === 'object') {
603
+ formattedSchema.properties[propName] = {
604
+ ...property,
605
+ items: openAISchemaFormat(property.items, nesting + 1),
606
+ };
607
+ }
608
+ }
609
+ }
610
+ if (formattedSchema?.type === 'object' && (!formattedSchema?.properties || Object.keys(formattedSchema?.properties ?? {}).length == 0)) {
611
+ //If no properties are defined, then additionalProperties: true was set or the object would be empty.
612
+ //OpenAI does not support this on structured output/ strict mode.
613
+ throw new Error("OpenAI does not support empty objects or objects with additionalProperties set to true");
614
+ }
615
+ return formattedSchema;
616
+ }
617
+ function extractTextFromResponse(response) {
618
+ if (response.output_text) {
619
+ return response.output_text;
620
+ }
621
+ const collected = [];
622
+ for (const item of response.output ?? []) {
623
+ if (item.type === 'message') {
624
+ const text = item.content
625
+ .map(part => part.type === 'output_text' ? part.text : '')
626
+ .join('');
627
+ if (text) {
628
+ collected.push(text);
629
+ }
630
+ }
631
+ }
632
+ return collected.join("\n");
633
+ }
634
+ function responseFinishReason(response, tools) {
635
+ if (tools && tools.length > 0) {
636
+ return "tool_use";
637
+ }
638
+ if (response.status === 'incomplete') {
639
+ if (response.incomplete_details?.reason === 'max_output_tokens') {
640
+ return 'length';
641
+ }
642
+ return response.incomplete_details?.reason ?? 'incomplete';
643
+ }
644
+ if (response.status && response.status !== 'completed') {
645
+ return response.status;
646
+ }
647
+ return 'stop';
648
+ }
649
+ function safeJsonParse(value) {
650
+ if (typeof value !== 'string') {
651
+ return value;
652
+ }
653
+ try {
654
+ return JSON.parse(value);
655
+ }
656
+ catch {
657
+ return value;
658
+ }
659
+ }
660
+ //# sourceMappingURL=index.js.map