@midscene/core 0.30.5 → 1.0.1-beta-20251021060907.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 (87) hide show
  1. package/dist/es/agent/agent.mjs +41 -33
  2. package/dist/es/agent/agent.mjs.map +1 -1
  3. package/dist/es/agent/execution-session.mjs +41 -0
  4. package/dist/es/agent/execution-session.mjs.map +1 -0
  5. package/dist/es/agent/task-builder.mjs +303 -0
  6. package/dist/es/agent/task-builder.mjs.map +1 -0
  7. package/dist/es/agent/tasks.mjs +68 -391
  8. package/dist/es/agent/tasks.mjs.map +1 -1
  9. package/dist/es/agent/ui-utils.mjs.map +1 -1
  10. package/dist/es/agent/utils.mjs +6 -6
  11. package/dist/es/agent/utils.mjs.map +1 -1
  12. package/dist/es/ai-model/common.mjs +1 -15
  13. package/dist/es/ai-model/common.mjs.map +1 -1
  14. package/dist/es/ai-model/inspect.mjs +2 -3
  15. package/dist/es/ai-model/inspect.mjs.map +1 -1
  16. package/dist/es/ai-model/llm-planning.mjs +6 -24
  17. package/dist/es/ai-model/llm-planning.mjs.map +1 -1
  18. package/dist/es/ai-model/prompt/llm-locator.mjs +3 -204
  19. package/dist/es/ai-model/prompt/llm-locator.mjs.map +1 -1
  20. package/dist/es/ai-model/service-caller/index.mjs +101 -231
  21. package/dist/es/ai-model/service-caller/index.mjs.map +1 -1
  22. package/dist/es/index.mjs +3 -2
  23. package/dist/es/index.mjs.map +1 -1
  24. package/dist/es/insight/index.mjs +18 -19
  25. package/dist/es/insight/index.mjs.map +1 -1
  26. package/dist/es/insight/utils.mjs +3 -3
  27. package/dist/es/insight/utils.mjs.map +1 -1
  28. package/dist/es/report.mjs.map +1 -1
  29. package/dist/es/{ai-model/action-executor.mjs → task-runner.mjs} +69 -10
  30. package/dist/es/task-runner.mjs.map +1 -0
  31. package/dist/es/types.mjs +18 -1
  32. package/dist/es/types.mjs.map +1 -1
  33. package/dist/es/utils.mjs +2 -2
  34. package/dist/es/yaml/player.mjs +18 -14
  35. package/dist/es/yaml/player.mjs.map +1 -1
  36. package/dist/lib/agent/agent.js +41 -33
  37. package/dist/lib/agent/agent.js.map +1 -1
  38. package/dist/lib/agent/execution-session.js +75 -0
  39. package/dist/lib/agent/execution-session.js.map +1 -0
  40. package/dist/lib/agent/task-builder.js +340 -0
  41. package/dist/lib/agent/task-builder.js.map +1 -0
  42. package/dist/lib/agent/tasks.js +68 -391
  43. package/dist/lib/agent/tasks.js.map +1 -1
  44. package/dist/lib/agent/ui-utils.js.map +1 -1
  45. package/dist/lib/agent/utils.js +6 -6
  46. package/dist/lib/agent/utils.js.map +1 -1
  47. package/dist/lib/ai-model/common.js +2 -19
  48. package/dist/lib/ai-model/common.js.map +1 -1
  49. package/dist/lib/ai-model/inspect.js +1 -2
  50. package/dist/lib/ai-model/inspect.js.map +1 -1
  51. package/dist/lib/ai-model/llm-planning.js +5 -23
  52. package/dist/lib/ai-model/llm-planning.js.map +1 -1
  53. package/dist/lib/ai-model/prompt/llm-locator.js +2 -206
  54. package/dist/lib/ai-model/prompt/llm-locator.js.map +1 -1
  55. package/dist/lib/ai-model/service-caller/index.js +236 -384
  56. package/dist/lib/ai-model/service-caller/index.js.map +1 -1
  57. package/dist/lib/index.js +9 -5
  58. package/dist/lib/index.js.map +1 -1
  59. package/dist/lib/insight/index.js +17 -18
  60. package/dist/lib/insight/index.js.map +1 -1
  61. package/dist/lib/insight/utils.js +5 -5
  62. package/dist/lib/insight/utils.js.map +1 -1
  63. package/dist/lib/report.js.map +1 -1
  64. package/dist/lib/{ai-model/action-executor.js → task-runner.js} +71 -12
  65. package/dist/lib/task-runner.js.map +1 -0
  66. package/dist/lib/types.js +22 -1
  67. package/dist/lib/types.js.map +1 -1
  68. package/dist/lib/utils.js +2 -2
  69. package/dist/lib/yaml/player.js +18 -14
  70. package/dist/lib/yaml/player.js.map +1 -1
  71. package/dist/types/agent/agent.d.ts +16 -0
  72. package/dist/types/agent/execution-session.d.ts +27 -0
  73. package/dist/types/agent/task-builder.d.ts +24 -0
  74. package/dist/types/agent/tasks.d.ts +8 -11
  75. package/dist/types/agent/ui-utils.d.ts +2 -2
  76. package/dist/types/agent/utils.d.ts +5 -2
  77. package/dist/types/ai-model/common.d.ts +0 -1
  78. package/dist/types/ai-model/prompt/llm-locator.d.ts +0 -2
  79. package/dist/types/index.d.ts +4 -3
  80. package/dist/types/insight/index.d.ts +5 -10
  81. package/dist/types/insight/utils.d.ts +2 -2
  82. package/dist/types/{ai-model/action-executor.d.ts → task-runner.d.ts} +14 -3
  83. package/dist/types/types.d.ts +47 -4
  84. package/dist/types/yaml.d.ts +3 -1
  85. package/package.json +4 -7
  86. package/dist/es/ai-model/action-executor.mjs.map +0 -1
  87. package/dist/lib/ai-model/action-executor.js.map +0 -1
