@jterrazz/intelligence 1.6.1 → 3.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.
- package/README.md +69 -165
- package/dist/index.cjs +649 -1625
- package/dist/index.d.ts +5 -12
- package/dist/index.js +5 -12
- package/dist/index.js.map +1 -1
- package/dist/middleware/__tests__/logging.middleware.test.js +390 -0
- package/dist/middleware/__tests__/logging.middleware.test.js.map +1 -0
- package/dist/middleware/logging.middleware.d.ts +21 -0
- package/dist/middleware/logging.middleware.js +296 -0
- package/dist/middleware/logging.middleware.js.map +1 -0
- package/dist/parsing/__tests__/create-schema-prompt.test.js +53 -0
- package/dist/parsing/__tests__/create-schema-prompt.test.js.map +1 -0
- package/dist/parsing/__tests__/parse-object.test.d.ts +1 -0
- package/dist/parsing/__tests__/parse-object.test.js +193 -0
- package/dist/parsing/__tests__/parse-object.test.js.map +1 -0
- package/dist/parsing/__tests__/parse-text.test.d.ts +1 -0
- package/dist/parsing/__tests__/parse-text.test.js +159 -0
- package/dist/parsing/__tests__/parse-text.test.js.map +1 -0
- package/dist/parsing/create-schema-prompt.d.ts +28 -0
- package/dist/parsing/create-schema-prompt.js +42 -0
- package/dist/parsing/create-schema-prompt.js.map +1 -0
- package/dist/parsing/parse-object.d.ts +33 -0
- package/dist/parsing/parse-object.js +360 -0
- package/dist/parsing/parse-object.js.map +1 -0
- package/dist/parsing/parse-text.d.ts +14 -0
- package/dist/parsing/parse-text.js +80 -0
- package/dist/parsing/parse-text.js.map +1 -0
- package/dist/providers/openrouter.provider.d.ts +36 -0
- package/dist/providers/openrouter.provider.js +58 -0
- package/dist/providers/openrouter.provider.js.map +1 -0
- package/package.json +15 -14
- package/dist/adapters/agents/autonomous-agent.adapter.d.ts +0 -30
- package/dist/adapters/agents/autonomous-agent.adapter.js +0 -400
- package/dist/adapters/agents/autonomous-agent.adapter.js.map +0 -1
- package/dist/adapters/agents/basic-agent.adapter.d.ts +0 -27
- package/dist/adapters/agents/basic-agent.adapter.js +0 -339
- package/dist/adapters/agents/basic-agent.adapter.js.map +0 -1
- package/dist/adapters/agents/retryable-agent.adapter.d.ts +0 -20
- package/dist/adapters/agents/retryable-agent.adapter.js +0 -263
- package/dist/adapters/agents/retryable-agent.adapter.js.map +0 -1
- package/dist/adapters/models/openrouter-model.adapter.d.ts +0 -38
- package/dist/adapters/models/openrouter-model.adapter.js +0 -89
- package/dist/adapters/models/openrouter-model.adapter.js.map +0 -1
- package/dist/adapters/prompts/__tests__/__snapshots__/presets.test.ts.snap +0 -120
- package/dist/adapters/prompts/__tests__/presets.test.js +0 -31
- package/dist/adapters/prompts/__tests__/presets.test.js.map +0 -1
- package/dist/adapters/prompts/library/categories/domain.d.ts +0 -11
- package/dist/adapters/prompts/library/categories/domain.js +0 -12
- package/dist/adapters/prompts/library/categories/domain.js.map +0 -1
- package/dist/adapters/prompts/library/categories/format.d.ts +0 -10
- package/dist/adapters/prompts/library/categories/format.js +0 -11
- package/dist/adapters/prompts/library/categories/format.js.map +0 -1
- package/dist/adapters/prompts/library/categories/foundations.d.ts +0 -12
- package/dist/adapters/prompts/library/categories/foundations.js +0 -13
- package/dist/adapters/prompts/library/categories/foundations.js.map +0 -1
- package/dist/adapters/prompts/library/categories/language.d.ts +0 -11
- package/dist/adapters/prompts/library/categories/language.js +0 -12
- package/dist/adapters/prompts/library/categories/language.js.map +0 -1
- package/dist/adapters/prompts/library/categories/persona.d.ts +0 -13
- package/dist/adapters/prompts/library/categories/persona.js +0 -14
- package/dist/adapters/prompts/library/categories/persona.js.map +0 -1
- package/dist/adapters/prompts/library/categories/response.d.ts +0 -9
- package/dist/adapters/prompts/library/categories/response.js +0 -10
- package/dist/adapters/prompts/library/categories/response.js.map +0 -1
- package/dist/adapters/prompts/library/categories/tone.d.ts +0 -9
- package/dist/adapters/prompts/library/categories/tone.js +0 -10
- package/dist/adapters/prompts/library/categories/tone.js.map +0 -1
- package/dist/adapters/prompts/library/categories/verbosity.d.ts +0 -8
- package/dist/adapters/prompts/library/categories/verbosity.js +0 -9
- package/dist/adapters/prompts/library/categories/verbosity.js.map +0 -1
- package/dist/adapters/prompts/library/index.d.ts +0 -68
- package/dist/adapters/prompts/library/index.js +0 -26
- package/dist/adapters/prompts/library/index.js.map +0 -1
- package/dist/adapters/prompts/library/presets.d.ts +0 -17
- package/dist/adapters/prompts/library/presets.js +0 -45
- package/dist/adapters/prompts/library/presets.js.map +0 -1
- package/dist/adapters/prompts/system-prompt.adapter.d.ts +0 -9
- package/dist/adapters/prompts/system-prompt.adapter.js +0 -57
- package/dist/adapters/prompts/system-prompt.adapter.js.map +0 -1
- package/dist/adapters/prompts/user-prompt.adapter.d.ts +0 -9
- package/dist/adapters/prompts/user-prompt.adapter.js +0 -57
- package/dist/adapters/prompts/user-prompt.adapter.js.map +0 -1
- package/dist/adapters/tools/safe-tool.adapter.d.ts +0 -27
- package/dist/adapters/tools/safe-tool.adapter.js +0 -283
- package/dist/adapters/tools/safe-tool.adapter.js.map +0 -1
- package/dist/adapters/utils/__tests__/ai-response-parser.test.js +0 -289
- package/dist/adapters/utils/__tests__/ai-response-parser.test.js.map +0 -1
- package/dist/adapters/utils/ai-response-parser-error.d.ts +0 -8
- package/dist/adapters/utils/ai-response-parser-error.js +0 -136
- package/dist/adapters/utils/ai-response-parser-error.js.map +0 -1
- package/dist/adapters/utils/ai-response-parser.d.ts +0 -60
- package/dist/adapters/utils/ai-response-parser.js +0 -347
- package/dist/adapters/utils/ai-response-parser.js.map +0 -1
- package/dist/ports/agent.port.d.ts +0 -17
- package/dist/ports/agent.port.js +0 -7
- package/dist/ports/agent.port.js.map +0 -1
- package/dist/ports/model.port.d.ts +0 -10
- package/dist/ports/model.port.js +0 -5
- package/dist/ports/model.port.js.map +0 -1
- package/dist/ports/prompt.port.d.ts +0 -9
- package/dist/ports/prompt.port.js +0 -5
- package/dist/ports/prompt.port.js.map +0 -1
- package/dist/ports/tool.port.d.ts +0 -11
- package/dist/ports/tool.port.js +0 -5
- package/dist/ports/tool.port.js.map +0 -1
- /package/dist/{adapters/prompts/__tests__/presets.test.d.ts → middleware/__tests__/logging.middleware.test.d.ts} +0 -0
- /package/dist/{adapters/utils/__tests__/ai-response-parser.test.d.ts → parsing/__tests__/create-schema-prompt.test.d.ts} +0 -0
package/dist/index.cjs
CHANGED
|
@@ -1,15 +1,348 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var prompts = require('@langchain/core/prompts');
|
|
4
|
-
var agents = require('langchain/agents');
|
|
5
3
|
var v4 = require('zod/v4');
|
|
6
4
|
var jsonrepair = require('jsonrepair');
|
|
7
|
-
var
|
|
8
|
-
var tools = require('langchain/tools');
|
|
5
|
+
var aiSdkProvider = require('@openrouter/ai-sdk-provider');
|
|
9
6
|
|
|
7
|
+
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
8
|
+
try {
|
|
9
|
+
var info = gen[key](arg);
|
|
10
|
+
var value = info.value;
|
|
11
|
+
} catch (error) {
|
|
12
|
+
reject(error);
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
if (info.done) {
|
|
16
|
+
resolve(value);
|
|
17
|
+
} else {
|
|
18
|
+
Promise.resolve(value).then(_next, _throw);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function _async_to_generator(fn) {
|
|
22
|
+
return function() {
|
|
23
|
+
var self = this, args = arguments;
|
|
24
|
+
return new Promise(function(resolve, reject) {
|
|
25
|
+
var gen = fn.apply(self, args);
|
|
26
|
+
function _next(value) {
|
|
27
|
+
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
|
|
28
|
+
}
|
|
29
|
+
function _throw(err) {
|
|
30
|
+
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
|
|
31
|
+
}
|
|
32
|
+
_next(undefined);
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function _define_property$2(obj, key, value) {
|
|
37
|
+
if (key in obj) {
|
|
38
|
+
Object.defineProperty(obj, key, {
|
|
39
|
+
value: value,
|
|
40
|
+
enumerable: true,
|
|
41
|
+
configurable: true,
|
|
42
|
+
writable: true
|
|
43
|
+
});
|
|
44
|
+
} else {
|
|
45
|
+
obj[key] = value;
|
|
46
|
+
}
|
|
47
|
+
return obj;
|
|
48
|
+
}
|
|
49
|
+
function _instanceof$1(left, right) {
|
|
50
|
+
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
51
|
+
return !!right[Symbol.hasInstance](left);
|
|
52
|
+
} else {
|
|
53
|
+
return left instanceof right;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function _object_spread$1(target) {
|
|
57
|
+
for(var i = 1; i < arguments.length; i++){
|
|
58
|
+
var source = arguments[i] != null ? arguments[i] : {};
|
|
59
|
+
var ownKeys = Object.keys(source);
|
|
60
|
+
if (typeof Object.getOwnPropertySymbols === "function") {
|
|
61
|
+
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
|
|
62
|
+
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
ownKeys.forEach(function(key) {
|
|
66
|
+
_define_property$2(target, key, source[key]);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return target;
|
|
70
|
+
}
|
|
71
|
+
function ownKeys(object, enumerableOnly) {
|
|
72
|
+
var keys = Object.keys(object);
|
|
73
|
+
if (Object.getOwnPropertySymbols) {
|
|
74
|
+
var symbols = Object.getOwnPropertySymbols(object);
|
|
75
|
+
keys.push.apply(keys, symbols);
|
|
76
|
+
}
|
|
77
|
+
return keys;
|
|
78
|
+
}
|
|
79
|
+
function _object_spread_props(target, source) {
|
|
80
|
+
source = source != null ? source : {};
|
|
81
|
+
if (Object.getOwnPropertyDescriptors) {
|
|
82
|
+
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
|
|
83
|
+
} else {
|
|
84
|
+
ownKeys(Object(source)).forEach(function(key) {
|
|
85
|
+
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
return target;
|
|
89
|
+
}
|
|
90
|
+
function _ts_generator(thisArg, body) {
|
|
91
|
+
var f, y, t, _ = {
|
|
92
|
+
label: 0,
|
|
93
|
+
sent: function() {
|
|
94
|
+
if (t[0] & 1) throw t[1];
|
|
95
|
+
return t[1];
|
|
96
|
+
},
|
|
97
|
+
trys: [],
|
|
98
|
+
ops: []
|
|
99
|
+
}, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
100
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
|
|
101
|
+
return this;
|
|
102
|
+
}), g;
|
|
103
|
+
function verb(n) {
|
|
104
|
+
return function(v) {
|
|
105
|
+
return step([
|
|
106
|
+
n,
|
|
107
|
+
v
|
|
108
|
+
]);
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function step(op) {
|
|
112
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
113
|
+
while(g && (g = 0, op[0] && (_ = 0)), _)try {
|
|
114
|
+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
115
|
+
if (y = 0, t) op = [
|
|
116
|
+
op[0] & 2,
|
|
117
|
+
t.value
|
|
118
|
+
];
|
|
119
|
+
switch(op[0]){
|
|
120
|
+
case 0:
|
|
121
|
+
case 1:
|
|
122
|
+
t = op;
|
|
123
|
+
break;
|
|
124
|
+
case 4:
|
|
125
|
+
_.label++;
|
|
126
|
+
return {
|
|
127
|
+
value: op[1],
|
|
128
|
+
done: false
|
|
129
|
+
};
|
|
130
|
+
case 5:
|
|
131
|
+
_.label++;
|
|
132
|
+
y = op[1];
|
|
133
|
+
op = [
|
|
134
|
+
0
|
|
135
|
+
];
|
|
136
|
+
continue;
|
|
137
|
+
case 7:
|
|
138
|
+
op = _.ops.pop();
|
|
139
|
+
_.trys.pop();
|
|
140
|
+
continue;
|
|
141
|
+
default:
|
|
142
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
|
143
|
+
_ = 0;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
|
147
|
+
_.label = op[1];
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
if (op[0] === 6 && _.label < t[1]) {
|
|
151
|
+
_.label = t[1];
|
|
152
|
+
t = op;
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
if (t && _.label < t[2]) {
|
|
156
|
+
_.label = t[2];
|
|
157
|
+
_.ops.push(op);
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
if (t[2]) _.ops.pop();
|
|
161
|
+
_.trys.pop();
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
op = body.call(thisArg, _);
|
|
165
|
+
} catch (e) {
|
|
166
|
+
op = [
|
|
167
|
+
6,
|
|
168
|
+
e
|
|
169
|
+
];
|
|
170
|
+
y = 0;
|
|
171
|
+
} finally{
|
|
172
|
+
f = t = 0;
|
|
173
|
+
}
|
|
174
|
+
if (op[0] & 5) throw op[1];
|
|
175
|
+
return {
|
|
176
|
+
value: op[0] ? op[1] : void 0,
|
|
177
|
+
done: true
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
}
|
|
10
181
|
/**
|
|
11
|
-
*
|
|
12
|
-
|
|
182
|
+
* Creates AI SDK middleware that logs model requests and responses.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```ts
|
|
186
|
+
* import { wrapLanguageModel } from 'ai';
|
|
187
|
+
*
|
|
188
|
+
* const model = wrapLanguageModel({
|
|
189
|
+
* model: openrouter('anthropic/claude-sonnet-4-20250514'),
|
|
190
|
+
* middleware: createLoggingMiddleware({ logger }),
|
|
191
|
+
* });
|
|
192
|
+
* ```
|
|
193
|
+
*/ function createLoggingMiddleware(options) {
|
|
194
|
+
var logger = options.logger, _options_verbose = options.verbose, verbose = _options_verbose === void 0 ? false : _options_verbose;
|
|
195
|
+
return {
|
|
196
|
+
middlewareVersion: 'v2',
|
|
197
|
+
wrapGenerate: function(param) {
|
|
198
|
+
var doGenerate = param.doGenerate, params = param.params;
|
|
199
|
+
return _async_to_generator(function() {
|
|
200
|
+
var startTime, result, error;
|
|
201
|
+
return _ts_generator(this, function(_state) {
|
|
202
|
+
switch(_state.label){
|
|
203
|
+
case 0:
|
|
204
|
+
startTime = Date.now();
|
|
205
|
+
logger.debug('Model request started', _object_spread$1({}, verbose && {
|
|
206
|
+
params: params
|
|
207
|
+
}));
|
|
208
|
+
_state.label = 1;
|
|
209
|
+
case 1:
|
|
210
|
+
_state.trys.push([
|
|
211
|
+
1,
|
|
212
|
+
3,
|
|
213
|
+
,
|
|
214
|
+
4
|
|
215
|
+
]);
|
|
216
|
+
return [
|
|
217
|
+
4,
|
|
218
|
+
doGenerate()
|
|
219
|
+
];
|
|
220
|
+
case 2:
|
|
221
|
+
result = _state.sent();
|
|
222
|
+
logger.debug('Model request completed', _object_spread$1({
|
|
223
|
+
durationMs: Date.now() - startTime,
|
|
224
|
+
finishReason: result.finishReason,
|
|
225
|
+
usage: result.usage
|
|
226
|
+
}, verbose && {
|
|
227
|
+
content: result.content
|
|
228
|
+
}));
|
|
229
|
+
return [
|
|
230
|
+
2,
|
|
231
|
+
result
|
|
232
|
+
];
|
|
233
|
+
case 3:
|
|
234
|
+
error = _state.sent();
|
|
235
|
+
logger.error('Model request failed', {
|
|
236
|
+
durationMs: Date.now() - startTime,
|
|
237
|
+
error: _instanceof$1(error, Error) ? error.message : 'Unknown error'
|
|
238
|
+
});
|
|
239
|
+
throw error;
|
|
240
|
+
case 4:
|
|
241
|
+
return [
|
|
242
|
+
2
|
|
243
|
+
];
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
})();
|
|
247
|
+
},
|
|
248
|
+
wrapStream: function(param) {
|
|
249
|
+
var doStream = param.doStream, params = param.params;
|
|
250
|
+
return _async_to_generator(function() {
|
|
251
|
+
var startTime, result, error;
|
|
252
|
+
return _ts_generator(this, function(_state) {
|
|
253
|
+
switch(_state.label){
|
|
254
|
+
case 0:
|
|
255
|
+
startTime = Date.now();
|
|
256
|
+
logger.debug('Model stream started', _object_spread$1({}, verbose && {
|
|
257
|
+
params: params
|
|
258
|
+
}));
|
|
259
|
+
_state.label = 1;
|
|
260
|
+
case 1:
|
|
261
|
+
_state.trys.push([
|
|
262
|
+
1,
|
|
263
|
+
3,
|
|
264
|
+
,
|
|
265
|
+
4
|
|
266
|
+
]);
|
|
267
|
+
return [
|
|
268
|
+
4,
|
|
269
|
+
doStream()
|
|
270
|
+
];
|
|
271
|
+
case 2:
|
|
272
|
+
result = _state.sent();
|
|
273
|
+
return [
|
|
274
|
+
2,
|
|
275
|
+
_object_spread_props(_object_spread$1({}, result), {
|
|
276
|
+
stream: result.stream
|
|
277
|
+
})
|
|
278
|
+
];
|
|
279
|
+
case 3:
|
|
280
|
+
error = _state.sent();
|
|
281
|
+
logger.error('Model stream failed', {
|
|
282
|
+
durationMs: Date.now() - startTime,
|
|
283
|
+
error: _instanceof$1(error, Error) ? error.message : 'Unknown error'
|
|
284
|
+
});
|
|
285
|
+
throw error;
|
|
286
|
+
case 4:
|
|
287
|
+
return [
|
|
288
|
+
2
|
|
289
|
+
];
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
})();
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Creates a system prompt that instructs the model to output structured data
|
|
299
|
+
* matching the provided Zod schema.
|
|
300
|
+
*
|
|
301
|
+
* Use this with `generateText` when the provider doesn't support native
|
|
302
|
+
* structured outputs, then parse the response with `parseObject`.
|
|
303
|
+
*
|
|
304
|
+
* @param schema - A Zod schema defining the expected output structure
|
|
305
|
+
* @returns A system prompt string with JSON schema instructions
|
|
306
|
+
*
|
|
307
|
+
* @example
|
|
308
|
+
* ```ts
|
|
309
|
+
* import { generateText } from 'ai';
|
|
310
|
+
* import { createSchemaPrompt, parseObject } from '@jterrazz/intelligence';
|
|
311
|
+
*
|
|
312
|
+
* const schema = z.object({ title: z.string(), tags: z.array(z.string()) });
|
|
313
|
+
*
|
|
314
|
+
* const { text } = await generateText({
|
|
315
|
+
* model,
|
|
316
|
+
* prompt: 'Generate an article about TypeScript',
|
|
317
|
+
* system: createSchemaPrompt(schema),
|
|
318
|
+
* });
|
|
319
|
+
*
|
|
320
|
+
* const result = parseObject(text, schema);
|
|
321
|
+
* ```
|
|
322
|
+
*/ function createSchemaPrompt(schema) {
|
|
323
|
+
var jsonSchema = v4.z.toJSONSchema(schema);
|
|
324
|
+
var schemaJson = JSON.stringify(jsonSchema, null, 2);
|
|
325
|
+
var isPrimitive = [
|
|
326
|
+
'boolean',
|
|
327
|
+
'integer',
|
|
328
|
+
'number',
|
|
329
|
+
'string'
|
|
330
|
+
].includes(jsonSchema.type);
|
|
331
|
+
if (isPrimitive) {
|
|
332
|
+
return "<OUTPUT_FORMAT>\nYou must respond with a ".concat(jsonSchema.type, " value that matches this schema:\n\n```json\n").concat(schemaJson, "\n```\n\nYour response should be only the ").concat(jsonSchema.type, " value, without any JSON wrapping or additional text.\n</OUTPUT_FORMAT>");
|
|
333
|
+
}
|
|
334
|
+
return "<OUTPUT_FORMAT>\nYou must respond with valid JSON that matches this JSON schema:\n\n```json\n".concat(schemaJson, "\n```\n\nYour response must be parseable JSON that validates against this schema. Do not include any text outside the JSON.\n</OUTPUT_FORMAT>");
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function _array_like_to_array(arr, len) {
|
|
338
|
+
if (len == null || len > arr.length) len = arr.length;
|
|
339
|
+
for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
|
|
340
|
+
return arr2;
|
|
341
|
+
}
|
|
342
|
+
function _array_with_holes(arr) {
|
|
343
|
+
if (Array.isArray(arr)) return arr;
|
|
344
|
+
}
|
|
345
|
+
function _assert_this_initialized(self) {
|
|
13
346
|
if (self === void 0) {
|
|
14
347
|
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
|
|
15
348
|
}
|
|
@@ -19,7 +352,7 @@ function _call_super(_this, derived, args) {
|
|
|
19
352
|
derived = _get_prototype_of(derived);
|
|
20
353
|
return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
|
|
21
354
|
}
|
|
22
|
-
function _class_call_check
|
|
355
|
+
function _class_call_check(instance, Constructor) {
|
|
23
356
|
if (!(instance instanceof Constructor)) {
|
|
24
357
|
throw new TypeError("Cannot call a class as a function");
|
|
25
358
|
}
|
|
@@ -41,7 +374,7 @@ function _construct(Parent, args, Class) {
|
|
|
41
374
|
}
|
|
42
375
|
return _construct.apply(null, arguments);
|
|
43
376
|
}
|
|
44
|
-
function _define_property$
|
|
377
|
+
function _define_property$1(obj, key, value) {
|
|
45
378
|
if (key in obj) {
|
|
46
379
|
Object.defineProperty(obj, key, {
|
|
47
380
|
value: value,
|
|
@@ -73,11 +406,45 @@ function _inherits(subClass, superClass) {
|
|
|
73
406
|
});
|
|
74
407
|
if (superClass) _set_prototype_of(subClass, superClass);
|
|
75
408
|
}
|
|
409
|
+
function _instanceof(left, right) {
|
|
410
|
+
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
411
|
+
return !!right[Symbol.hasInstance](left);
|
|
412
|
+
} else {
|
|
413
|
+
return left instanceof right;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
76
416
|
function _is_native_function(fn) {
|
|
77
417
|
return Function.toString.call(fn).indexOf("[native code]") !== -1;
|
|
78
418
|
}
|
|
419
|
+
function _iterable_to_array_limit(arr, i) {
|
|
420
|
+
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
|
|
421
|
+
if (_i == null) return;
|
|
422
|
+
var _arr = [];
|
|
423
|
+
var _n = true;
|
|
424
|
+
var _d = false;
|
|
425
|
+
var _s, _e;
|
|
426
|
+
try {
|
|
427
|
+
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
|
|
428
|
+
_arr.push(_s.value);
|
|
429
|
+
if (i && _arr.length === i) break;
|
|
430
|
+
}
|
|
431
|
+
} catch (err) {
|
|
432
|
+
_d = true;
|
|
433
|
+
_e = err;
|
|
434
|
+
} finally{
|
|
435
|
+
try {
|
|
436
|
+
if (!_n && _i["return"] != null) _i["return"]();
|
|
437
|
+
} finally{
|
|
438
|
+
if (_d) throw _e;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return _arr;
|
|
442
|
+
}
|
|
443
|
+
function _non_iterable_rest() {
|
|
444
|
+
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
445
|
+
}
|
|
79
446
|
function _possible_constructor_return(self, call) {
|
|
80
|
-
if (call && (_type_of
|
|
447
|
+
if (call && (_type_of(call) === "object" || typeof call === "function")) {
|
|
81
448
|
return call;
|
|
82
449
|
}
|
|
83
450
|
return _assert_this_initialized(self);
|
|
@@ -89,10 +456,21 @@ function _set_prototype_of(o, p) {
|
|
|
89
456
|
};
|
|
90
457
|
return _set_prototype_of(o, p);
|
|
91
458
|
}
|
|
92
|
-
function
|
|
459
|
+
function _sliced_to_array(arr, i) {
|
|
460
|
+
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
|
|
461
|
+
}
|
|
462
|
+
function _type_of(obj) {
|
|
93
463
|
"@swc/helpers - typeof";
|
|
94
464
|
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
|
|
95
465
|
}
|
|
466
|
+
function _unsupported_iterable_to_array(o, minLen) {
|
|
467
|
+
if (!o) return;
|
|
468
|
+
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
469
|
+
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
470
|
+
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
471
|
+
if (n === "Map" || n === "Set") return Array.from(n);
|
|
472
|
+
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
473
|
+
}
|
|
96
474
|
function _wrap_native_super(Class) {
|
|
97
475
|
var _cache = typeof Map === "function" ? new Map() : undefined;
|
|
98
476
|
_wrap_native_super = function wrapNativeSuper(Class) {
|
|
@@ -127,1093 +505,271 @@ function _is_native_reflect_construct() {
|
|
|
127
505
|
return !!result;
|
|
128
506
|
})();
|
|
129
507
|
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
508
|
+
/**
|
|
509
|
+
* Error thrown when object parsing fails.
|
|
510
|
+
* Contains the original text for debugging purposes.
|
|
511
|
+
*/ var ParseObjectError = /*#__PURE__*/ function(Error1) {
|
|
512
|
+
_inherits(ParseObjectError, Error1);
|
|
513
|
+
function ParseObjectError(message, cause, text) {
|
|
514
|
+
_class_call_check(this, ParseObjectError);
|
|
134
515
|
var _this;
|
|
135
|
-
_this = _call_super(this,
|
|
516
|
+
_this = _call_super(this, ParseObjectError, [
|
|
136
517
|
message
|
|
137
|
-
]), _define_property$
|
|
138
|
-
_this.name = 'AIResponseParserError';
|
|
518
|
+
]), _define_property$1(_this, "cause", void 0), _define_property$1(_this, "text", void 0), _define_property$1(_this, "name", void 0), _this.cause = cause, _this.text = text, _this.name = 'ParseObjectError';
|
|
139
519
|
return _this;
|
|
140
520
|
}
|
|
141
|
-
return
|
|
521
|
+
return ParseObjectError;
|
|
142
522
|
}(_wrap_native_super(Error));
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
523
|
+
/**
|
|
524
|
+
* Parses AI-generated text into structured data validated against a Zod schema.
|
|
525
|
+
*
|
|
526
|
+
* Handles common AI response formats:
|
|
527
|
+
* - JSON wrapped in markdown code blocks
|
|
528
|
+
* - JSON embedded in prose text
|
|
529
|
+
* - Malformed JSON (auto-repaired)
|
|
530
|
+
* - Escaped unicode and special characters
|
|
531
|
+
*
|
|
532
|
+
* @param text - The raw AI response text
|
|
533
|
+
* @param schema - A Zod schema to validate and type the result
|
|
534
|
+
* @returns The parsed and validated data
|
|
535
|
+
* @throws {ParseObjectError} When parsing or validation fails
|
|
536
|
+
*
|
|
537
|
+
* @example
|
|
538
|
+
* ```ts
|
|
539
|
+
* const schema = z.object({ title: z.string(), tags: z.array(z.string()) });
|
|
540
|
+
* const result = parseObject(aiResponse, schema);
|
|
541
|
+
* // result is typed as { title: string; tags: string[] }
|
|
542
|
+
* ```
|
|
543
|
+
*/ function parseObject(text, schema) {
|
|
544
|
+
try {
|
|
545
|
+
var jsonString = extractJsonString(text);
|
|
546
|
+
var extracted = extractBySchemaType(jsonString, schema, text);
|
|
547
|
+
var unescaped = unescapeJsonValues(extracted);
|
|
548
|
+
return schema.parse(unescaped);
|
|
549
|
+
} catch (error) {
|
|
550
|
+
if (_instanceof(error, ParseObjectError)) {
|
|
551
|
+
throw error;
|
|
552
|
+
}
|
|
553
|
+
if (_instanceof(error, v4.z.ZodError)) {
|
|
554
|
+
throw new ParseObjectError('Failed to validate response against schema', error, text);
|
|
555
|
+
}
|
|
556
|
+
throw error;
|
|
557
|
+
}
|
|
148
558
|
}
|
|
149
|
-
|
|
150
|
-
|
|
559
|
+
var MARKDOWN_CODE_BLOCK_RE = /```(?:json)?\r?\n([^`]*?)\r?\n```/g;
|
|
560
|
+
function convertToPrimitive(value, schema) {
|
|
561
|
+
if (_instanceof(schema, v4.z.ZodBoolean)) return Boolean(value);
|
|
562
|
+
if (_instanceof(schema, v4.z.ZodNull)) return null;
|
|
563
|
+
if (_instanceof(schema, v4.z.ZodNumber)) return Number(value);
|
|
564
|
+
if (_instanceof(schema, v4.z.ZodString)) return String(value);
|
|
565
|
+
return value;
|
|
151
566
|
}
|
|
152
|
-
function
|
|
153
|
-
|
|
154
|
-
|
|
567
|
+
function extractArray(text, originalText) {
|
|
568
|
+
var start = text.indexOf('[');
|
|
569
|
+
var end = text.lastIndexOf(']');
|
|
570
|
+
if (start === -1 || end === -1) {
|
|
571
|
+
throw new ParseObjectError('No array found in response', undefined, originalText);
|
|
572
|
+
}
|
|
573
|
+
try {
|
|
574
|
+
var raw = text.slice(start, end + 1);
|
|
575
|
+
return JSON.parse(jsonrepair.jsonrepair(raw));
|
|
576
|
+
} catch (error) {
|
|
577
|
+
throw new ParseObjectError('Failed to parse array JSON', error, originalText);
|
|
155
578
|
}
|
|
156
579
|
}
|
|
157
|
-
function
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
Object.defineProperty(target, descriptor.key, descriptor);
|
|
580
|
+
function extractBySchemaType(text, schema, originalText) {
|
|
581
|
+
if (_instanceof(schema, v4.z.ZodArray)) {
|
|
582
|
+
return extractArray(text, originalText);
|
|
583
|
+
}
|
|
584
|
+
if (_instanceof(schema, v4.z.ZodObject)) {
|
|
585
|
+
return extractObject(text, originalText);
|
|
164
586
|
}
|
|
587
|
+
if (_instanceof(schema, v4.z.ZodBoolean) || _instanceof(schema, v4.z.ZodNull) || _instanceof(schema, v4.z.ZodNumber) || _instanceof(schema, v4.z.ZodString)) {
|
|
588
|
+
return extractPrimitive(text, schema);
|
|
589
|
+
}
|
|
590
|
+
throw new ParseObjectError('Unsupported schema type', undefined, originalText);
|
|
165
591
|
}
|
|
166
|
-
function
|
|
167
|
-
|
|
168
|
-
|
|
592
|
+
function extractJsonFromCodeBlock(block) {
|
|
593
|
+
var content = block.replace(/```(?:json)?\r?\n([^`]*?)\r?\n```/, '$1').trim();
|
|
594
|
+
try {
|
|
595
|
+
JSON.parse(content);
|
|
596
|
+
return content;
|
|
597
|
+
} catch (e) {
|
|
598
|
+
return null;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
function extractJsonString(text) {
|
|
602
|
+
var codeBlocks = text.match(MARKDOWN_CODE_BLOCK_RE);
|
|
603
|
+
if (codeBlocks && codeBlocks.length > 0) {
|
|
604
|
+
var validBlocks = codeBlocks.map(function(block) {
|
|
605
|
+
return extractJsonFromCodeBlock(block);
|
|
606
|
+
}).filter(function(block) {
|
|
607
|
+
return block !== null;
|
|
608
|
+
});
|
|
609
|
+
if (validBlocks.length > 0) {
|
|
610
|
+
return findLongestString(validBlocks);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
var structures = findJsonStructures(text);
|
|
614
|
+
if (structures.length > 0) {
|
|
615
|
+
return findLongestString(structures);
|
|
616
|
+
}
|
|
617
|
+
return text.replace(/\s+/g, ' ').trim();
|
|
169
618
|
}
|
|
170
|
-
function
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
configurable: true,
|
|
176
|
-
writable: true
|
|
177
|
-
});
|
|
178
|
-
} else {
|
|
179
|
-
obj[key] = value;
|
|
180
|
-
}
|
|
181
|
-
return obj;
|
|
182
|
-
}
|
|
183
|
-
function _instanceof$3(left, right) {
|
|
184
|
-
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
185
|
-
return !!right[Symbol.hasInstance](left);
|
|
186
|
-
} else {
|
|
187
|
-
return left instanceof right;
|
|
619
|
+
function extractObject(text, originalText) {
|
|
620
|
+
var start = text.indexOf('{');
|
|
621
|
+
var end = text.lastIndexOf('}');
|
|
622
|
+
if (start === -1 || end === -1) {
|
|
623
|
+
throw new ParseObjectError('No object found in response', undefined, originalText);
|
|
188
624
|
}
|
|
189
|
-
}
|
|
190
|
-
function _iterable_to_array_limit(arr, i) {
|
|
191
|
-
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
|
|
192
|
-
if (_i == null) return;
|
|
193
|
-
var _arr = [];
|
|
194
|
-
var _n = true;
|
|
195
|
-
var _d = false;
|
|
196
|
-
var _s, _e;
|
|
197
625
|
try {
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
if (i && _arr.length === i) break;
|
|
201
|
-
}
|
|
202
|
-
} catch (err) {
|
|
203
|
-
_d = true;
|
|
204
|
-
_e = err;
|
|
205
|
-
} finally{
|
|
206
|
-
try {
|
|
207
|
-
if (!_n && _i["return"] != null) _i["return"]();
|
|
208
|
-
} finally{
|
|
209
|
-
if (_d) throw _e;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
return _arr;
|
|
213
|
-
}
|
|
214
|
-
function _non_iterable_rest() {
|
|
215
|
-
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
216
|
-
}
|
|
217
|
-
function _sliced_to_array(arr, i) {
|
|
218
|
-
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
|
|
219
|
-
}
|
|
220
|
-
function _type_of(obj) {
|
|
221
|
-
"@swc/helpers - typeof";
|
|
222
|
-
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
|
|
223
|
-
}
|
|
224
|
-
function _unsupported_iterable_to_array(o, minLen) {
|
|
225
|
-
if (!o) return;
|
|
226
|
-
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
227
|
-
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
228
|
-
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
229
|
-
if (n === "Map" || n === "Set") return Array.from(n);
|
|
230
|
-
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
231
|
-
}
|
|
232
|
-
/**
|
|
233
|
-
* Parses AI response text into structured data based on Zod schema
|
|
234
|
-
*/ var AIResponseParser = /*#__PURE__*/ function() {
|
|
235
|
-
function AIResponseParser(schema) {
|
|
236
|
-
_class_call_check$6(this, AIResponseParser);
|
|
237
|
-
_define_property$6(this, "schema", void 0);
|
|
238
|
-
this.schema = schema;
|
|
239
|
-
}
|
|
240
|
-
_create_class$6(AIResponseParser, [
|
|
241
|
-
{
|
|
242
|
-
key: "parse",
|
|
243
|
-
value: /**
|
|
244
|
-
* Parses the AI response text based on the configured schema
|
|
245
|
-
*/ function parse(text) {
|
|
246
|
-
try {
|
|
247
|
-
var cleanedText = this.cleanText(text);
|
|
248
|
-
var json = this.extractJsonFromText(cleanedText);
|
|
249
|
-
var unescapedJson = this.unescapeJsonValues(json);
|
|
250
|
-
return this.schema.parse(unescapedJson);
|
|
251
|
-
} catch (error) {
|
|
252
|
-
if (_instanceof$3(error, v4.z.ZodError)) {
|
|
253
|
-
throw new AIResponseParserError('Failed to validate response against schema', error, text);
|
|
254
|
-
}
|
|
255
|
-
throw error;
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
},
|
|
259
|
-
{
|
|
260
|
-
key: "cleanText",
|
|
261
|
-
value: /**
|
|
262
|
-
* Cleans text and finds the largest schema-compatible structure
|
|
263
|
-
*/ function cleanText(text) {
|
|
264
|
-
var _this = this;
|
|
265
|
-
// First try to extract from markdown code blocks
|
|
266
|
-
var codeBlocks = text.match(/```(?:json)?\r?\n([^`]*?)\r?\n```/g);
|
|
267
|
-
if (codeBlocks) {
|
|
268
|
-
// Try each code block and return the largest valid one
|
|
269
|
-
var validBlocks = codeBlocks.map(function(block) {
|
|
270
|
-
return _this.extractJsonFromCodeBlock(block);
|
|
271
|
-
}).filter(function(block) {
|
|
272
|
-
return block !== null;
|
|
273
|
-
});
|
|
274
|
-
if (validBlocks.length > 0) {
|
|
275
|
-
return this.findLargestString(validBlocks);
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
// If no valid code blocks, try to find JSON-like structures in the text
|
|
279
|
-
var jsonMatches = this.findJsonStructures(text);
|
|
280
|
-
if (jsonMatches.length > 0) {
|
|
281
|
-
return this.findLargestString(jsonMatches);
|
|
282
|
-
}
|
|
283
|
-
// If no JSON structures found, clean and return the original text
|
|
284
|
-
return text.replace(/\s+/g, ' ').trim();
|
|
285
|
-
}
|
|
286
|
-
},
|
|
287
|
-
{
|
|
288
|
-
key: "convertToPrimitive",
|
|
289
|
-
value: /**
|
|
290
|
-
* Converts value to appropriate primitive type based on schema
|
|
291
|
-
*/ function convertToPrimitive(value, schema) {
|
|
292
|
-
if (_instanceof$3(schema, v4.z.ZodString)) {
|
|
293
|
-
return String(value);
|
|
294
|
-
}
|
|
295
|
-
if (_instanceof$3(schema, v4.z.ZodNumber)) {
|
|
296
|
-
return Number(value);
|
|
297
|
-
}
|
|
298
|
-
if (_instanceof$3(schema, v4.z.ZodBoolean)) {
|
|
299
|
-
return Boolean(value);
|
|
300
|
-
}
|
|
301
|
-
if (_instanceof$3(schema, v4.z.ZodNull)) {
|
|
302
|
-
return null;
|
|
303
|
-
}
|
|
304
|
-
return value;
|
|
305
|
-
}
|
|
306
|
-
},
|
|
307
|
-
{
|
|
308
|
-
key: "extractArray",
|
|
309
|
-
value: /**
|
|
310
|
-
* Extracts array from text
|
|
311
|
-
*/ function extractArray(text) {
|
|
312
|
-
var arrayStart = text.indexOf('[');
|
|
313
|
-
var arrayEnd = text.lastIndexOf(']');
|
|
314
|
-
if (arrayStart === -1 || arrayEnd === -1) {
|
|
315
|
-
throw new AIResponseParserError('No array found in response', undefined, text);
|
|
316
|
-
}
|
|
317
|
-
try {
|
|
318
|
-
var raw = text.slice(arrayStart, arrayEnd + 1);
|
|
319
|
-
var repaired = this.repairJson(raw);
|
|
320
|
-
return JSON.parse(repaired);
|
|
321
|
-
} catch (error) {
|
|
322
|
-
throw new AIResponseParserError('Failed to parse array JSON', error, text);
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
},
|
|
326
|
-
{
|
|
327
|
-
key: "extractJsonFromCodeBlock",
|
|
328
|
-
value: /**
|
|
329
|
-
* Extracts and validates JSON content from a code block
|
|
330
|
-
*/ function extractJsonFromCodeBlock(block) {
|
|
331
|
-
var content = block.replace(/```(?:json)?\r?\n([^`]*?)\r?\n```/, '$1').trim();
|
|
332
|
-
try {
|
|
333
|
-
// Attempt to parse as JSON to validate structure
|
|
334
|
-
JSON.parse(content);
|
|
335
|
-
return content;
|
|
336
|
-
} catch (e) {
|
|
337
|
-
return null;
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
},
|
|
341
|
-
{
|
|
342
|
-
key: "extractJsonFromText",
|
|
343
|
-
value: /**
|
|
344
|
-
* Extracts and parses JSON from text based on schema type
|
|
345
|
-
*/ function extractJsonFromText(text) {
|
|
346
|
-
if (_instanceof$3(this.schema, v4.z.ZodArray)) {
|
|
347
|
-
return this.extractArray(text);
|
|
348
|
-
}
|
|
349
|
-
if (_instanceof$3(this.schema, v4.z.ZodObject)) {
|
|
350
|
-
return this.extractObject(text);
|
|
351
|
-
}
|
|
352
|
-
if (_instanceof$3(this.schema, v4.z.ZodString) || _instanceof$3(this.schema, v4.z.ZodNumber) || _instanceof$3(this.schema, v4.z.ZodBoolean) || _instanceof$3(this.schema, v4.z.ZodNull)) {
|
|
353
|
-
return this.extractPrimitive(text, this.schema);
|
|
354
|
-
}
|
|
355
|
-
throw new AIResponseParserError('Unsupported schema type', undefined, text);
|
|
356
|
-
}
|
|
357
|
-
},
|
|
358
|
-
{
|
|
359
|
-
key: "extractObject",
|
|
360
|
-
value: /**
|
|
361
|
-
* Extracts object from text
|
|
362
|
-
*/ function extractObject(text) {
|
|
363
|
-
var objectStart = text.indexOf('{');
|
|
364
|
-
var objectEnd = text.lastIndexOf('}');
|
|
365
|
-
if (objectStart === -1 || objectEnd === -1) {
|
|
366
|
-
throw new AIResponseParserError('No object found in response', undefined, text);
|
|
367
|
-
}
|
|
368
|
-
try {
|
|
369
|
-
var raw = text.slice(objectStart, objectEnd + 1);
|
|
370
|
-
var repaired = this.repairJson(raw);
|
|
371
|
-
return JSON.parse(repaired);
|
|
372
|
-
} catch (error) {
|
|
373
|
-
throw new AIResponseParserError('Failed to parse object JSON', error, text);
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
},
|
|
377
|
-
{
|
|
378
|
-
key: "extractPrimitive",
|
|
379
|
-
value: /**
|
|
380
|
-
* Extracts and converts primitive value from text
|
|
381
|
-
*/ function extractPrimitive(text, schema) {
|
|
382
|
-
var trimmed = text.trim();
|
|
383
|
-
// Try to parse as JSON first in case it's quoted
|
|
384
|
-
try {
|
|
385
|
-
var parsed = JSON.parse(trimmed);
|
|
386
|
-
return this.convertToPrimitive(parsed, schema);
|
|
387
|
-
} catch (e) {
|
|
388
|
-
// If not valid JSON, use the raw string
|
|
389
|
-
return this.convertToPrimitive(trimmed, schema);
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
},
|
|
393
|
-
{
|
|
394
|
-
key: "findJsonStructures",
|
|
395
|
-
value: /**
|
|
396
|
-
* Finds valid JSON structures in raw text
|
|
397
|
-
*/ function findJsonStructures(text) {
|
|
398
|
-
var jsonMatches = [];
|
|
399
|
-
var depth = 0;
|
|
400
|
-
var start = -1;
|
|
401
|
-
for(var i = 0; i < text.length; i++){
|
|
402
|
-
var char = text[i];
|
|
403
|
-
if (char === '{' || char === '[') {
|
|
404
|
-
if (depth === 0) start = i;
|
|
405
|
-
depth++;
|
|
406
|
-
} else if (char === '}' || char === ']') {
|
|
407
|
-
depth--;
|
|
408
|
-
if (depth === 0 && start !== -1) {
|
|
409
|
-
var potentialJson = text.slice(start, i + 1);
|
|
410
|
-
try {
|
|
411
|
-
JSON.parse(potentialJson);
|
|
412
|
-
jsonMatches.push(potentialJson);
|
|
413
|
-
} catch (e) {
|
|
414
|
-
// Invalid JSON, ignore
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
return jsonMatches;
|
|
420
|
-
}
|
|
421
|
-
},
|
|
422
|
-
{
|
|
423
|
-
key: "findLargestString",
|
|
424
|
-
value: /**
|
|
425
|
-
* Returns the largest string from an array of strings
|
|
426
|
-
*/ function findLargestString(strings) {
|
|
427
|
-
return strings.reduce(function(largest, current) {
|
|
428
|
-
return current.length > largest.length ? current : largest;
|
|
429
|
-
}, strings[0]);
|
|
430
|
-
}
|
|
431
|
-
},
|
|
432
|
-
{
|
|
433
|
-
key: "repairJson",
|
|
434
|
-
value: /**
|
|
435
|
-
* Repairs common JSON issues using jsonrepair library
|
|
436
|
-
*/ function repairJson(jsonString) {
|
|
437
|
-
return jsonrepair.jsonrepair(jsonString);
|
|
438
|
-
}
|
|
439
|
-
},
|
|
440
|
-
{
|
|
441
|
-
key: "unescapeJsonValues",
|
|
442
|
-
value: /**
|
|
443
|
-
* Recursively unescapes all string values in a JSON object/array
|
|
444
|
-
*/ function unescapeJsonValues(json) {
|
|
445
|
-
var _this = this;
|
|
446
|
-
if (typeof json === 'string') {
|
|
447
|
-
return this.unescapeText(json);
|
|
448
|
-
}
|
|
449
|
-
if (Array.isArray(json)) {
|
|
450
|
-
return json.map(function(item) {
|
|
451
|
-
return _this.unescapeJsonValues(item);
|
|
452
|
-
});
|
|
453
|
-
}
|
|
454
|
-
if ((typeof json === "undefined" ? "undefined" : _type_of(json)) === 'object' && json !== null) {
|
|
455
|
-
return Object.fromEntries(Object.entries(json).map(function(param) {
|
|
456
|
-
var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1];
|
|
457
|
-
return [
|
|
458
|
-
key,
|
|
459
|
-
_this.unescapeJsonValues(value)
|
|
460
|
-
];
|
|
461
|
-
}));
|
|
462
|
-
}
|
|
463
|
-
return json;
|
|
464
|
-
}
|
|
465
|
-
},
|
|
466
|
-
{
|
|
467
|
-
key: "unescapeText",
|
|
468
|
-
value: /**
|
|
469
|
-
* Unescapes common escaped characters in text
|
|
470
|
-
*/ function unescapeText(text) {
|
|
471
|
-
return text.replace(/\\"/g, '"') // Unescape quotes
|
|
472
|
-
.replace(/\\n/g, '\n') // Unescape newlines
|
|
473
|
-
.replace(/\\r/g, '\r') // Unescape carriage returns
|
|
474
|
-
.replace(/\\t/g, '\t') // Unescape tabs
|
|
475
|
-
.replace(/\\\\/g, '\\') // Unescape backslashes
|
|
476
|
-
.replace(/\\u([0-9a-fA-F]{4})/g, function(_, code) {
|
|
477
|
-
return String.fromCharCode(parseInt(code, 16));
|
|
478
|
-
}); // Unescape unicode
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
]);
|
|
482
|
-
return AIResponseParser;
|
|
483
|
-
}();
|
|
484
|
-
|
|
485
|
-
function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
|
|
486
|
-
try {
|
|
487
|
-
var info = gen[key](arg);
|
|
488
|
-
var value = info.value;
|
|
626
|
+
var raw = text.slice(start, end + 1);
|
|
627
|
+
return JSON.parse(jsonrepair.jsonrepair(raw));
|
|
489
628
|
} catch (error) {
|
|
490
|
-
|
|
491
|
-
return;
|
|
492
|
-
}
|
|
493
|
-
if (info.done) {
|
|
494
|
-
resolve(value);
|
|
495
|
-
} else {
|
|
496
|
-
Promise.resolve(value).then(_next, _throw);
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
function _async_to_generator$2(fn) {
|
|
500
|
-
return function() {
|
|
501
|
-
var self = this, args = arguments;
|
|
502
|
-
return new Promise(function(resolve, reject) {
|
|
503
|
-
var gen = fn.apply(self, args);
|
|
504
|
-
function _next(value) {
|
|
505
|
-
asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
|
|
506
|
-
}
|
|
507
|
-
function _throw(err) {
|
|
508
|
-
asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
|
|
509
|
-
}
|
|
510
|
-
_next(undefined);
|
|
511
|
-
});
|
|
512
|
-
};
|
|
513
|
-
}
|
|
514
|
-
function _class_call_check$5(instance, Constructor) {
|
|
515
|
-
if (!(instance instanceof Constructor)) {
|
|
516
|
-
throw new TypeError("Cannot call a class as a function");
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
function _defineProperties$5(target, props) {
|
|
520
|
-
for(var i = 0; i < props.length; i++){
|
|
521
|
-
var descriptor = props[i];
|
|
522
|
-
descriptor.enumerable = descriptor.enumerable || false;
|
|
523
|
-
descriptor.configurable = true;
|
|
524
|
-
if ("value" in descriptor) descriptor.writable = true;
|
|
525
|
-
Object.defineProperty(target, descriptor.key, descriptor);
|
|
526
|
-
}
|
|
527
|
-
}
|
|
528
|
-
function _create_class$5(Constructor, protoProps, staticProps) {
|
|
529
|
-
if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);
|
|
530
|
-
return Constructor;
|
|
531
|
-
}
|
|
532
|
-
function _define_property$5(obj, key, value) {
|
|
533
|
-
if (key in obj) {
|
|
534
|
-
Object.defineProperty(obj, key, {
|
|
535
|
-
value: value,
|
|
536
|
-
enumerable: true,
|
|
537
|
-
configurable: true,
|
|
538
|
-
writable: true
|
|
539
|
-
});
|
|
540
|
-
} else {
|
|
541
|
-
obj[key] = value;
|
|
542
|
-
}
|
|
543
|
-
return obj;
|
|
544
|
-
}
|
|
545
|
-
function _instanceof$2(left, right) {
|
|
546
|
-
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
547
|
-
return !!right[Symbol.hasInstance](left);
|
|
548
|
-
} else {
|
|
549
|
-
return left instanceof right;
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
function _ts_generator$2(thisArg, body) {
|
|
553
|
-
var f, y, t, _ = {
|
|
554
|
-
label: 0,
|
|
555
|
-
sent: function() {
|
|
556
|
-
if (t[0] & 1) throw t[1];
|
|
557
|
-
return t[1];
|
|
558
|
-
},
|
|
559
|
-
trys: [],
|
|
560
|
-
ops: []
|
|
561
|
-
}, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
562
|
-
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
|
|
563
|
-
return this;
|
|
564
|
-
}), g;
|
|
565
|
-
function verb(n) {
|
|
566
|
-
return function(v) {
|
|
567
|
-
return step([
|
|
568
|
-
n,
|
|
569
|
-
v
|
|
570
|
-
]);
|
|
571
|
-
};
|
|
572
|
-
}
|
|
573
|
-
function step(op) {
|
|
574
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
575
|
-
while(g && (g = 0, op[0] && (_ = 0)), _)try {
|
|
576
|
-
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
577
|
-
if (y = 0, t) op = [
|
|
578
|
-
op[0] & 2,
|
|
579
|
-
t.value
|
|
580
|
-
];
|
|
581
|
-
switch(op[0]){
|
|
582
|
-
case 0:
|
|
583
|
-
case 1:
|
|
584
|
-
t = op;
|
|
585
|
-
break;
|
|
586
|
-
case 4:
|
|
587
|
-
_.label++;
|
|
588
|
-
return {
|
|
589
|
-
value: op[1],
|
|
590
|
-
done: false
|
|
591
|
-
};
|
|
592
|
-
case 5:
|
|
593
|
-
_.label++;
|
|
594
|
-
y = op[1];
|
|
595
|
-
op = [
|
|
596
|
-
0
|
|
597
|
-
];
|
|
598
|
-
continue;
|
|
599
|
-
case 7:
|
|
600
|
-
op = _.ops.pop();
|
|
601
|
-
_.trys.pop();
|
|
602
|
-
continue;
|
|
603
|
-
default:
|
|
604
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
|
605
|
-
_ = 0;
|
|
606
|
-
continue;
|
|
607
|
-
}
|
|
608
|
-
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
|
609
|
-
_.label = op[1];
|
|
610
|
-
break;
|
|
611
|
-
}
|
|
612
|
-
if (op[0] === 6 && _.label < t[1]) {
|
|
613
|
-
_.label = t[1];
|
|
614
|
-
t = op;
|
|
615
|
-
break;
|
|
616
|
-
}
|
|
617
|
-
if (t && _.label < t[2]) {
|
|
618
|
-
_.label = t[2];
|
|
619
|
-
_.ops.push(op);
|
|
620
|
-
break;
|
|
621
|
-
}
|
|
622
|
-
if (t[2]) _.ops.pop();
|
|
623
|
-
_.trys.pop();
|
|
624
|
-
continue;
|
|
625
|
-
}
|
|
626
|
-
op = body.call(thisArg, _);
|
|
627
|
-
} catch (e) {
|
|
628
|
-
op = [
|
|
629
|
-
6,
|
|
630
|
-
e
|
|
631
|
-
];
|
|
632
|
-
y = 0;
|
|
633
|
-
} finally{
|
|
634
|
-
f = t = 0;
|
|
635
|
-
}
|
|
636
|
-
if (op[0] & 5) throw op[1];
|
|
637
|
-
return {
|
|
638
|
-
value: op[0] ? op[1] : void 0,
|
|
639
|
-
done: true
|
|
640
|
-
};
|
|
629
|
+
throw new ParseObjectError('Failed to parse object JSON', error, originalText);
|
|
641
630
|
}
|
|
642
631
|
}
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
{
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
case 0:
|
|
665
|
-
(_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.debug('Starting chat execution', {
|
|
666
|
-
agent: this.name
|
|
667
|
-
});
|
|
668
|
-
_state.label = 1;
|
|
669
|
-
case 1:
|
|
670
|
-
_state.trys.push([
|
|
671
|
-
1,
|
|
672
|
-
4,
|
|
673
|
-
,
|
|
674
|
-
5
|
|
675
|
-
]);
|
|
676
|
-
return [
|
|
677
|
-
4,
|
|
678
|
-
this.createExecutor()
|
|
679
|
-
];
|
|
680
|
-
case 2:
|
|
681
|
-
executor = _state.sent();
|
|
682
|
-
userInput = this.resolveUserInput(input);
|
|
683
|
-
return [
|
|
684
|
-
4,
|
|
685
|
-
executor.invoke({
|
|
686
|
-
input: userInput
|
|
687
|
-
})
|
|
688
|
-
];
|
|
689
|
-
case 3:
|
|
690
|
-
result = _state.sent();
|
|
691
|
-
(_this_options_logger1 = this.options.logger) === null || _this_options_logger1 === void 0 ? void 0 : _this_options_logger1.debug('Agent execution completed', {
|
|
692
|
-
agent: this.name,
|
|
693
|
-
hasOutput: 'output' in result
|
|
694
|
-
});
|
|
695
|
-
if (!result || typeof result.output !== 'string') {
|
|
696
|
-
throw new Error('Agent returned an invalid result structure.');
|
|
697
|
-
}
|
|
698
|
-
agentResponse = this.parseAgentOutput(result.output);
|
|
699
|
-
if (!agentResponse) {
|
|
700
|
-
return [
|
|
701
|
-
2,
|
|
702
|
-
null
|
|
703
|
-
];
|
|
704
|
-
}
|
|
705
|
-
if (!agentResponse.shouldRespond) {
|
|
706
|
-
(_this_options_logger2 = this.options.logger) === null || _this_options_logger2 === void 0 ? void 0 : _this_options_logger2.debug('Agent chose to remain silent', {
|
|
707
|
-
agent: this.name,
|
|
708
|
-
reason: agentResponse.reason
|
|
709
|
-
});
|
|
710
|
-
return [
|
|
711
|
-
2,
|
|
712
|
-
null
|
|
713
|
-
];
|
|
714
|
-
}
|
|
715
|
-
message = (_agentResponse_message = agentResponse.message) !== null && _agentResponse_message !== void 0 ? _agentResponse_message : '';
|
|
716
|
-
if (this.options.schema) {
|
|
717
|
-
validatedResponse = this.validateResponseContent(message, this.options.schema);
|
|
718
|
-
(_this_options_logger3 = this.options.logger) === null || _this_options_logger3 === void 0 ? void 0 : _this_options_logger3.debug('Execution finished; response content validated.', {
|
|
719
|
-
agent: this.name
|
|
720
|
-
});
|
|
721
|
-
return [
|
|
722
|
-
2,
|
|
723
|
-
validatedResponse
|
|
724
|
-
];
|
|
725
|
-
} else {
|
|
726
|
-
(_this_options_logger4 = this.options.logger) === null || _this_options_logger4 === void 0 ? void 0 : _this_options_logger4.debug('Execution finished', {
|
|
727
|
-
agent: this.name
|
|
728
|
-
});
|
|
729
|
-
// When no schema is provided, we assume TOutput is string (default), so message is the result
|
|
730
|
-
return [
|
|
731
|
-
2,
|
|
732
|
-
message
|
|
733
|
-
];
|
|
734
|
-
}
|
|
735
|
-
case 4:
|
|
736
|
-
error = _state.sent();
|
|
737
|
-
(_this_options_logger5 = this.options.logger) === null || _this_options_logger5 === void 0 ? void 0 : _this_options_logger5.error('Chat execution failed', {
|
|
738
|
-
agent: this.name,
|
|
739
|
-
error: _instanceof$2(error, Error) ? error.message : 'Unknown error'
|
|
740
|
-
});
|
|
741
|
-
return [
|
|
742
|
-
2,
|
|
743
|
-
null
|
|
744
|
-
];
|
|
745
|
-
case 5:
|
|
746
|
-
return [
|
|
747
|
-
2
|
|
748
|
-
];
|
|
749
|
-
}
|
|
750
|
-
});
|
|
751
|
-
}).call(this);
|
|
752
|
-
}
|
|
753
|
-
},
|
|
754
|
-
{
|
|
755
|
-
key: "createExecutor",
|
|
756
|
-
value: function createExecutor() {
|
|
757
|
-
return _async_to_generator$2(function() {
|
|
758
|
-
var model, tools, schemaFormatInstructions, jsonSchema, isPrimitiveType, jsonSchemaString, prompt, agent;
|
|
759
|
-
return _ts_generator$2(this, function(_state) {
|
|
760
|
-
switch(_state.label){
|
|
761
|
-
case 0:
|
|
762
|
-
model = this.options.model.getModel();
|
|
763
|
-
tools = this.options.tools.map(function(tool) {
|
|
764
|
-
return tool.getDynamicTool();
|
|
765
|
-
});
|
|
766
|
-
// Add schema format instructions if schema is provided
|
|
767
|
-
schemaFormatInstructions = '';
|
|
768
|
-
if (this.options.schema) {
|
|
769
|
-
jsonSchema = v4.z.toJSONSchema(this.options.schema);
|
|
770
|
-
isPrimitiveType = [
|
|
771
|
-
'boolean',
|
|
772
|
-
'integer',
|
|
773
|
-
'number',
|
|
774
|
-
'string'
|
|
775
|
-
].includes(jsonSchema.type);
|
|
776
|
-
jsonSchemaString = JSON.stringify(jsonSchema, null, 2).replace(/{/g, '{{').replace(/}/g, '}}');
|
|
777
|
-
if (isPrimitiveType) {
|
|
778
|
-
schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be a '.concat(jsonSchema.type, " value that matches this schema description:\n\n```json\n").concat(jsonSchemaString, '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: your ').concat(jsonSchema.type, ' value here"\n}}\n```\n\nDo not wrap the ').concat(jsonSchema.type, ' value in JSON - just provide the raw value after "RESPOND: ".');
|
|
779
|
-
} else {
|
|
780
|
-
schemaFormatInstructions = '\n\nSCHEMA VALIDATION: When providing a "RESPOND:" answer, the content after "RESPOND: " must be valid JSON that matches this JSON schema description:\n\n```json\n'.concat(jsonSchemaString, '\n```\n\nExample format:\n```json\n{{\n "action": "Final Answer",\n "action_input": "RESPOND: {{\\"field1\\": \\"value1\\", \\"field2\\": \\"value2\\"}}"\n}}\n```\n');
|
|
781
|
-
}
|
|
782
|
-
}
|
|
783
|
-
prompt = prompts.ChatPromptTemplate.fromMessages([
|
|
784
|
-
[
|
|
785
|
-
'system',
|
|
786
|
-
SYSTEM_PROMPT_TEMPLATE.replace('{mission_prompt}', this.options.systemPrompt.generate()).replace('{schema_format}', schemaFormatInstructions)
|
|
787
|
-
],
|
|
788
|
-
[
|
|
789
|
-
'human',
|
|
790
|
-
'{input}'
|
|
791
|
-
]
|
|
792
|
-
]);
|
|
793
|
-
return [
|
|
794
|
-
4,
|
|
795
|
-
agents.createStructuredChatAgent({
|
|
796
|
-
llm: model,
|
|
797
|
-
prompt: prompt,
|
|
798
|
-
tools: tools
|
|
799
|
-
})
|
|
800
|
-
];
|
|
801
|
-
case 1:
|
|
802
|
-
agent = _state.sent();
|
|
803
|
-
return [
|
|
804
|
-
2,
|
|
805
|
-
agents.AgentExecutor.fromAgentAndTools({
|
|
806
|
-
agent: agent,
|
|
807
|
-
tools: tools,
|
|
808
|
-
verbose: this.options.verbose
|
|
809
|
-
})
|
|
810
|
-
];
|
|
811
|
-
}
|
|
812
|
-
});
|
|
813
|
-
}).call(this);
|
|
814
|
-
}
|
|
815
|
-
},
|
|
816
|
-
{
|
|
817
|
-
key: "parseAgentOutput",
|
|
818
|
-
value: function parseAgentOutput(output) {
|
|
819
|
-
var _this_options_logger;
|
|
820
|
-
var text = output.trim();
|
|
821
|
-
var respondMatch = text.match(/^RESPOND:\s*([\s\S]+)$/i);
|
|
822
|
-
if (respondMatch) {
|
|
823
|
-
return {
|
|
824
|
-
message: respondMatch[1].trim(),
|
|
825
|
-
shouldRespond: true
|
|
826
|
-
};
|
|
827
|
-
}
|
|
828
|
-
var silentMatch = text.match(/^SILENT:\s*([\s\S]+)$/i);
|
|
829
|
-
if (silentMatch) {
|
|
830
|
-
return {
|
|
831
|
-
reason: silentMatch[1].trim(),
|
|
832
|
-
shouldRespond: false
|
|
833
|
-
};
|
|
834
|
-
}
|
|
835
|
-
(_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.error("Agent output was missing 'RESPOND:' or 'SILENT:' prefix.", {
|
|
836
|
-
agent: this.name,
|
|
837
|
-
rawOutput: output
|
|
838
|
-
});
|
|
839
|
-
return null;
|
|
840
|
-
}
|
|
841
|
-
},
|
|
842
|
-
{
|
|
843
|
-
key: "resolveUserInput",
|
|
844
|
-
value: function resolveUserInput(input) {
|
|
845
|
-
if (input) {
|
|
846
|
-
return input.generate();
|
|
847
|
-
}
|
|
848
|
-
return 'Proceed with your instructions.';
|
|
849
|
-
}
|
|
850
|
-
},
|
|
851
|
-
{
|
|
852
|
-
key: "validateResponseContent",
|
|
853
|
-
value: function validateResponseContent(content, schema) {
|
|
632
|
+
function extractPrimitive(text, schema) {
|
|
633
|
+
var trimmed = text.trim();
|
|
634
|
+
try {
|
|
635
|
+
return convertToPrimitive(JSON.parse(trimmed), schema);
|
|
636
|
+
} catch (e) {
|
|
637
|
+
return convertToPrimitive(trimmed, schema);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
function findJsonStructures(text) {
|
|
641
|
+
var matches = [];
|
|
642
|
+
var depth = 0;
|
|
643
|
+
var start = -1;
|
|
644
|
+
for(var i = 0; i < text.length; i++){
|
|
645
|
+
var _char = text[i];
|
|
646
|
+
if (_char === '{' || _char === '[') {
|
|
647
|
+
if (depth === 0) start = i;
|
|
648
|
+
depth++;
|
|
649
|
+
} else if (_char === '}' || _char === ']') {
|
|
650
|
+
depth--;
|
|
651
|
+
if (depth === 0 && start !== -1) {
|
|
652
|
+
var candidate = text.slice(start, i + 1);
|
|
854
653
|
try {
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
agent: this.name,
|
|
860
|
-
error: _instanceof$2(error, Error) ? error.message : 'Unknown error',
|
|
861
|
-
rawContent: content
|
|
862
|
-
});
|
|
863
|
-
throw new Error('Invalid response content from model.');
|
|
654
|
+
JSON.parse(candidate);
|
|
655
|
+
matches.push(candidate);
|
|
656
|
+
} catch (e) {
|
|
657
|
+
// Invalid JSON, skip
|
|
864
658
|
}
|
|
865
659
|
}
|
|
866
660
|
}
|
|
867
|
-
]);
|
|
868
|
-
return AutonomousAgentAdapter;
|
|
869
|
-
}();
|
|
870
|
-
|
|
871
|
-
function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
|
|
872
|
-
try {
|
|
873
|
-
var info = gen[key](arg);
|
|
874
|
-
var value = info.value;
|
|
875
|
-
} catch (error) {
|
|
876
|
-
reject(error);
|
|
877
|
-
return;
|
|
878
661
|
}
|
|
879
|
-
|
|
880
|
-
resolve(value);
|
|
881
|
-
} else {
|
|
882
|
-
Promise.resolve(value).then(_next, _throw);
|
|
883
|
-
}
|
|
884
|
-
}
|
|
885
|
-
function _async_to_generator$1(fn) {
|
|
886
|
-
return function() {
|
|
887
|
-
var self = this, args = arguments;
|
|
888
|
-
return new Promise(function(resolve, reject) {
|
|
889
|
-
var gen = fn.apply(self, args);
|
|
890
|
-
function _next(value) {
|
|
891
|
-
asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
|
|
892
|
-
}
|
|
893
|
-
function _throw(err) {
|
|
894
|
-
asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
|
|
895
|
-
}
|
|
896
|
-
_next(undefined);
|
|
897
|
-
});
|
|
898
|
-
};
|
|
662
|
+
return matches;
|
|
899
663
|
}
|
|
900
|
-
function
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
function _defineProperties$4(target, props) {
|
|
906
|
-
for(var i = 0; i < props.length; i++){
|
|
907
|
-
var descriptor = props[i];
|
|
908
|
-
descriptor.enumerable = descriptor.enumerable || false;
|
|
909
|
-
descriptor.configurable = true;
|
|
910
|
-
if ("value" in descriptor) descriptor.writable = true;
|
|
911
|
-
Object.defineProperty(target, descriptor.key, descriptor);
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
function _create_class$4(Constructor, protoProps, staticProps) {
|
|
915
|
-
if (protoProps) _defineProperties$4(Constructor.prototype, protoProps);
|
|
916
|
-
return Constructor;
|
|
917
|
-
}
|
|
918
|
-
function _define_property$4(obj, key, value) {
|
|
919
|
-
if (key in obj) {
|
|
920
|
-
Object.defineProperty(obj, key, {
|
|
921
|
-
value: value,
|
|
922
|
-
enumerable: true,
|
|
923
|
-
configurable: true,
|
|
924
|
-
writable: true
|
|
925
|
-
});
|
|
926
|
-
} else {
|
|
927
|
-
obj[key] = value;
|
|
928
|
-
}
|
|
929
|
-
return obj;
|
|
930
|
-
}
|
|
931
|
-
function _instanceof$1(left, right) {
|
|
932
|
-
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
933
|
-
return !!right[Symbol.hasInstance](left);
|
|
934
|
-
} else {
|
|
935
|
-
return left instanceof right;
|
|
936
|
-
}
|
|
664
|
+
function findLongestString(strings) {
|
|
665
|
+
return strings.reduce(function(longest, current) {
|
|
666
|
+
return current.length > longest.length ? current : longest;
|
|
667
|
+
});
|
|
937
668
|
}
|
|
938
|
-
function
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
sent: function() {
|
|
942
|
-
if (t[0] & 1) throw t[1];
|
|
943
|
-
return t[1];
|
|
944
|
-
},
|
|
945
|
-
trys: [],
|
|
946
|
-
ops: []
|
|
947
|
-
}, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
948
|
-
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
|
|
949
|
-
return this;
|
|
950
|
-
}), g;
|
|
951
|
-
function verb(n) {
|
|
952
|
-
return function(v) {
|
|
953
|
-
return step([
|
|
954
|
-
n,
|
|
955
|
-
v
|
|
956
|
-
]);
|
|
957
|
-
};
|
|
958
|
-
}
|
|
959
|
-
function step(op) {
|
|
960
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
961
|
-
while(g && (g = 0, op[0] && (_ = 0)), _)try {
|
|
962
|
-
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
963
|
-
if (y = 0, t) op = [
|
|
964
|
-
op[0] & 2,
|
|
965
|
-
t.value
|
|
966
|
-
];
|
|
967
|
-
switch(op[0]){
|
|
968
|
-
case 0:
|
|
969
|
-
case 1:
|
|
970
|
-
t = op;
|
|
971
|
-
break;
|
|
972
|
-
case 4:
|
|
973
|
-
_.label++;
|
|
974
|
-
return {
|
|
975
|
-
value: op[1],
|
|
976
|
-
done: false
|
|
977
|
-
};
|
|
978
|
-
case 5:
|
|
979
|
-
_.label++;
|
|
980
|
-
y = op[1];
|
|
981
|
-
op = [
|
|
982
|
-
0
|
|
983
|
-
];
|
|
984
|
-
continue;
|
|
985
|
-
case 7:
|
|
986
|
-
op = _.ops.pop();
|
|
987
|
-
_.trys.pop();
|
|
988
|
-
continue;
|
|
989
|
-
default:
|
|
990
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
|
991
|
-
_ = 0;
|
|
992
|
-
continue;
|
|
993
|
-
}
|
|
994
|
-
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
|
995
|
-
_.label = op[1];
|
|
996
|
-
break;
|
|
997
|
-
}
|
|
998
|
-
if (op[0] === 6 && _.label < t[1]) {
|
|
999
|
-
_.label = t[1];
|
|
1000
|
-
t = op;
|
|
1001
|
-
break;
|
|
1002
|
-
}
|
|
1003
|
-
if (t && _.label < t[2]) {
|
|
1004
|
-
_.label = t[2];
|
|
1005
|
-
_.ops.push(op);
|
|
1006
|
-
break;
|
|
1007
|
-
}
|
|
1008
|
-
if (t[2]) _.ops.pop();
|
|
1009
|
-
_.trys.pop();
|
|
1010
|
-
continue;
|
|
1011
|
-
}
|
|
1012
|
-
op = body.call(thisArg, _);
|
|
1013
|
-
} catch (e) {
|
|
1014
|
-
op = [
|
|
1015
|
-
6,
|
|
1016
|
-
e
|
|
1017
|
-
];
|
|
1018
|
-
y = 0;
|
|
1019
|
-
} finally{
|
|
1020
|
-
f = t = 0;
|
|
1021
|
-
}
|
|
1022
|
-
if (op[0] & 5) throw op[1];
|
|
1023
|
-
return {
|
|
1024
|
-
value: op[0] ? op[1] : void 0,
|
|
1025
|
-
done: true
|
|
1026
|
-
};
|
|
669
|
+
function unescapeJsonValues(json) {
|
|
670
|
+
if (typeof json === 'string') {
|
|
671
|
+
return unescapeString(json);
|
|
1027
672
|
}
|
|
673
|
+
if (Array.isArray(json)) {
|
|
674
|
+
return json.map(unescapeJsonValues);
|
|
675
|
+
}
|
|
676
|
+
if ((typeof json === "undefined" ? "undefined" : _type_of(json)) === 'object' && json !== null) {
|
|
677
|
+
return Object.fromEntries(Object.entries(json).map(function(param) {
|
|
678
|
+
var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1];
|
|
679
|
+
return [
|
|
680
|
+
key,
|
|
681
|
+
unescapeJsonValues(value)
|
|
682
|
+
];
|
|
683
|
+
}));
|
|
684
|
+
}
|
|
685
|
+
return json;
|
|
686
|
+
}
|
|
687
|
+
function unescapeString(text) {
|
|
688
|
+
return text.replace(/\\"/g, '"').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, '\t').replace(/\\\\/g, '\\').replace(/\\u([0-9a-fA-F]{4})/g, function(_, code) {
|
|
689
|
+
return String.fromCharCode(Number.parseInt(code, 16));
|
|
690
|
+
});
|
|
1028
691
|
}
|
|
692
|
+
|
|
693
|
+
var INVISIBLE_CHARS_RE = /[\u00AD\u180E\u200B-\u200C\u200E-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;
|
|
694
|
+
/* eslint-disable no-control-regex -- intentionally matching control characters */ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentionally matching control characters for sanitization
|
|
695
|
+
var ASCII_CTRL_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g;
|
|
696
|
+
/* eslint-enable no-control-regex */ var SPACE_LIKE_RE = /[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/g;
|
|
697
|
+
var MULTIPLE_SPACES_RE = / {2,}/g;
|
|
698
|
+
var CR_RE = /\r\n?/g;
|
|
699
|
+
var CITATION_RE = / *\(oaicite:\d+\)\{index=\d+\}/g;
|
|
700
|
+
var EM_DASH_SEPARATOR_RE = /(?:\s+[—–―‒]\s*|\s*[—–―‒]\s+)/g;
|
|
701
|
+
var TYPOGRAPHY_REPLACEMENTS = [
|
|
702
|
+
{
|
|
703
|
+
pattern: /[\u2018\u2019\u201A]/g,
|
|
704
|
+
replacement: "'"
|
|
705
|
+
},
|
|
706
|
+
{
|
|
707
|
+
pattern: /[\u201C\u201D\u201E]/g,
|
|
708
|
+
replacement: '"'
|
|
709
|
+
},
|
|
710
|
+
{
|
|
711
|
+
pattern: /[\u2013\u2014]/g,
|
|
712
|
+
replacement: '-'
|
|
713
|
+
},
|
|
714
|
+
{
|
|
715
|
+
pattern: /\u2026/g,
|
|
716
|
+
replacement: '...'
|
|
717
|
+
},
|
|
718
|
+
{
|
|
719
|
+
pattern: /[\u2022\u25AA-\u25AB\u25B8-\u25B9\u25CF]/g,
|
|
720
|
+
replacement: '-'
|
|
721
|
+
}
|
|
722
|
+
];
|
|
1029
723
|
/**
|
|
1030
|
-
*
|
|
1031
|
-
*
|
|
1032
|
-
* @
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
case 2:
|
|
1066
|
-
content = _state.sent();
|
|
1067
|
-
if (this.options.schema) {
|
|
1068
|
-
parsedResponse = this.parseResponse(content, this.options.schema);
|
|
1069
|
-
(_this_options_logger1 = this.options.logger) === null || _this_options_logger1 === void 0 ? void 0 : _this_options_logger1.debug('Execution finished and response parsed', {
|
|
1070
|
-
agent: this.name
|
|
1071
|
-
});
|
|
1072
|
-
return [
|
|
1073
|
-
2,
|
|
1074
|
-
parsedResponse
|
|
1075
|
-
];
|
|
1076
|
-
} else {
|
|
1077
|
-
(_this_options_logger2 = this.options.logger) === null || _this_options_logger2 === void 0 ? void 0 : _this_options_logger2.debug('Execution finished', {
|
|
1078
|
-
agent: this.name
|
|
1079
|
-
});
|
|
1080
|
-
// When no schema is provided, we assume TOutput is string (default), so content is the result
|
|
1081
|
-
return [
|
|
1082
|
-
2,
|
|
1083
|
-
content
|
|
1084
|
-
];
|
|
1085
|
-
}
|
|
1086
|
-
case 3:
|
|
1087
|
-
error = _state.sent();
|
|
1088
|
-
(_this_options_logger3 = this.options.logger) === null || _this_options_logger3 === void 0 ? void 0 : _this_options_logger3.error('Execution failed', {
|
|
1089
|
-
agent: this.name,
|
|
1090
|
-
error: _instanceof$1(error, Error) ? error.message : 'Unknown error'
|
|
1091
|
-
});
|
|
1092
|
-
return [
|
|
1093
|
-
2,
|
|
1094
|
-
null
|
|
1095
|
-
];
|
|
1096
|
-
case 4:
|
|
1097
|
-
return [
|
|
1098
|
-
2
|
|
1099
|
-
];
|
|
1100
|
-
}
|
|
1101
|
-
});
|
|
1102
|
-
}).call(this);
|
|
1103
|
-
}
|
|
1104
|
-
},
|
|
1105
|
-
{
|
|
1106
|
-
key: "invokeModel",
|
|
1107
|
-
value: function invokeModel(input) {
|
|
1108
|
-
return _async_to_generator$1(function() {
|
|
1109
|
-
var _this_options_logger, userInput, systemMessage, jsonSchema, isPrimitiveType, messages, _this_options_logger1, response, content;
|
|
1110
|
-
return _ts_generator$1(this, function(_state) {
|
|
1111
|
-
switch(_state.label){
|
|
1112
|
-
case 0:
|
|
1113
|
-
userInput = this.resolveUserInput(input);
|
|
1114
|
-
systemMessage = this.options.systemPrompt.generate();
|
|
1115
|
-
// Add schema definition to system prompt if schema is provided
|
|
1116
|
-
if (this.options.schema) {
|
|
1117
|
-
jsonSchema = v4.z.toJSONSchema(this.options.schema);
|
|
1118
|
-
isPrimitiveType = [
|
|
1119
|
-
'boolean',
|
|
1120
|
-
'integer',
|
|
1121
|
-
'number',
|
|
1122
|
-
'string'
|
|
1123
|
-
].includes(jsonSchema.type);
|
|
1124
|
-
if (isPrimitiveType) {
|
|
1125
|
-
systemMessage += "\n\n<OUTPUT_FORMAT>\nYou must respond with a ".concat(jsonSchema.type, " value that matches this schema:\n\n```json\n").concat(JSON.stringify(jsonSchema, null, 2), "\n```\n\nYour response should be only the ").concat(jsonSchema.type, " value, without any JSON wrapping or additional text.\n</OUTPUT_FORMAT>");
|
|
1126
|
-
} else {
|
|
1127
|
-
systemMessage += "\n\n<OUTPUT_FORMAT>\nYou must respond with valid JSON that matches this JSON schema description:\n\n```json\n".concat(JSON.stringify(jsonSchema, null, 2), "\n```\n\nYour response must be parseable JSON that validates against this schema. Do not include any text outside the JSON.\n</OUTPUT_FORMAT>");
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
messages = [
|
|
1131
|
-
{
|
|
1132
|
-
content: systemMessage,
|
|
1133
|
-
role: 'system'
|
|
1134
|
-
},
|
|
1135
|
-
{
|
|
1136
|
-
content: userInput,
|
|
1137
|
-
role: 'user'
|
|
1138
|
-
}
|
|
1139
|
-
];
|
|
1140
|
-
(_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.debug('Invoking model...', {
|
|
1141
|
-
agent: this.name,
|
|
1142
|
-
hasSchema: !!this.options.schema
|
|
1143
|
-
});
|
|
1144
|
-
if (this.options.verbose) {
|
|
1145
|
-
(_this_options_logger1 = this.options.logger) === null || _this_options_logger1 === void 0 ? void 0 : _this_options_logger1.debug('Sending messages to model...', {
|
|
1146
|
-
agent: this.name,
|
|
1147
|
-
messages: messages
|
|
1148
|
-
});
|
|
1149
|
-
}
|
|
1150
|
-
return [
|
|
1151
|
-
4,
|
|
1152
|
-
this.options.model.getModel().invoke(messages)
|
|
1153
|
-
];
|
|
1154
|
-
case 1:
|
|
1155
|
-
response = _state.sent();
|
|
1156
|
-
content = response.content;
|
|
1157
|
-
if (typeof content !== 'string') {
|
|
1158
|
-
throw new Error('Model returned a non-string content type.');
|
|
1159
|
-
}
|
|
1160
|
-
return [
|
|
1161
|
-
2,
|
|
1162
|
-
content
|
|
1163
|
-
];
|
|
1164
|
-
}
|
|
1165
|
-
});
|
|
1166
|
-
}).call(this);
|
|
1167
|
-
}
|
|
1168
|
-
},
|
|
1169
|
-
{
|
|
1170
|
-
key: "parseResponse",
|
|
1171
|
-
value: function parseResponse(content, schema) {
|
|
1172
|
-
try {
|
|
1173
|
-
return new AIResponseParser(schema).parse(content);
|
|
1174
|
-
} catch (error) {
|
|
1175
|
-
var _this_options_logger;
|
|
1176
|
-
(_this_options_logger = this.options.logger) === null || _this_options_logger === void 0 ? void 0 : _this_options_logger.error('Failed to parse model response.', {
|
|
1177
|
-
agent: this.name,
|
|
1178
|
-
error: _instanceof$1(error, Error) ? error.message : 'Unknown error',
|
|
1179
|
-
rawContent: content
|
|
1180
|
-
});
|
|
1181
|
-
throw new Error('Invalid response format from model.');
|
|
1182
|
-
}
|
|
724
|
+
* Parses and sanitizes text by removing AI artifacts and normalizing typography.
|
|
725
|
+
*
|
|
726
|
+
* @param text - The text to parse
|
|
727
|
+
* @param options - Parsing options
|
|
728
|
+
* @returns The cleaned text
|
|
729
|
+
*/ function parseText(text) {
|
|
730
|
+
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
|
|
731
|
+
var _options_normalizeEmDashesToCommas = options.normalizeEmDashesToCommas, normalizeEmDashesToCommas = _options_normalizeEmDashesToCommas === void 0 ? true : _options_normalizeEmDashesToCommas, _options_collapseSpaces = options.collapseSpaces, collapseSpaces = _options_collapseSpaces === void 0 ? true : _options_collapseSpaces;
|
|
732
|
+
if (!text) return '';
|
|
733
|
+
var result = text;
|
|
734
|
+
if (result.charCodeAt(0) === 0xfeff) {
|
|
735
|
+
result = result.slice(1);
|
|
736
|
+
}
|
|
737
|
+
result = result.replace(CR_RE, '\n');
|
|
738
|
+
result = result.replace(CITATION_RE, '');
|
|
739
|
+
result = result.normalize('NFKC');
|
|
740
|
+
result = result.replace(INVISIBLE_CHARS_RE, '');
|
|
741
|
+
result = result.replace(ASCII_CTRL_RE, '');
|
|
742
|
+
if (normalizeEmDashesToCommas) {
|
|
743
|
+
result = result.replace(EM_DASH_SEPARATOR_RE, ', ');
|
|
744
|
+
}
|
|
745
|
+
result = result.replace(SPACE_LIKE_RE, ' ');
|
|
746
|
+
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
|
|
747
|
+
try {
|
|
748
|
+
for(var _iterator = TYPOGRAPHY_REPLACEMENTS[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
|
|
749
|
+
var _step_value = _step.value, pattern = _step_value.pattern, replacement = _step_value.replacement;
|
|
750
|
+
result = result.replace(pattern, replacement);
|
|
751
|
+
}
|
|
752
|
+
} catch (err) {
|
|
753
|
+
_didIteratorError = true;
|
|
754
|
+
_iteratorError = err;
|
|
755
|
+
} finally{
|
|
756
|
+
try {
|
|
757
|
+
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
|
|
758
|
+
_iterator["return"]();
|
|
1183
759
|
}
|
|
1184
|
-
}
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
value: function resolveUserInput(input) {
|
|
1188
|
-
if (input) {
|
|
1189
|
-
return input.generate();
|
|
1190
|
-
}
|
|
1191
|
-
return 'Proceed with your instructions.';
|
|
760
|
+
} finally{
|
|
761
|
+
if (_didIteratorError) {
|
|
762
|
+
throw _iteratorError;
|
|
1192
763
|
}
|
|
1193
764
|
}
|
|
1194
|
-
]);
|
|
1195
|
-
return BasicAgentAdapter;
|
|
1196
|
-
}();
|
|
1197
|
-
|
|
1198
|
-
function _class_call_check$3(instance, Constructor) {
|
|
1199
|
-
if (!(instance instanceof Constructor)) {
|
|
1200
|
-
throw new TypeError("Cannot call a class as a function");
|
|
1201
765
|
}
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
for(var i = 0; i < props.length; i++){
|
|
1205
|
-
var descriptor = props[i];
|
|
1206
|
-
descriptor.enumerable = descriptor.enumerable || false;
|
|
1207
|
-
descriptor.configurable = true;
|
|
1208
|
-
if ("value" in descriptor) descriptor.writable = true;
|
|
1209
|
-
Object.defineProperty(target, descriptor.key, descriptor);
|
|
766
|
+
if (collapseSpaces) {
|
|
767
|
+
result = result.replace(MULTIPLE_SPACES_RE, ' ').trim();
|
|
1210
768
|
}
|
|
769
|
+
return result;
|
|
1211
770
|
}
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
return Constructor;
|
|
1215
|
-
}
|
|
1216
|
-
function _define_property$3(obj, key, value) {
|
|
771
|
+
|
|
772
|
+
function _define_property(obj, key, value) {
|
|
1217
773
|
if (key in obj) {
|
|
1218
774
|
Object.defineProperty(obj, key, {
|
|
1219
775
|
value: value,
|
|
@@ -1236,574 +792,42 @@ function _object_spread(target) {
|
|
|
1236
792
|
}));
|
|
1237
793
|
}
|
|
1238
794
|
ownKeys.forEach(function(key) {
|
|
1239
|
-
_define_property
|
|
795
|
+
_define_property(target, key, source[key]);
|
|
1240
796
|
});
|
|
1241
797
|
}
|
|
1242
798
|
return target;
|
|
1243
799
|
}
|
|
1244
800
|
/**
|
|
1245
|
-
*
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
}
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
801
|
+
* Creates an OpenRouter provider for AI SDK models.
|
|
802
|
+
*
|
|
803
|
+
* @example
|
|
804
|
+
* ```ts
|
|
805
|
+
* const provider = createOpenRouterProvider({ apiKey: process.env.OPENROUTER_API_KEY });
|
|
806
|
+
* const model = provider.model('anthropic/claude-sonnet-4-20250514');
|
|
807
|
+
*
|
|
808
|
+
* const { text } = await generateText({ model, prompt: 'Hello!' });
|
|
809
|
+
* ```
|
|
810
|
+
*/ function createOpenRouterProvider(config) {
|
|
811
|
+
var openrouter = aiSdkProvider.createOpenRouter({
|
|
812
|
+
apiKey: config.apiKey
|
|
813
|
+
});
|
|
814
|
+
return {
|
|
815
|
+
model: function model(name) {
|
|
816
|
+
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
|
|
817
|
+
return openrouter(name, _object_spread({}, options.maxTokens !== undefined && {
|
|
818
|
+
maxTokens: options.maxTokens
|
|
819
|
+
}, options.reasoning && {
|
|
820
|
+
extraBody: {
|
|
821
|
+
reasoning: options.reasoning
|
|
1266
822
|
}
|
|
1267
|
-
}
|
|
1268
|
-
modelName: config.modelName,
|
|
1269
|
-
openAIApiKey: config.apiKey
|
|
1270
|
-
});
|
|
1271
|
-
}
|
|
1272
|
-
_create_class$3(OpenRouterModelAdapter, [
|
|
1273
|
-
{
|
|
1274
|
-
key: "getModel",
|
|
1275
|
-
value: function getModel() {
|
|
1276
|
-
return this.model;
|
|
1277
|
-
}
|
|
1278
|
-
}
|
|
1279
|
-
]);
|
|
1280
|
-
return OpenRouterModelAdapter;
|
|
1281
|
-
}();
|
|
1282
|
-
|
|
1283
|
-
/**
|
|
1284
|
-
* Specifies the agent's area of knowledge and expertise.
|
|
1285
|
-
* This focuses the agent's responses within a specific context.
|
|
1286
|
-
*/ var DOMAINS = {
|
|
1287
|
-
ACADEMIC_RESEARCH: "\n<Domain>\nYour knowledge is specialized in academic research. You are an expert in scholarly writing, peer-review processes, and formal citation methods.\n</Domain>",
|
|
1288
|
-
BUSINESS_STRATEGY: "\n<Domain>\nYour knowledge is specialized in business strategy, including market analysis, competitive positioning, and operational planning.\n</Domain>",
|
|
1289
|
-
DATA_SCIENCE: "\n<Domain>\nYour knowledge is specialized in data science, including statistical analysis, machine learning, and data visualization.\n</Domain>",
|
|
1290
|
-
GENERAL: "\n<Domain>\nYou possess broad, generalist knowledge across a wide variety of subjects.\n</Domain>",
|
|
1291
|
-
SOFTWARE_ENGINEERING: "\n<Domain>\nYour knowledge is specialized in software engineering. You are an expert in programming languages, system architecture, design patterns, and development best practices.\n</Domain>"
|
|
1292
|
-
};
|
|
1293
|
-
|
|
1294
|
-
/**
|
|
1295
|
-
* Defines the required structural format for the agent's output.
|
|
1296
|
-
*/ var FORMATS = {
|
|
1297
|
-
DISCORD_MARKDOWN: "\n<Format>\nYou MUST format your response using Discord-flavored Markdown (e.g., **bold**, *italics*, __underline__, `code`, ```code blocks```, > quotes).\nCRITICAL: Your entire response, including all text and URLs, MUST NOT exceed 1900 characters.\n</Format>",
|
|
1298
|
-
JSON: "\n<Format>\nYou MUST respond ONLY with a single, valid, well-formed JSON object.\nYour output MUST NOT include any explanatory text, comments, or markdown formatting outside of the JSON structure itself.\n</Format>",
|
|
1299
|
-
MARKDOWN: "\n<Format>\nYou MUST format your response using Markdown for clear, structured communication.\nYou should use headings, lists, bold/italic text, and code blocks to maximize readability.\n</Format>",
|
|
1300
|
-
PLAIN_TEXT: "\n<Format>\nYou MUST respond in plain text only, without any special formatting, markdown, or structural elements.\n</Format>",
|
|
1301
|
-
STEP_BY_STEP: "\n<Format>\nYou MUST break down any instructions or processes into a clear, numbered, step-by-step list.\nEach step must be a distinct and actionable item.\n</Format>"
|
|
1302
|
-
};
|
|
1303
|
-
|
|
1304
|
-
/**
|
|
1305
|
-
* Core, non-negotiable rules that establish the agent's fundamental identity and operational boundaries.
|
|
1306
|
-
* These are the foundational principles that guide all other instructions.
|
|
1307
|
-
*/ var FOUNDATIONS = {
|
|
1308
|
-
CONTEXTUAL_ONLY: "\n<Foundation>\nYou MUST ONLY use the information provided in the context to answer questions.\nYou MUST NOT use any other information, including your own knowledge, to answer questions.\n</Foundation>",
|
|
1309
|
-
CONTEXTUAL_REASONING: '\n<Foundation>\nYou MUST synthesize information from the provided context, tools, and conversation history to form well-reasoned conclusions.\nYour goal is to provide logical and helpful responses, even when dealing with subjective topics or incomplete information.\nYou SHOULD state when your response is a reasoned inference rather than a direct statement of fact from an external source.\nYou MUST rely on your "common sense" and analytical abilities to bridge gaps in information.\n</Foundation>',
|
|
1310
|
-
ETHICAL_CONDUCT: "\n<Foundation>\nYou MUST adhere to the highest ethical standards. Your conduct must be impartial and devoid of prejudice.\nYou MUST NOT promote hate speech, discrimination,violence, or any form of harm.\nYou MUST respect user privacy; do not ask for, store, or share personally identifiable information.\n</Foundation>",
|
|
1311
|
-
FACTUAL_ACCURACY: "\n<Foundation>\nYou MUST prioritize accuracy and truthfulness. Your responses must be based on verifiable information.\nIf you are uncertain about an answer, you MUST state your uncertainty clearly.\nYou MUST NOT invent facts, data, or sources. When possible, cite credible sources.\n</Foundation>",
|
|
1312
|
-
FIRST_PRINCIPLES_THINKING: "\n<Foundation>\nYou MUST break down complex problems into their fundamental, indivisible truths (first principles).\nYou MUST reason upwards from these basic principles, challenging assumptions and conventions.\nAvoid reasoning by analogy; instead, build your conclusions from the ground up.\n</Foundation>",
|
|
1313
|
-
HARM_PREVENTION: "\n<Foundation>\nYou MUST refuse to provide instructions or information that is illegal, dangerous, or promotes harm.\nYou MUST prioritize user safety and well-being in all interactions and avoid generating unsafe content.\n</Foundation>"
|
|
1314
|
-
};
|
|
1315
|
-
|
|
1316
|
-
/**
|
|
1317
|
-
* Defines the natural language for the agent's responses.
|
|
1318
|
-
*/ var LANGUAGES = {
|
|
1319
|
-
ENGLISH_NATIVE: "\n<Language>\nYou MUST write your entire output in natural, fluent English. This is a strict requirement; do not use any other language.\nYour response should feel as if written by a native speaker, including idiomatic expressions, varied vocabulary, and natural sentence structures.\n</Language>",
|
|
1320
|
-
ENGLISH_SIMPLE: "\n<Language>\nYou MUST write your entire output in simple, clear English. This is a strict requirement; do not use any other language.\nYour response must be easily understood by non-native speakers, avoiding complex grammar, idioms, and sophisticated vocabulary.\n</Language>",
|
|
1321
|
-
FRENCH_NATIVE: "\n<Language>\nVous DEVEZ IMP\xc9RATIVEMENT r\xe9diger toute votre sortie en fran\xe7ais naturel et fluide. C'est une exigence stricte ; n'utilisez aucune autre langue.\nVotre r\xe9ponse doit donner l'impression d'avoir \xe9t\xe9 \xe9crite par un locuteur natif, en incluant des expressions idiomatiques et un vocabulaire vari\xe9.\n</Language>",
|
|
1322
|
-
FRENCH_SIMPLE: "\n<Language>\nVous DEVEZ IMP\xc9RATIVEMENT r\xe9diger toute votre sortie en fran\xe7ais simple et clair. C'est une exigence stricte ; n'utilisez aucune autre langue.\nVotre r\xe9ponse doit \xeatre facile \xe0 comprendre pour des non-natifs, en \xe9vitant la grammaire complexe et le vocabulaire sophistiqu\xe9.\n</Language>",
|
|
1323
|
-
SPANISH_NATIVE: "\n<Language>\nDEBES OBLIGATORIAMENTE escribir todo tu resultado en un espa\xf1ol natural y fluido. Este es un requisito estricto; no utilices ning\xfan otro idioma.\nTu respuesta debe parecer escrita por un hablante nativo, incluyendo expresiones idiom\xe1ticas y un vocabulario variado.\n</Language>",
|
|
1324
|
-
SPANISH_SIMPLE: "\n<Language>\nDEBES OBLIGATORIAMENTE escribir todo tu resultado en un espa\xf1ol simple y claro. Este es un requisito estricto; no utilices ning\xfan otro idioma.\nTu respuesta debe ser f\xe1cil de entender para hablantes no nativos, evitando gram\xe1tica compleja y vocabulario sofisticado.\n</Language>"
|
|
1325
|
-
};
|
|
1326
|
-
|
|
1327
|
-
/**
|
|
1328
|
-
* Defines the agent's core identity, role, and purpose, integrating key skills.
|
|
1329
|
-
* This sets the primary character and interaction style.
|
|
1330
|
-
*/ var PERSONAS = {
|
|
1331
|
-
COMMUNITY_ANIMATOR: "\n<Persona>\nYou are the Community Animator, the vibrant heart of a digital community (e.g., Discord).\nYour purpose is to keep the community active, engaged, and positive.\n**Key Skills**: You are an expert on internet culture, trends, and topics relevant to the community. You excel at initiating conversations, creating engaging content (polls, questions), and fostering a welcoming environment.\n</Persona>",
|
|
1332
|
-
CREATIVE_PARTNER: "\n<Persona>\nYou are a Creative Partner, an imaginative collaborator for brainstorming and exploration.\nYour purpose is to help users generate and develop novel ideas.\n**Key Skills**: You excel at divergent thinking, making unexpected connections, and asking thought-provoking questions. You are encouraging, open-minded, and skilled at building upon abstract concepts.\n</Persona>",
|
|
1333
|
-
EXPERT_ADVISOR: "\n<Persona>\nYou are an Expert Advisor in your specified domain.\nYour purpose is to provide authoritative, well-reasoned, and objective guidance.\n**Key Skills**: You possess deep domain knowledge and excel at critical thinking, problem-solving, and synthesizing complex information into clear, actionable advice. Your communication is precise and confident.\n</Persona>",
|
|
1334
|
-
HUMAN_LIKE_CONTRIBUTOR: "\n<Persona>\nYou are a Human-Like Contributor, a thoughtful and engaging participant in a group chat.\nYour purpose is to interact in a way that is indistinguishable from a human, fostering natural and coherent conversations.\n**Key Skills**: You excel at maintaining conversational context, ensuring your contributions are a logical continuation of past interactions. You avoid repetition and can proactively initiate new topics when appropriate. Your style is natural, personal, and adaptive.\n</Persona>",
|
|
1335
|
-
JOURNALIST: "\n<Persona>\nYou are a Journalist, a skilled writer who crafts engaging, informative, and well-structured articles.\nYour purpose is to provide users with valuable, well-researched, and well-written content.\n**Key Skills**: You excel at writing clear, concise, and engaging articles. You are skilled at researching and gathering information, and you are able to write in a way that is both informative and entertaining.\n</Persona>",
|
|
1336
|
-
SUPPORT_AGENT: "\n<Persona>\nYou are a friendly, patient, and empathetic Support Agent.\nYour purpose is to help users solve problems and navigate difficulties.\n**Key Skills**: You are an excellent listener and a clear communicator. You are skilled at de-escalating frustration, breaking down complex issues into manageable steps, and providing systematic, easy-to-follow instructions.\n</Persona>",
|
|
1337
|
-
TUTOR: "\n<Persona>\nYou are a patient, knowledgeable, and encouraging Tutor.\nYour purpose is to help users learn and understand complex subjects.\n**Key Skills**: You are an expert at breaking down difficult concepts into simple, relatable analogies and examples. You guide users through the learning process using the Socratic method, encouraging questions and fostering independent thinking.\n</Persona>"
|
|
1338
|
-
};
|
|
1339
|
-
|
|
1340
|
-
/**
|
|
1341
|
-
* Defines the agent's strategic approach to when and how it should respond.
|
|
1342
|
-
*/ var RESPONSES = {
|
|
1343
|
-
ALWAYS_ENGAGE: "\n<ResponseStrategy>\nYou must always provide a response to the user's input. Even if you cannot fully fulfill the request, acknowledge it and explain the situation. Your primary directive is to be responsive.\n</ResponseStrategy>",
|
|
1344
|
-
CONTEXTUAL_ENGAGEMENT: "\n<ResponseStrategy>\nBefore responding, you must analyze the conversation history and the immediate context. Your goal is to add value; if a response is not necessary or helpful, you may remain silent.\n</ResponseStrategy>",
|
|
1345
|
-
SELECTIVE_ENGAGEMENT: "\n<ResponseStrategy>\nYou must only respond when you can provide a valuable, relevant, and substantive contribution to the conversation. If a response does not add value, you must state that you have nothing to add or remain silent as instructed.\n</ResponseStrategy>",
|
|
1346
|
-
TOOL_DRIVEN: "\n<ResponseStrategy>\nYour first priority is to use your available tools to gather the most current and accurate information before formulating a response. Do not answer from memory if a tool can provide a more reliable answer.\n</ResponseStrategy>"
|
|
1347
|
-
};
|
|
1348
|
-
|
|
1349
|
-
/**
|
|
1350
|
-
* Determines the emotional flavor and attitude of the agent's language.
|
|
1351
|
-
*/ var TONES = {
|
|
1352
|
-
EMPATHETIC: "\n<Tone>\nYou must adopt a warm, understanding, and supportive tone. Acknowledge the user's feelings and demonstrate active listening.\n</Tone>",
|
|
1353
|
-
HUMOROUS: "\n<Tone>\nYou should employ light-hearted humor, wit, and cleverness. Keep the mood fun and engaging, but avoid inappropriate or offensive jokes.\n</Tone>",
|
|
1354
|
-
NEUTRAL: "\n<Tone>\nYou must maintain an impartial, objective, and straightforward tone. Avoid all emotional language and stick to the facts.\n</Tone>",
|
|
1355
|
-
PROFESSIONAL: "\n<Tone>\nYou must use a formal, respectful, and clear tone. Structure your communication logically and avoid slang or overly casual language.\n</Tone>"
|
|
1356
|
-
};
|
|
1357
|
-
|
|
1358
|
-
/**
|
|
1359
|
-
* Controls the level of detail and length of the agent's responses.
|
|
1360
|
-
*/ var VERBOSITY = {
|
|
1361
|
-
CONCISE: "\n<Verbosity>\nYou must provide brief, to-the-point answers. Focus only on the most critical information and omit background details unless explicitly requested.\n</Verbosity>",
|
|
1362
|
-
DETAILED: "\n<Verbosity>\nYou must offer comprehensive and thorough responses. Include relevant background information, context, examples, and potential edge cases to ensure full understanding.\n</Verbosity>",
|
|
1363
|
-
NORMAL: "\n<Verbosity>\nYou should provide a balanced level of detail, sufficient for a clear understanding without being overwhelming or too brief.\n</Verbosity>"
|
|
1364
|
-
};
|
|
1365
|
-
|
|
1366
|
-
/**
|
|
1367
|
-
* Provides ready-to-use combinations of prompt parts for common use cases.
|
|
1368
|
-
*/ var PRESETS = {
|
|
1369
|
-
/**
|
|
1370
|
-
* A fun and engaging community animator for platforms like Discord.
|
|
1371
|
-
*/ COMMUNITY_ANIMATOR: [
|
|
1372
|
-
FOUNDATIONS.HARM_PREVENTION,
|
|
1373
|
-
PERSONAS.COMMUNITY_ANIMATOR,
|
|
1374
|
-
DOMAINS.GENERAL,
|
|
1375
|
-
TONES.HUMOROUS,
|
|
1376
|
-
VERBOSITY.NORMAL,
|
|
1377
|
-
RESPONSES.CONTEXTUAL_ENGAGEMENT
|
|
1378
|
-
],
|
|
1379
|
-
/**
|
|
1380
|
-
* A creative partner for brainstorming and ideation.
|
|
1381
|
-
*/ CREATIVE_BRAINSTORMER: [
|
|
1382
|
-
FOUNDATIONS.ETHICAL_CONDUCT,
|
|
1383
|
-
PERSONAS.CREATIVE_PARTNER,
|
|
1384
|
-
DOMAINS.GENERAL,
|
|
1385
|
-
TONES.HUMOROUS,
|
|
1386
|
-
VERBOSITY.NORMAL,
|
|
1387
|
-
RESPONSES.ALWAYS_ENGAGE
|
|
1388
|
-
],
|
|
1389
|
-
/**
|
|
1390
|
-
* A friendly and empathetic support agent for general queries.
|
|
1391
|
-
*/ EMPATHETIC_SUPPORT_AGENT: [
|
|
1392
|
-
FOUNDATIONS.HARM_PREVENTION,
|
|
1393
|
-
FOUNDATIONS.ETHICAL_CONDUCT,
|
|
1394
|
-
PERSONAS.SUPPORT_AGENT,
|
|
1395
|
-
DOMAINS.GENERAL,
|
|
1396
|
-
TONES.EMPATHETIC,
|
|
1397
|
-
VERBOSITY.NORMAL,
|
|
1398
|
-
FORMATS.STEP_BY_STEP,
|
|
1399
|
-
RESPONSES.ALWAYS_ENGAGE
|
|
1400
|
-
]
|
|
1401
|
-
};
|
|
1402
|
-
|
|
1403
|
-
var PROMPT_LIBRARY = {
|
|
1404
|
-
DOMAINS: DOMAINS,
|
|
1405
|
-
FORMATS: FORMATS,
|
|
1406
|
-
FOUNDATIONS: FOUNDATIONS,
|
|
1407
|
-
LANGUAGES: LANGUAGES,
|
|
1408
|
-
PERSONAS: PERSONAS,
|
|
1409
|
-
PRESETS: PRESETS,
|
|
1410
|
-
RESPONSES: RESPONSES,
|
|
1411
|
-
TONES: TONES,
|
|
1412
|
-
VERBOSITY: VERBOSITY
|
|
1413
|
-
};
|
|
1414
|
-
|
|
1415
|
-
function _class_call_check$2(instance, Constructor) {
|
|
1416
|
-
if (!(instance instanceof Constructor)) {
|
|
1417
|
-
throw new TypeError("Cannot call a class as a function");
|
|
1418
|
-
}
|
|
1419
|
-
}
|
|
1420
|
-
function _defineProperties$2(target, props) {
|
|
1421
|
-
for(var i = 0; i < props.length; i++){
|
|
1422
|
-
var descriptor = props[i];
|
|
1423
|
-
descriptor.enumerable = descriptor.enumerable || false;
|
|
1424
|
-
descriptor.configurable = true;
|
|
1425
|
-
if ("value" in descriptor) descriptor.writable = true;
|
|
1426
|
-
Object.defineProperty(target, descriptor.key, descriptor);
|
|
1427
|
-
}
|
|
1428
|
-
}
|
|
1429
|
-
function _create_class$2(Constructor, protoProps, staticProps) {
|
|
1430
|
-
if (protoProps) _defineProperties$2(Constructor.prototype, protoProps);
|
|
1431
|
-
return Constructor;
|
|
1432
|
-
}
|
|
1433
|
-
function _define_property$2(obj, key, value) {
|
|
1434
|
-
if (key in obj) {
|
|
1435
|
-
Object.defineProperty(obj, key, {
|
|
1436
|
-
value: value,
|
|
1437
|
-
enumerable: true,
|
|
1438
|
-
configurable: true,
|
|
1439
|
-
writable: true
|
|
1440
|
-
});
|
|
1441
|
-
} else {
|
|
1442
|
-
obj[key] = value;
|
|
1443
|
-
}
|
|
1444
|
-
return obj;
|
|
1445
|
-
}
|
|
1446
|
-
/**
|
|
1447
|
-
* System prompt adapter that generates a system prompt from a list of strings
|
|
1448
|
-
*/ var SystemPromptAdapter = /*#__PURE__*/ function() {
|
|
1449
|
-
function SystemPromptAdapter() {
|
|
1450
|
-
for(var _len = arguments.length, prompts = new Array(_len), _key = 0; _key < _len; _key++){
|
|
1451
|
-
prompts[_key] = arguments[_key];
|
|
1452
|
-
}
|
|
1453
|
-
_class_call_check$2(this, SystemPromptAdapter);
|
|
1454
|
-
_define_property$2(this, "finalPrompt", void 0);
|
|
1455
|
-
var flattenedPrompts = prompts.flat();
|
|
1456
|
-
this.finalPrompt = flattenedPrompts.join('\n\n');
|
|
1457
|
-
}
|
|
1458
|
-
_create_class$2(SystemPromptAdapter, [
|
|
1459
|
-
{
|
|
1460
|
-
key: "generate",
|
|
1461
|
-
value: function generate() {
|
|
1462
|
-
return this.finalPrompt;
|
|
1463
|
-
}
|
|
1464
|
-
}
|
|
1465
|
-
]);
|
|
1466
|
-
return SystemPromptAdapter;
|
|
1467
|
-
}();
|
|
1468
|
-
|
|
1469
|
-
function _class_call_check$1(instance, Constructor) {
|
|
1470
|
-
if (!(instance instanceof Constructor)) {
|
|
1471
|
-
throw new TypeError("Cannot call a class as a function");
|
|
1472
|
-
}
|
|
1473
|
-
}
|
|
1474
|
-
function _defineProperties$1(target, props) {
|
|
1475
|
-
for(var i = 0; i < props.length; i++){
|
|
1476
|
-
var descriptor = props[i];
|
|
1477
|
-
descriptor.enumerable = descriptor.enumerable || false;
|
|
1478
|
-
descriptor.configurable = true;
|
|
1479
|
-
if ("value" in descriptor) descriptor.writable = true;
|
|
1480
|
-
Object.defineProperty(target, descriptor.key, descriptor);
|
|
1481
|
-
}
|
|
1482
|
-
}
|
|
1483
|
-
function _create_class$1(Constructor, protoProps, staticProps) {
|
|
1484
|
-
if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
|
|
1485
|
-
return Constructor;
|
|
1486
|
-
}
|
|
1487
|
-
function _define_property$1(obj, key, value) {
|
|
1488
|
-
if (key in obj) {
|
|
1489
|
-
Object.defineProperty(obj, key, {
|
|
1490
|
-
value: value,
|
|
1491
|
-
enumerable: true,
|
|
1492
|
-
configurable: true,
|
|
1493
|
-
writable: true
|
|
1494
|
-
});
|
|
1495
|
-
} else {
|
|
1496
|
-
obj[key] = value;
|
|
1497
|
-
}
|
|
1498
|
-
return obj;
|
|
1499
|
-
}
|
|
1500
|
-
/**
|
|
1501
|
-
* User prompt adapter that generates a user prompt from a list of strings
|
|
1502
|
-
*/ var UserPromptAdapter = /*#__PURE__*/ function() {
|
|
1503
|
-
function UserPromptAdapter() {
|
|
1504
|
-
for(var _len = arguments.length, prompts = new Array(_len), _key = 0; _key < _len; _key++){
|
|
1505
|
-
prompts[_key] = arguments[_key];
|
|
1506
|
-
}
|
|
1507
|
-
_class_call_check$1(this, UserPromptAdapter);
|
|
1508
|
-
_define_property$1(this, "finalPrompt", void 0);
|
|
1509
|
-
var flattenedPrompts = prompts.flat();
|
|
1510
|
-
this.finalPrompt = flattenedPrompts.join('\n\n');
|
|
1511
|
-
}
|
|
1512
|
-
_create_class$1(UserPromptAdapter, [
|
|
1513
|
-
{
|
|
1514
|
-
key: "generate",
|
|
1515
|
-
value: function generate() {
|
|
1516
|
-
return this.finalPrompt;
|
|
1517
|
-
}
|
|
823
|
+
}));
|
|
1518
824
|
}
|
|
1519
|
-
]);
|
|
1520
|
-
return UserPromptAdapter;
|
|
1521
|
-
}();
|
|
1522
|
-
|
|
1523
|
-
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
1524
|
-
try {
|
|
1525
|
-
var info = gen[key](arg);
|
|
1526
|
-
var value = info.value;
|
|
1527
|
-
} catch (error) {
|
|
1528
|
-
reject(error);
|
|
1529
|
-
return;
|
|
1530
|
-
}
|
|
1531
|
-
if (info.done) {
|
|
1532
|
-
resolve(value);
|
|
1533
|
-
} else {
|
|
1534
|
-
Promise.resolve(value).then(_next, _throw);
|
|
1535
|
-
}
|
|
1536
|
-
}
|
|
1537
|
-
function _async_to_generator(fn) {
|
|
1538
|
-
return function() {
|
|
1539
|
-
var self = this, args = arguments;
|
|
1540
|
-
return new Promise(function(resolve, reject) {
|
|
1541
|
-
var gen = fn.apply(self, args);
|
|
1542
|
-
function _next(value) {
|
|
1543
|
-
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
|
|
1544
|
-
}
|
|
1545
|
-
function _throw(err) {
|
|
1546
|
-
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
|
|
1547
|
-
}
|
|
1548
|
-
_next(undefined);
|
|
1549
|
-
});
|
|
1550
825
|
};
|
|
1551
826
|
}
|
|
1552
|
-
function _class_call_check(instance, Constructor) {
|
|
1553
|
-
if (!(instance instanceof Constructor)) {
|
|
1554
|
-
throw new TypeError("Cannot call a class as a function");
|
|
1555
|
-
}
|
|
1556
|
-
}
|
|
1557
|
-
function _defineProperties(target, props) {
|
|
1558
|
-
for(var i = 0; i < props.length; i++){
|
|
1559
|
-
var descriptor = props[i];
|
|
1560
|
-
descriptor.enumerable = descriptor.enumerable || false;
|
|
1561
|
-
descriptor.configurable = true;
|
|
1562
|
-
if ("value" in descriptor) descriptor.writable = true;
|
|
1563
|
-
Object.defineProperty(target, descriptor.key, descriptor);
|
|
1564
|
-
}
|
|
1565
|
-
}
|
|
1566
|
-
function _create_class(Constructor, protoProps, staticProps) {
|
|
1567
|
-
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
|
|
1568
|
-
return Constructor;
|
|
1569
|
-
}
|
|
1570
|
-
function _define_property(obj, key, value) {
|
|
1571
|
-
if (key in obj) {
|
|
1572
|
-
Object.defineProperty(obj, key, {
|
|
1573
|
-
value: value,
|
|
1574
|
-
enumerable: true,
|
|
1575
|
-
configurable: true,
|
|
1576
|
-
writable: true
|
|
1577
|
-
});
|
|
1578
|
-
} else {
|
|
1579
|
-
obj[key] = value;
|
|
1580
|
-
}
|
|
1581
|
-
return obj;
|
|
1582
|
-
}
|
|
1583
|
-
function _instanceof(left, right) {
|
|
1584
|
-
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
1585
|
-
return !!right[Symbol.hasInstance](left);
|
|
1586
|
-
} else {
|
|
1587
|
-
return left instanceof right;
|
|
1588
|
-
}
|
|
1589
|
-
}
|
|
1590
|
-
function _ts_generator(thisArg, body) {
|
|
1591
|
-
var f, y, t, _ = {
|
|
1592
|
-
label: 0,
|
|
1593
|
-
sent: function() {
|
|
1594
|
-
if (t[0] & 1) throw t[1];
|
|
1595
|
-
return t[1];
|
|
1596
|
-
},
|
|
1597
|
-
trys: [],
|
|
1598
|
-
ops: []
|
|
1599
|
-
}, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
1600
|
-
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
|
|
1601
|
-
return this;
|
|
1602
|
-
}), g;
|
|
1603
|
-
function verb(n) {
|
|
1604
|
-
return function(v) {
|
|
1605
|
-
return step([
|
|
1606
|
-
n,
|
|
1607
|
-
v
|
|
1608
|
-
]);
|
|
1609
|
-
};
|
|
1610
|
-
}
|
|
1611
|
-
function step(op) {
|
|
1612
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
1613
|
-
while(g && (g = 0, op[0] && (_ = 0)), _)try {
|
|
1614
|
-
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
1615
|
-
if (y = 0, t) op = [
|
|
1616
|
-
op[0] & 2,
|
|
1617
|
-
t.value
|
|
1618
|
-
];
|
|
1619
|
-
switch(op[0]){
|
|
1620
|
-
case 0:
|
|
1621
|
-
case 1:
|
|
1622
|
-
t = op;
|
|
1623
|
-
break;
|
|
1624
|
-
case 4:
|
|
1625
|
-
_.label++;
|
|
1626
|
-
return {
|
|
1627
|
-
value: op[1],
|
|
1628
|
-
done: false
|
|
1629
|
-
};
|
|
1630
|
-
case 5:
|
|
1631
|
-
_.label++;
|
|
1632
|
-
y = op[1];
|
|
1633
|
-
op = [
|
|
1634
|
-
0
|
|
1635
|
-
];
|
|
1636
|
-
continue;
|
|
1637
|
-
case 7:
|
|
1638
|
-
op = _.ops.pop();
|
|
1639
|
-
_.trys.pop();
|
|
1640
|
-
continue;
|
|
1641
|
-
default:
|
|
1642
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
|
|
1643
|
-
_ = 0;
|
|
1644
|
-
continue;
|
|
1645
|
-
}
|
|
1646
|
-
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
|
|
1647
|
-
_.label = op[1];
|
|
1648
|
-
break;
|
|
1649
|
-
}
|
|
1650
|
-
if (op[0] === 6 && _.label < t[1]) {
|
|
1651
|
-
_.label = t[1];
|
|
1652
|
-
t = op;
|
|
1653
|
-
break;
|
|
1654
|
-
}
|
|
1655
|
-
if (t && _.label < t[2]) {
|
|
1656
|
-
_.label = t[2];
|
|
1657
|
-
_.ops.push(op);
|
|
1658
|
-
break;
|
|
1659
|
-
}
|
|
1660
|
-
if (t[2]) _.ops.pop();
|
|
1661
|
-
_.trys.pop();
|
|
1662
|
-
continue;
|
|
1663
|
-
}
|
|
1664
|
-
op = body.call(thisArg, _);
|
|
1665
|
-
} catch (e) {
|
|
1666
|
-
op = [
|
|
1667
|
-
6,
|
|
1668
|
-
e
|
|
1669
|
-
];
|
|
1670
|
-
y = 0;
|
|
1671
|
-
} finally{
|
|
1672
|
-
f = t = 0;
|
|
1673
|
-
}
|
|
1674
|
-
if (op[0] & 5) throw op[1];
|
|
1675
|
-
return {
|
|
1676
|
-
value: op[0] ? op[1] : void 0,
|
|
1677
|
-
done: true
|
|
1678
|
-
};
|
|
1679
|
-
}
|
|
1680
|
-
}
|
|
1681
|
-
/**
|
|
1682
|
-
* Safe tool adapter that provides error handling and logging for LangChain tools
|
|
1683
|
-
*/ var SafeToolAdapter = /*#__PURE__*/ function() {
|
|
1684
|
-
function SafeToolAdapter(config) {
|
|
1685
|
-
var options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
|
|
1686
|
-
_class_call_check(this, SafeToolAdapter);
|
|
1687
|
-
_define_property(this, "config", void 0);
|
|
1688
|
-
_define_property(this, "options", void 0);
|
|
1689
|
-
_define_property(this, "dynamicTool", void 0);
|
|
1690
|
-
this.config = config;
|
|
1691
|
-
this.options = options;
|
|
1692
|
-
var logger = options.logger, schema = options.schema;
|
|
1693
|
-
if (schema) {
|
|
1694
|
-
// Use DynamicStructuredTool for parameterized tools
|
|
1695
|
-
this.dynamicTool = new tools.DynamicStructuredTool({
|
|
1696
|
-
description: config.description,
|
|
1697
|
-
func: function(args) {
|
|
1698
|
-
return _async_to_generator(function() {
|
|
1699
|
-
var error, errorMessage;
|
|
1700
|
-
return _ts_generator(this, function(_state) {
|
|
1701
|
-
switch(_state.label){
|
|
1702
|
-
case 0:
|
|
1703
|
-
_state.trys.push([
|
|
1704
|
-
0,
|
|
1705
|
-
2,
|
|
1706
|
-
,
|
|
1707
|
-
3
|
|
1708
|
-
]);
|
|
1709
|
-
return [
|
|
1710
|
-
4,
|
|
1711
|
-
config.execute(args)
|
|
1712
|
-
];
|
|
1713
|
-
case 1:
|
|
1714
|
-
return [
|
|
1715
|
-
2,
|
|
1716
|
-
_state.sent()
|
|
1717
|
-
];
|
|
1718
|
-
case 2:
|
|
1719
|
-
error = _state.sent();
|
|
1720
|
-
errorMessage = _instanceof(error, Error) ? error.message : String(error);
|
|
1721
|
-
logger === null || logger === void 0 ? void 0 : logger.error("Unexpected error in ".concat(config.name), {
|
|
1722
|
-
args: args,
|
|
1723
|
-
error: errorMessage,
|
|
1724
|
-
toolName: config.name
|
|
1725
|
-
});
|
|
1726
|
-
return [
|
|
1727
|
-
2,
|
|
1728
|
-
"Tool ".concat(config.name, " failed to execute")
|
|
1729
|
-
];
|
|
1730
|
-
case 3:
|
|
1731
|
-
return [
|
|
1732
|
-
2
|
|
1733
|
-
];
|
|
1734
|
-
}
|
|
1735
|
-
});
|
|
1736
|
-
})();
|
|
1737
|
-
},
|
|
1738
|
-
name: config.name,
|
|
1739
|
-
schema: schema
|
|
1740
|
-
});
|
|
1741
|
-
} else {
|
|
1742
|
-
// Use DynamicTool for simple tools
|
|
1743
|
-
this.dynamicTool = new tools.DynamicTool({
|
|
1744
|
-
description: config.description,
|
|
1745
|
-
func: function() {
|
|
1746
|
-
return _async_to_generator(function() {
|
|
1747
|
-
var error, errorMessage;
|
|
1748
|
-
return _ts_generator(this, function(_state) {
|
|
1749
|
-
switch(_state.label){
|
|
1750
|
-
case 0:
|
|
1751
|
-
_state.trys.push([
|
|
1752
|
-
0,
|
|
1753
|
-
2,
|
|
1754
|
-
,
|
|
1755
|
-
3
|
|
1756
|
-
]);
|
|
1757
|
-
return [
|
|
1758
|
-
4,
|
|
1759
|
-
config.execute()
|
|
1760
|
-
];
|
|
1761
|
-
case 1:
|
|
1762
|
-
return [
|
|
1763
|
-
2,
|
|
1764
|
-
_state.sent()
|
|
1765
|
-
];
|
|
1766
|
-
case 2:
|
|
1767
|
-
error = _state.sent();
|
|
1768
|
-
errorMessage = _instanceof(error, Error) ? error.message : String(error);
|
|
1769
|
-
logger === null || logger === void 0 ? void 0 : logger.error("Unexpected error in ".concat(config.name), {
|
|
1770
|
-
error: errorMessage,
|
|
1771
|
-
toolName: config.name
|
|
1772
|
-
});
|
|
1773
|
-
return [
|
|
1774
|
-
2,
|
|
1775
|
-
"Tool ".concat(config.name, " failed to execute")
|
|
1776
|
-
];
|
|
1777
|
-
case 3:
|
|
1778
|
-
return [
|
|
1779
|
-
2
|
|
1780
|
-
];
|
|
1781
|
-
}
|
|
1782
|
-
});
|
|
1783
|
-
})();
|
|
1784
|
-
},
|
|
1785
|
-
name: config.name
|
|
1786
|
-
});
|
|
1787
|
-
}
|
|
1788
|
-
}
|
|
1789
|
-
_create_class(SafeToolAdapter, [
|
|
1790
|
-
{
|
|
1791
|
-
/**
|
|
1792
|
-
* Get the underlying LangChain DynamicTool instance
|
|
1793
|
-
*/ key: "getDynamicTool",
|
|
1794
|
-
value: function getDynamicTool() {
|
|
1795
|
-
return this.dynamicTool;
|
|
1796
|
-
}
|
|
1797
|
-
}
|
|
1798
|
-
]);
|
|
1799
|
-
return SafeToolAdapter;
|
|
1800
|
-
}();
|
|
1801
827
|
|
|
1802
|
-
exports.
|
|
1803
|
-
exports.
|
|
1804
|
-
exports.
|
|
1805
|
-
exports.
|
|
1806
|
-
exports.
|
|
1807
|
-
exports.
|
|
1808
|
-
exports.SystemPromptAdapter = SystemPromptAdapter;
|
|
1809
|
-
exports.UserPromptAdapter = UserPromptAdapter;
|
|
828
|
+
exports.ParseObjectError = ParseObjectError;
|
|
829
|
+
exports.createLoggingMiddleware = createLoggingMiddleware;
|
|
830
|
+
exports.createOpenRouterProvider = createOpenRouterProvider;
|
|
831
|
+
exports.createSchemaPrompt = createSchemaPrompt;
|
|
832
|
+
exports.parseObject = parseObject;
|
|
833
|
+
exports.parseText = parseText;
|