@@ -1,21 +1,5 @@
1
1
  "use strict";
2
- var __webpack_modules__ = {
3
- "langsmith/wrappers": function(module) {
4
- module.exports = import("langsmith/wrappers").then(function(module) {
5
- return module;
6
- });
7
- }
8
- };
9
- var __webpack_module_cache__ = {};
10
- function __webpack_require__(moduleId) {
11
- var cachedModule = __webpack_module_cache__[moduleId];
12
- if (void 0 !== cachedModule) return cachedModule.exports;
13
- var module = __webpack_module_cache__[moduleId] = {
14
- exports: {}
15
- };
16
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
17
- return module.exports;
18
- }
2
+ var __webpack_require__ = {};
19
3
  (()=>{
20
4
  __webpack_require__.n = (module)=>{
21
5
  var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
@@ -47,36 +31,43 @@ function __webpack_require__(moduleId) {
47
31
  };
48
32
  })();
49
33
  var __webpack_exports__ = {};
50
- (()=>{
51
- __webpack_require__.r(__webpack_exports__);
52
- __webpack_require__.d(__webpack_exports__, {
53
- extractJSONFromCodeBlock: ()=>extractJSONFromCodeBlock,
54
- callAIWithStringResponse: ()=>callAIWithStringResponse,
55
- preprocessDoubaoBboxJson: ()=>preprocessDoubaoBboxJson,
56
- callAIWithObjectResponse: ()=>callAIWithObjectResponse,
57
- getResponseFormat: ()=>getResponseFormat,
58
- safeParseJson: ()=>safeParseJson,
59
- callAI: ()=>callAI
34
+ __webpack_require__.r(__webpack_exports__);
35
+ __webpack_require__.d(__webpack_exports__, {
36
+ extractJSONFromCodeBlock: ()=>extractJSONFromCodeBlock,
37
+ callAIWithStringResponse: ()=>callAIWithStringResponse,
38
+ preprocessDoubaoBboxJson: ()=>preprocessDoubaoBboxJson,
39
+ callAIWithObjectResponse: ()=>callAIWithObjectResponse,
40
+ getResponseFormat: ()=>getResponseFormat,
41
+ safeParseJson: ()=>safeParseJson,
42
+ callAI: ()=>callAI
43
+ });
44
+ const external_types_js_namespaceObject = require("../../types.js");
45
+ const env_namespaceObject = require("@midscene/shared/env");
46
+ const logger_namespaceObject = require("@midscene/shared/logger");
47
+ const utils_namespaceObject = require("@midscene/shared/utils");
48
+ const external_https_proxy_agent_namespaceObject = require("https-proxy-agent");
49
+ const external_jsonrepair_namespaceObject = require("jsonrepair");
50
+ const external_openai_namespaceObject = require("openai");
51
+ var external_openai_default = /*#__PURE__*/ __webpack_require__.n(external_openai_namespaceObject);
52
+ const external_socks_proxy_agent_namespaceObject = require("socks-proxy-agent");
53
+ const external_common_js_namespaceObject = require("../common.js");
54
+ const assertion_js_namespaceObject = require("../prompt/assertion.js");
55
+ const llm_planning_js_namespaceObject = require("../prompt/llm-planning.js");
56
+ async function createChatClient({ AIActionTypeValue, modelConfig }) {
57
+ const { socksProxy, httpProxy, modelName, openaiBaseURL, openaiApiKey, openaiExtraConfig, modelDescription, uiTarsModelVersion: uiTarsVersion, vlMode, createOpenAIClient } = modelConfig;
58
+ let openai;
59
+ if (createOpenAIClient) openai = createOpenAIClient({
60
+ modelName,
61
+ openaiApiKey,
62
+ openaiBaseURL,
63
+ socksProxy,
64
+ httpProxy,
65
+ openaiExtraConfig,
66
+ vlMode,
67
+ intent: modelConfig.intent,
68
+ modelDescription
60
69
  });
61
- const external_types_js_namespaceObject = require("../../types.js");
62
- const sdk_namespaceObject = require("@anthropic-ai/sdk");
63
- const identity_namespaceObject = require("@azure/identity");
64
- const env_namespaceObject = require("@midscene/shared/env");
65
- const img_namespaceObject = require("@midscene/shared/img");
66
- const logger_namespaceObject = require("@midscene/shared/logger");
67
- const utils_namespaceObject = require("@midscene/shared/utils");
68
- const external_https_proxy_agent_namespaceObject = require("https-proxy-agent");
69
- const external_jsonrepair_namespaceObject = require("jsonrepair");
70
- const external_openai_namespaceObject = require("openai");
71
- var external_openai_default = /*#__PURE__*/ __webpack_require__.n(external_openai_namespaceObject);
72
- const external_socks_proxy_agent_namespaceObject = require("socks-proxy-agent");
73
- const external_common_js_namespaceObject = require("../common.js");
74
- const assertion_js_namespaceObject = require("../prompt/assertion.js");
75
- const llm_locator_js_namespaceObject = require("../prompt/llm-locator.js");
76
- const llm_planning_js_namespaceObject = require("../prompt/llm-planning.js");
77
- async function createChatClient({ AIActionTypeValue, modelConfig }) {
78
- const { socksProxy, httpProxy, modelName, openaiBaseURL, openaiApiKey, openaiExtraConfig, openaiUseAzureDeprecated, useAzureOpenai, azureOpenaiScope, azureOpenaiKey, azureOpenaiEndpoint, azureOpenaiApiVersion, azureOpenaiDeployment, azureExtraConfig, useAnthropicSdk, anthropicApiKey, modelDescription, uiTarsModelVersion: uiTarsVersion, vlMode } = modelConfig;
79
- let openai;
70
+ else {
80
71
  let proxyAgent;
81
72
  const debugProxy = (0, logger_namespaceObject.getDebug)('ai:call:proxy');
82
73
  if (httpProxy) {
@@ -86,365 +77,226 @@ var __webpack_exports__ = {};
86
77
  debugProxy('using socks proxy', socksProxy);
87
78
  proxyAgent = new external_socks_proxy_agent_namespaceObject.SocksProxyAgent(socksProxy);
88
79
  }
89
- if (openaiUseAzureDeprecated) openai = new external_openai_namespaceObject.AzureOpenAI({
80
+ openai = new (external_openai_default())({
90
81
  baseURL: openaiBaseURL,
91
82
  apiKey: openaiApiKey,
92
- httpAgent: proxyAgent,
83
+ ...proxyAgent ? {
84
+ httpAgent: proxyAgent
85
+ } : {},
93
86
  ...openaiExtraConfig,
94
87
  dangerouslyAllowBrowser: true
95
88
  });
96
- else if (useAzureOpenai) {
97
- let tokenProvider;
98
- if (azureOpenaiScope) {
99
- (0, utils_namespaceObject.assert)(!utils_namespaceObject.ifInBrowser, 'Azure OpenAI is not supported in browser with Midscene.');
100
- const credential = new identity_namespaceObject.DefaultAzureCredential();
101
- tokenProvider = (0, identity_namespaceObject.getBearerTokenProvider)(credential, azureOpenaiScope);
102
- openai = new external_openai_namespaceObject.AzureOpenAI({
103
- azureADTokenProvider: tokenProvider,
104
- endpoint: azureOpenaiEndpoint,
105
- apiVersion: azureOpenaiApiVersion,
106
- deployment: azureOpenaiDeployment,
107
- ...openaiExtraConfig,
108
- ...azureExtraConfig
109
- });
110
- } else openai = new external_openai_namespaceObject.AzureOpenAI({
111
- apiKey: azureOpenaiKey,
112
- endpoint: azureOpenaiEndpoint,
113
- apiVersion: azureOpenaiApiVersion,
114
- deployment: azureOpenaiDeployment,
115
- dangerouslyAllowBrowser: true,
116
- ...openaiExtraConfig,
117
- ...azureExtraConfig
118
- });
119
- } else if (!useAnthropicSdk) openai = new (external_openai_default())({
120
- baseURL: openaiBaseURL,
121
- apiKey: openaiApiKey,
122
- httpAgent: proxyAgent,
123
- ...openaiExtraConfig,
124
- defaultHeaders: {
125
- ...(null == openaiExtraConfig ? void 0 : openaiExtraConfig.defaultHeaders) || {},
126
- [env_namespaceObject.MIDSCENE_API_TYPE]: AIActionTypeValue.toString()
127
- },
128
- dangerouslyAllowBrowser: true
129
- });
130
- if (openai && env_namespaceObject.globalConfigManager.getEnvConfigInBoolean(env_namespaceObject.MIDSCENE_LANGSMITH_DEBUG)) {
131
- if (utils_namespaceObject.ifInBrowser) throw new Error('langsmith is not supported in browser');
132
- console.log('DEBUGGING MODE: langsmith wrapper enabled');
133
- const { wrapOpenAI } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "langsmith/wrappers"));
134
- openai = wrapOpenAI(openai);
135
- }
136
- if (void 0 !== openai) return {
137
- completion: openai.chat.completions,
138
- style: 'openai',
139
- modelName,
140
- modelDescription,
141
- uiTarsVersion,
142
- vlMode
143
- };
144
- if (useAnthropicSdk) openai = new sdk_namespaceObject.Anthropic({
145
- apiKey: anthropicApiKey,
146
- httpAgent: proxyAgent,
147
- dangerouslyAllowBrowser: true
148
- });
149
- if (void 0 !== openai && openai.messages) return {
150
- completion: openai.messages,
151
- style: 'anthropic',
152
- modelName,
153
- modelDescription,
154
- uiTarsVersion,
155
- vlMode
156
- };
157
- throw new Error('Openai SDK or Anthropic SDK is not initialized');
158
89
  }
159
- async function callAI(messages, AIActionTypeValue, modelConfig, options) {
160
- const { completion, style, modelName, modelDescription, uiTarsVersion, vlMode } = await createChatClient({
161
- AIActionTypeValue,
162
- modelConfig
163
- });
164
- const responseFormat = getResponseFormat(modelName, AIActionTypeValue);
165
- const maxTokens = env_namespaceObject.globalConfigManager.getEnvConfigValue(env_namespaceObject.OPENAI_MAX_TOKENS);
166
- const debugCall = (0, logger_namespaceObject.getDebug)('ai:call');
167
- const debugProfileStats = (0, logger_namespaceObject.getDebug)('ai:profile:stats');
168
- const debugProfileDetail = (0, logger_namespaceObject.getDebug)('ai:profile:detail');
169
- const startTime = Date.now();
170
- const isStreaming = (null == options ? void 0 : options.stream) && (null == options ? void 0 : options.onChunk);
171
- let content;
172
- let accumulated = '';
173
- let usage;
174
- let timeCost;
175
- const commonConfig = {
176
- temperature: 'vlm-ui-tars' === vlMode ? 0.0 : 0.1,
177
- stream: !!isStreaming,
178
- max_tokens: 'number' == typeof maxTokens ? maxTokens : Number.parseInt(maxTokens || '2048', 10),
179
- ...'qwen-vl' === vlMode || 'qwen3-vl' === vlMode ? {
180
- vl_high_resolution_images: true
181
- } : {}
182
- };
183
- try {
184
- if ('openai' === style) {
185
- debugCall(`sending ${isStreaming ? 'streaming ' : ''}request to ${modelName}`);
186
- if (isStreaming) {
187
- const stream = await completion.create({
188
- model: modelName,
189
- messages,
190
- response_format: responseFormat,
191
- ...commonConfig
192
- }, {
193
- stream: true
194
- });
195
- for await (const chunk of stream){
196
- var _chunk_choices__delta, _chunk_choices_, _chunk_choices, _chunk_choices__delta1, _chunk_choices_1, _chunk_choices1, _chunk_choices_2, _chunk_choices2;
197
- const content = (null == (_chunk_choices = chunk.choices) ? void 0 : null == (_chunk_choices_ = _chunk_choices[0]) ? void 0 : null == (_chunk_choices__delta = _chunk_choices_.delta) ? void 0 : _chunk_choices__delta.content) || '';
198
- const reasoning_content = (null == (_chunk_choices1 = chunk.choices) ? void 0 : null == (_chunk_choices_1 = _chunk_choices1[0]) ? void 0 : null == (_chunk_choices__delta1 = _chunk_choices_1.delta) ? void 0 : _chunk_choices__delta1.reasoning_content) || '';
199
- if (chunk.usage) usage = chunk.usage;
200
- if (content || reasoning_content) {
201
- accumulated += content;
202
- const chunkData = {
203
- content,
204
- reasoning_content,
205
- accumulated,
206
- isComplete: false,
207
- usage: void 0
208
- };
209
- options.onChunk(chunkData);
210
- }
211
- if (null == (_chunk_choices2 = chunk.choices) ? void 0 : null == (_chunk_choices_2 = _chunk_choices2[0]) ? void 0 : _chunk_choices_2.finish_reason) {
212
- timeCost = Date.now() - startTime;
213
- if (!usage) {
214
- const estimatedTokens = Math.max(1, Math.floor(accumulated.length / 4));
215
- usage = {
216
- prompt_tokens: estimatedTokens,
217
- completion_tokens: estimatedTokens,
218
- total_tokens: 2 * estimatedTokens
219
- };
220
- }
221
- const finalChunk = {
222
- content: '',
223
- accumulated,
224
- reasoning_content: '',
225
- isComplete: true,
226
- usage: {
227
- prompt_tokens: usage.prompt_tokens ?? 0,
228
- completion_tokens: usage.completion_tokens ?? 0,
229
- total_tokens: usage.total_tokens ?? 0,
230
- time_cost: timeCost ?? 0,
231
- model_name: modelName,
232
- model_description: modelDescription,
233
- intent: modelConfig.intent
234
- }
235
- };
236
- options.onChunk(finalChunk);
237
- break;
238
- }
239
- }
240
- content = accumulated;
241
- debugProfileStats(`streaming model, ${modelName}, mode, ${vlMode || 'default'}, cost-ms, ${timeCost}`);
242
- } else {
243
- var _result_usage, _result_usage1, _result_usage2;
244
- const result = await completion.create({
245
- model: modelName,
246
- messages,
247
- response_format: responseFormat,
248
- ...commonConfig
249
- });
250
- timeCost = Date.now() - startTime;
251
- debugProfileStats(`model, ${modelName}, mode, ${vlMode || 'default'}, ui-tars-version, ${uiTarsVersion}, prompt-tokens, ${(null == (_result_usage = result.usage) ? void 0 : _result_usage.prompt_tokens) || ''}, completion-tokens, ${(null == (_result_usage1 = result.usage) ? void 0 : _result_usage1.completion_tokens) || ''}, total-tokens, ${(null == (_result_usage2 = result.usage) ? void 0 : _result_usage2.total_tokens) || ''}, cost-ms, ${timeCost}, requestId, ${result._request_id || ''}`);
252
- debugProfileDetail(`model usage detail: ${JSON.stringify(result.usage)}`);
253
- (0, utils_namespaceObject.assert)(result.choices, `invalid response from LLM service: ${JSON.stringify(result)}`);
254
- content = result.choices[0].message.content;
255
- usage = result.usage;
90
+ return {
91
+ completion: openai.chat.completions,
92
+ modelName,
93
+ modelDescription,
94
+ uiTarsVersion,
95
+ vlMode
96
+ };
97
+ }
98
+ async function callAI(messages, AIActionTypeValue, modelConfig, options) {
99
+ const { completion, modelName, modelDescription, uiTarsVersion, vlMode } = await createChatClient({
100
+ AIActionTypeValue,
101
+ modelConfig
102
+ });
103
+ const responseFormat = getResponseFormat(modelName, AIActionTypeValue);
104
+ const maxTokens = env_namespaceObject.globalConfigManager.getEnvConfigValue(env_namespaceObject.OPENAI_MAX_TOKENS);
105
+ const debugCall = (0, logger_namespaceObject.getDebug)('ai:call');
106
+ const debugProfileStats = (0, logger_namespaceObject.getDebug)('ai:profile:stats');
107
+ const debugProfileDetail = (0, logger_namespaceObject.getDebug)('ai:profile:detail');
108
+ const startTime = Date.now();
109
+ const isStreaming = (null == options ? void 0 : options.stream) && (null == options ? void 0 : options.onChunk);
110
+ let content;
111
+ let accumulated = '';
112
+ let usage;
113
+ let timeCost;
114
+ const commonConfig = {
115
+ temperature: 'vlm-ui-tars' === vlMode ? 0.0 : 0.1,
116
+ stream: !!isStreaming,
117
+ max_tokens: 'number' == typeof maxTokens ? maxTokens : Number.parseInt(maxTokens || '2048', 10),
118
+ ...'qwen-vl' === vlMode ? {
119
+ vl_high_resolution_images: true
120
+ } : {}
121
+ };
122
+ try {
123
+ debugCall(`sending ${isStreaming ? 'streaming ' : ''}request to ${modelName}`);
124
+ if (isStreaming) {
125
+ const stream = await completion.create({
126
+ model: modelName,
127
+ messages,
128
+ response_format: responseFormat,
129
+ ...commonConfig
130
+ }, {
131
+ stream: true
132
+ });
133
+ for await (const chunk of stream){
134
+ var _chunk_choices__delta, _chunk_choices_, _chunk_choices, _chunk_choices__delta1, _chunk_choices_1, _chunk_choices1, _chunk_choices_2, _chunk_choices2;
135
+ const content = (null == (_chunk_choices = chunk.choices) ? void 0 : null == (_chunk_choices_ = _chunk_choices[0]) ? void 0 : null == (_chunk_choices__delta = _chunk_choices_.delta) ? void 0 : _chunk_choices__delta.content) || '';
136
+ const reasoning_content = (null == (_chunk_choices1 = chunk.choices) ? void 0 : null == (_chunk_choices_1 = _chunk_choices1[0]) ? void 0 : null == (_chunk_choices__delta1 = _chunk_choices_1.delta) ? void 0 : _chunk_choices__delta1.reasoning_content) || '';
137
+ if (chunk.usage) usage = chunk.usage;
138
+ if (content || reasoning_content) {
139
+ accumulated += content;
140
+ const chunkData = {
141
+ content,
142
+ reasoning_content,
143
+ accumulated,
144
+ isComplete: false,
145
+ usage: void 0
146
+ };
147
+ options.onChunk(chunkData);
256
148
  }
257
- debugCall(`response: ${content}`);
258
- (0, utils_namespaceObject.assert)(content, 'empty content');
259
- } else if ('anthropic' === style) {
260
- const convertImageContent = (content)=>{
261
- if ('image_url' === content.type) {
262
- const imgBase64 = content.image_url.url;
263
- (0, utils_namespaceObject.assert)(imgBase64, 'image_url is required');
264
- const { mimeType, body } = (0, img_namespaceObject.parseBase64)(content.image_url.url);
265
- return {
266
- source: {
267
- type: 'base64',
268
- media_type: mimeType,
269
- data: body
270
- },
271
- type: 'image'
149
+ if (null == (_chunk_choices2 = chunk.choices) ? void 0 : null == (_chunk_choices_2 = _chunk_choices2[0]) ? void 0 : _chunk_choices_2.finish_reason) {
150
+ timeCost = Date.now() - startTime;
151
+ if (!usage) {
152
+ const estimatedTokens = Math.max(1, Math.floor(accumulated.length / 4));
153
+ usage = {
154
+ prompt_tokens: estimatedTokens,
155
+ completion_tokens: estimatedTokens,
156
+ total_tokens: 2 * estimatedTokens
272
157
  };
273
158
  }
274
- return content;
275
- };
276
- if (isStreaming) {
277
- const stream = await completion.create({
278
- model: modelName,
279
- system: 'You are a versatile professional in software UI automation',
280
- messages: messages.map((m)=>({
281
- role: 'user',
282
- content: Array.isArray(m.content) ? m.content.map(convertImageContent) : m.content
283
- })),
284
- response_format: responseFormat,
285
- ...commonConfig
286
- });
287
- for await (const chunk of stream){
288
- var _chunk_delta;
289
- const content = (null == (_chunk_delta = chunk.delta) ? void 0 : _chunk_delta.text) || '';
290
- if (content) {
291
- accumulated += content;
292
- const chunkData = {
293
- content,
294
- accumulated,
295
- reasoning_content: '',
296
- isComplete: false,
297
- usage: void 0
298
- };
299
- options.onChunk(chunkData);
300
- }
301
- if ('message_stop' === chunk.type) {
302
- timeCost = Date.now() - startTime;
303
- const anthropicUsage = chunk.usage;
304
- const finalChunk = {
305
- content: '',
306
- accumulated,
307
- reasoning_content: '',
308
- isComplete: true,
309
- usage: anthropicUsage ? {
310
- prompt_tokens: anthropicUsage.input_tokens ?? 0,
311
- completion_tokens: anthropicUsage.output_tokens ?? 0,
312
- total_tokens: (anthropicUsage.input_tokens ?? 0) + (anthropicUsage.output_tokens ?? 0),
313
- time_cost: timeCost ?? 0,
314
- model_name: modelName,
315
- model_description: modelDescription,
316
- intent: modelConfig.intent
317
- } : void 0
318
- };
319
- options.onChunk(finalChunk);
320
- break;
159
+ const finalChunk = {
160
+ content: '',
161
+ accumulated,
162
+ reasoning_content: '',
163
+ isComplete: true,
164
+ usage: {
165
+ prompt_tokens: usage.prompt_tokens ?? 0,
166
+ completion_tokens: usage.completion_tokens ?? 0,
167
+ total_tokens: usage.total_tokens ?? 0,
168
+ time_cost: timeCost ?? 0,
169
+ model_name: modelName,
170
+ model_description: modelDescription,
171
+ intent: modelConfig.intent
321
172
  }
322
- }
323
- content = accumulated;
324
- } else {
325
- const result = await completion.create({
326
- model: modelName,
327
- system: 'You are a versatile professional in software UI automation',
328
- messages: messages.map((m)=>({
329
- role: 'user',
330
- content: Array.isArray(m.content) ? m.content.map(convertImageContent) : m.content
331
- })),
332
- response_format: responseFormat,
333
- ...commonConfig
334
- });
335
- timeCost = Date.now() - startTime;
336
- content = result.content[0].text;
337
- usage = result.usage;
173
+ };
174
+ options.onChunk(finalChunk);
175
+ break;
338
176
  }
339
- (0, utils_namespaceObject.assert)(content, 'empty content');
340
177
  }
341
- if (isStreaming && !usage) {
342
- const estimatedTokens = Math.max(1, Math.floor((content || '').length / 4));
343
- usage = {
344
- prompt_tokens: estimatedTokens,
345
- completion_tokens: estimatedTokens,
346
- total_tokens: 2 * estimatedTokens
347
- };
348
- }
349
- return {
350
- content: content || '',
351
- usage: usage ? {
352
- prompt_tokens: usage.prompt_tokens ?? 0,
353
- completion_tokens: usage.completion_tokens ?? 0,
354
- total_tokens: usage.total_tokens ?? 0,
355
- time_cost: timeCost ?? 0,
356
- model_name: modelName,
357
- model_description: modelDescription,
358
- intent: modelConfig.intent
359
- } : void 0,
360
- isStreamed: !!isStreaming
361
- };
362
- } catch (e) {
363
- console.error(' call AI error', e);
364
- const newError = new Error(`failed to call ${isStreaming ? 'streaming ' : ''}AI model service: ${e.message}. Trouble shooting: https://midscenejs.com/model-provider.html`, {
365
- cause: e
178
+ content = accumulated;
179
+ debugProfileStats(`streaming model, ${modelName}, mode, ${vlMode || 'default'}, cost-ms, ${timeCost}`);
180
+ } else {
181
+ var _result_usage, _result_usage1, _result_usage2;
182
+ const result = await completion.create({
183
+ model: modelName,
184
+ messages,
185
+ response_format: responseFormat,
186
+ ...commonConfig
366
187
  });
367
- throw newError;
188
+ timeCost = Date.now() - startTime;
189
+ debugProfileStats(`model, ${modelName}, mode, ${vlMode || 'default'}, ui-tars-version, ${uiTarsVersion}, prompt-tokens, ${(null == (_result_usage = result.usage) ? void 0 : _result_usage.prompt_tokens) || ''}, completion-tokens, ${(null == (_result_usage1 = result.usage) ? void 0 : _result_usage1.completion_tokens) || ''}, total-tokens, ${(null == (_result_usage2 = result.usage) ? void 0 : _result_usage2.total_tokens) || ''}, cost-ms, ${timeCost}, requestId, ${result._request_id || ''}`);
190
+ debugProfileDetail(`model usage detail: ${JSON.stringify(result.usage)}`);
191
+ (0, utils_namespaceObject.assert)(result.choices, `invalid response from LLM service: ${JSON.stringify(result)}`);
192
+ content = result.choices[0].message.content;
193
+ usage = result.usage;
368
194
  }
369
- }
370
- const getResponseFormat = (modelName, AIActionTypeValue)=>{
371
- let responseFormat;
372
- if (modelName.includes('gpt-4')) switch(AIActionTypeValue){
373
- case external_common_js_namespaceObject.AIActionType.ASSERT:
374
- responseFormat = assertion_js_namespaceObject.assertSchema;
375
- break;
376
- case external_common_js_namespaceObject.AIActionType.INSPECT_ELEMENT:
377
- responseFormat = llm_locator_js_namespaceObject.locatorSchema;
378
- break;
379
- case external_common_js_namespaceObject.AIActionType.PLAN:
380
- responseFormat = llm_planning_js_namespaceObject.planSchema;
381
- break;
382
- case external_common_js_namespaceObject.AIActionType.EXTRACT_DATA:
383
- case external_common_js_namespaceObject.AIActionType.DESCRIBE_ELEMENT:
384
- responseFormat = {
385
- type: external_types_js_namespaceObject.AIResponseFormat.JSON
386
- };
387
- break;
388
- case external_common_js_namespaceObject.AIActionType.TEXT:
389
- responseFormat = void 0;
390
- break;
195
+ debugCall(`response: ${content}`);
196
+ (0, utils_namespaceObject.assert)(content, 'empty content');
197
+ if (isStreaming && !usage) {
198
+ const estimatedTokens = Math.max(1, Math.floor((content || '').length / 4));
199
+ usage = {
200
+ prompt_tokens: estimatedTokens,
201
+ completion_tokens: estimatedTokens,
202
+ total_tokens: 2 * estimatedTokens
203
+ };
391
204
  }
392
- if ('gpt-4o-2024-05-13' === modelName && AIActionTypeValue !== external_common_js_namespaceObject.AIActionType.TEXT) responseFormat = {
393
- type: external_types_js_namespaceObject.AIResponseFormat.JSON
394
- };
395
- return responseFormat;
396
- };
397
- async function callAIWithObjectResponse(messages, AIActionTypeValue, modelConfig) {
398
- const response = await callAI(messages, AIActionTypeValue, modelConfig);
399
- (0, utils_namespaceObject.assert)(response, 'empty response');
400
- const vlMode = modelConfig.vlMode;
401
- const jsonContent = safeParseJson(response.content, vlMode);
402
205
  return {
403
- content: jsonContent,
404
- usage: response.usage
405
- };
406
- }
407
- async function callAIWithStringResponse(msgs, AIActionTypeValue, modelConfig) {
408
- const { content, usage } = await callAI(msgs, AIActionTypeValue, modelConfig);
409
- return {
410
- content,
411
- usage
206
+ content: content || '',
207
+ usage: usage ? {
208
+ prompt_tokens: usage.prompt_tokens ?? 0,
209
+ completion_tokens: usage.completion_tokens ?? 0,
210
+ total_tokens: usage.total_tokens ?? 0,
211
+ time_cost: timeCost ?? 0,
212
+ model_name: modelName,
213
+ model_description: modelDescription,
214
+ intent: modelConfig.intent
215
+ } : void 0,
216
+ isStreamed: !!isStreaming
412
217
  };
218
+ } catch (e) {
219
+ console.error(' call AI error', e);
220
+ const newError = new Error(`failed to call ${isStreaming ? 'streaming ' : ''}AI model service: ${e.message}. Trouble shooting: https://midscenejs.com/model-provider.html`, {
221
+ cause: e
222
+ });
223
+ throw newError;
413
224
  }
414
- function extractJSONFromCodeBlock(response) {
415
- try {
416
- const jsonMatch = response.match(/^\s*(\{[\s\S]*\})\s*$/);
417
- if (jsonMatch) return jsonMatch[1];
418
- const codeBlockMatch = response.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
419
- if (codeBlockMatch) return codeBlockMatch[1];
420
- const jsonLikeMatch = response.match(/\{[\s\S]*\}/);
421
- if (jsonLikeMatch) return jsonLikeMatch[0];
422
- } catch {}
423
- return response;
225
+ }
226
+ const getResponseFormat = (modelName, AIActionTypeValue)=>{
227
+ let responseFormat;
228
+ if (modelName.includes('gpt-4')) switch(AIActionTypeValue){
229
+ case external_common_js_namespaceObject.AIActionType.ASSERT:
230
+ responseFormat = assertion_js_namespaceObject.assertSchema;
231
+ break;
232
+ case external_common_js_namespaceObject.AIActionType.PLAN:
233
+ responseFormat = llm_planning_js_namespaceObject.planSchema;
234
+ break;
235
+ case external_common_js_namespaceObject.AIActionType.EXTRACT_DATA:
236
+ case external_common_js_namespaceObject.AIActionType.DESCRIBE_ELEMENT:
237
+ responseFormat = {
238
+ type: external_types_js_namespaceObject.AIResponseFormat.JSON
239
+ };
240
+ break;
241
+ case external_common_js_namespaceObject.AIActionType.TEXT:
242
+ responseFormat = void 0;
243
+ break;
424
244
  }
425
- function preprocessDoubaoBboxJson(input) {
426
- if (input.includes('bbox')) while(/\d+\s+\d+/.test(input))input = input.replace(/(\d+)\s+(\d+)/g, '$1,$2');
427
- return input;
245
+ if ('gpt-4o-2024-05-13' === modelName && AIActionTypeValue !== external_common_js_namespaceObject.AIActionType.TEXT) responseFormat = {
246
+ type: external_types_js_namespaceObject.AIResponseFormat.JSON
247
+ };
248
+ return responseFormat;
249
+ };
250
+ async function callAIWithObjectResponse(messages, AIActionTypeValue, modelConfig) {
251
+ const response = await callAI(messages, AIActionTypeValue, modelConfig);
252
+ (0, utils_namespaceObject.assert)(response, 'empty response');
253
+ const vlMode = modelConfig.vlMode;
254
+ const jsonContent = safeParseJson(response.content, vlMode);
255
+ return {
256
+ content: jsonContent,
257
+ usage: response.usage
258
+ };
259
+ }
260
+ async function callAIWithStringResponse(msgs, AIActionTypeValue, modelConfig) {
261
+ const { content, usage } = await callAI(msgs, AIActionTypeValue, modelConfig);
262
+ return {
263
+ content,
264
+ usage
265
+ };
266
+ }
267
+ function extractJSONFromCodeBlock(response) {
268
+ try {
269
+ const jsonMatch = response.match(/^\s*(\{[\s\S]*\})\s*$/);
270
+ if (jsonMatch) return jsonMatch[1];
271
+ const codeBlockMatch = response.match(/```(?:json)?\s*(\{[\s\S]*?\})\s*```/);
272
+ if (codeBlockMatch) return codeBlockMatch[1];
273
+ const jsonLikeMatch = response.match(/\{[\s\S]*\}/);
274
+ if (jsonLikeMatch) return jsonLikeMatch[0];
275
+ } catch {}
276
+ return response;
277
+ }
278
+ function preprocessDoubaoBboxJson(input) {
279
+ if (input.includes('bbox')) while(/\d+\s+\d+/.test(input))input = input.replace(/(\d+)\s+(\d+)/g, '$1,$2');
280
+ return input;
281
+ }
282
+ function safeParseJson(input, vlMode) {
283
+ const cleanJsonString = extractJSONFromCodeBlock(input);
284
+ if (null == cleanJsonString ? void 0 : cleanJsonString.match(/\((\d+),(\d+)\)/)) {
285
+ var _cleanJsonString_match;
286
+ return null == (_cleanJsonString_match = cleanJsonString.match(/\((\d+),(\d+)\)/)) ? void 0 : _cleanJsonString_match.slice(1).map(Number);
428
287
  }
429
- function safeParseJson(input, vlMode) {
430
- const cleanJsonString = extractJSONFromCodeBlock(input);
431
- if (null == cleanJsonString ? void 0 : cleanJsonString.match(/\((\d+),(\d+)\)/)) {
432
- var _cleanJsonString_match;
433
- return null == (_cleanJsonString_match = cleanJsonString.match(/\((\d+),(\d+)\)/)) ? void 0 : _cleanJsonString_match.slice(1).map(Number);
434
- }
435
- try {
436
- return JSON.parse(cleanJsonString);
437
- } catch {}
438
- try {
439
- return JSON.parse((0, external_jsonrepair_namespaceObject.jsonrepair)(cleanJsonString));
440
- } catch (e) {}
441
- if ('doubao-vision' === vlMode || 'vlm-ui-tars' === vlMode) {
442
- const jsonString = preprocessDoubaoBboxJson(cleanJsonString);
443
- return JSON.parse((0, external_jsonrepair_namespaceObject.jsonrepair)(jsonString));
444
- }
445
- throw Error(`failed to parse json response: ${input}`);
288
+ try {
289
+ return JSON.parse(cleanJsonString);
290
+ } catch {}
291
+ try {
292
+ return JSON.parse((0, external_jsonrepair_namespaceObject.jsonrepair)(cleanJsonString));
293
+ } catch (e) {}
294
+ if ('doubao-vision' === vlMode || 'vlm-ui-tars' === vlMode) {
295
+ const jsonString = preprocessDoubaoBboxJson(cleanJsonString);
296
+ return JSON.parse((0, external_jsonrepair_namespaceObject.jsonrepair)(jsonString));
446
297
  }
447
- })();
298
+ throw Error(`failed to parse json response: ${input}`);
299
+ }
448
300
  exports.callAI = __webpack_exports__.callAI;
449
301
  exports.callAIWithObjectResponse = __webpack_exports__.callAIWithObjectResponse;
450
302
  exports.callAIWithStringResponse = __webpack_exports__.callAIWithStringResponse;