agentic-api 1.0.1
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 +198 -0
- package/dist/src/agents/authentication.d.ts +6 -0
- package/dist/src/agents/authentication.js +216 -0
- package/dist/src/agents/digestor.d.ts +7 -0
- package/dist/src/agents/digestor.js +60 -0
- package/dist/src/agents/memory.d.ts +0 -0
- package/dist/src/agents/memory.js +1 -0
- package/dist/src/agents/prompts.d.ts +7 -0
- package/dist/src/agents/prompts.js +302 -0
- package/dist/src/agents/semantic.d.ts +4 -0
- package/dist/src/agents/semantic.js +20 -0
- package/dist/src/agents/simpleExample.d.ts +3 -0
- package/dist/src/agents/simpleExample.js +38 -0
- package/dist/src/agents/system-review.d.ts +5 -0
- package/dist/src/agents/system-review.js +181 -0
- package/dist/src/agents/system.d.ts +4 -0
- package/dist/src/agents/system.js +21 -0
- package/dist/src/agents/systemReview.d.ts +4 -0
- package/dist/src/agents/systemReview.js +22 -0
- package/dist/src/execute.d.ts +42 -0
- package/dist/src/execute.js +289 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +32 -0
- package/dist/src/princing.openai.d.ts +4 -0
- package/dist/src/princing.openai.js +49 -0
- package/dist/src/prompts.d.ts +5 -0
- package/dist/src/prompts.js +136 -0
- package/dist/src/scrapper.d.ts +54 -0
- package/dist/src/scrapper.js +294 -0
- package/dist/src/types.d.ts +126 -0
- package/dist/src/types.js +93 -0
- package/dist/src/utils.d.ts +27 -0
- package/dist/src/utils.js +288 -0
- package/package.json +45 -0
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.extractCaptcha = extractCaptcha;
|
|
7
|
+
exports.callGPTForParsingPDF = callGPTForParsingPDF;
|
|
8
|
+
exports.callGPTForParsingHTML = callGPTForParsingHTML;
|
|
9
|
+
exports.html2markdown = html2markdown;
|
|
10
|
+
exports.pdf2markdown = pdf2markdown;
|
|
11
|
+
const child_process_1 = require("child_process");
|
|
12
|
+
const util_1 = require("util");
|
|
13
|
+
const path_1 = __importDefault(require("path"));
|
|
14
|
+
const fs_1 = __importDefault(require("fs"));
|
|
15
|
+
const jsdom_1 = require("jsdom");
|
|
16
|
+
const readability_1 = require("@mozilla/readability");
|
|
17
|
+
const princing_openai_1 = require("./princing.openai");
|
|
18
|
+
const prompts_1 = require("./prompts");
|
|
19
|
+
const utils_1 = require("./utils");
|
|
20
|
+
// Promisify exec for easier async/await usage
|
|
21
|
+
const execAsync = (0, util_1.promisify)(child_process_1.exec);
|
|
22
|
+
const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
|
|
23
|
+
const randomFile = (ext = '') => {
|
|
24
|
+
const random = () => Math.random() * 1000 | 0;
|
|
25
|
+
return `temp-${random()}-${random()}${ext}`;
|
|
26
|
+
};
|
|
27
|
+
async function extractCaptcha(base64Image, openai) {
|
|
28
|
+
const content = [
|
|
29
|
+
{ type: 'text', text: "Extrais uniquement le nombre" },
|
|
30
|
+
{ type: 'image_url', image_url: { url: `data:image/jpeg;base64,${base64Image}` } },
|
|
31
|
+
];
|
|
32
|
+
// Cost per captcha $0.0000696
|
|
33
|
+
const model = "gpt-4o-mini";
|
|
34
|
+
const response = await openai.chat.completions.create({
|
|
35
|
+
model,
|
|
36
|
+
messages: [{ role: "user", content }],
|
|
37
|
+
max_completion_tokens: 50,
|
|
38
|
+
});
|
|
39
|
+
const cost = (0, princing_openai_1.calculateCost)(model, response.usage);
|
|
40
|
+
// Récupérer la réponse markdown
|
|
41
|
+
const number = response.choices[0].message.content;
|
|
42
|
+
return { number, cost };
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Calls GPT to parse a PDF file and convert it to markdown format.
|
|
46
|
+
*
|
|
47
|
+
* @param {string} inputfile - The name of the PDF file being processed
|
|
48
|
+
* @param {any} pdfData - The extracted content from the PDF file
|
|
49
|
+
* @param {any} openai - The OpenAI client instance
|
|
50
|
+
* @param {any[]} links - Optional array of links extracted from the PDF to be integrated into the markdown
|
|
51
|
+
* @returns {Promise<{markdown: string, cost: number}>} - The parsed markdown content and the cost of the API call
|
|
52
|
+
*/
|
|
53
|
+
async function callGPTForParsingPDF(inputfile, pdfData, openai, links = []) {
|
|
54
|
+
// Convertir le contenu en chaîne de caractères (attention à la taille potentielle !)
|
|
55
|
+
const pdfDataAsString = JSON.stringify(pdfData, null, 2);
|
|
56
|
+
// Format: YYYY-MM-DD
|
|
57
|
+
const today = new Date().toISOString().substring(0, 10);
|
|
58
|
+
const linkLabel = ' une liste de liens que tu dois placer dans le document. Si le libellé d\'un lien correspond à un texte existant dans le document, intègre le lien directement dans le texte. Sinon, place ces liens sous forme de liste à puces dans une section annexe (# Références externes) à la fin du document.';
|
|
59
|
+
const linkPrefix = linkLabel + links.reduce((acc, link) => {
|
|
60
|
+
return acc + `- [${link.text}](${link.href})\n`;
|
|
61
|
+
}, '');
|
|
62
|
+
// Créer le prompt pour décrire la tâche au LLM
|
|
63
|
+
const messages = [
|
|
64
|
+
{ role: "system",
|
|
65
|
+
content: prompts_1.textToMarkdownPrompt },
|
|
66
|
+
{ role: "user",
|
|
67
|
+
content: `Nous sommes le ${today}, voici le nom du document "${inputfile}", et ${linkPrefix}` },
|
|
68
|
+
{ role: "user",
|
|
69
|
+
content: `Voici le document, pour commencer, tu DOIS extrais uniquement la structure (titres et sous-titres) selon les instructions et sans les contenus détaillés:\n\n${pdfDataAsString}` }
|
|
70
|
+
];
|
|
71
|
+
// WARNING: o3-mini is buggy with "Marche à suivre nouveau bail.pdf"
|
|
72
|
+
const model = "o3-mini"; // "gpt-4o-mini";
|
|
73
|
+
let response = await openai.chat.completions.create({
|
|
74
|
+
model: model,
|
|
75
|
+
messages,
|
|
76
|
+
max_completion_tokens: 15192,
|
|
77
|
+
reasoning_effort: "low",
|
|
78
|
+
stop: "|<|james|>|"
|
|
79
|
+
});
|
|
80
|
+
// response_format: { type: "json_object" }
|
|
81
|
+
let cost = (0, princing_openai_1.calculateCost)(model, response.usage);
|
|
82
|
+
console.log(`Markdown 💰 cost: ${cost}`);
|
|
83
|
+
messages.push({
|
|
84
|
+
role: "user",
|
|
85
|
+
content: `Maintenant génère le contenu Markdown détaillé et exhaustif correspondant à chaque section avec les liens intégrés correctement.`
|
|
86
|
+
});
|
|
87
|
+
response = await openai.chat.completions.create({
|
|
88
|
+
model: model,
|
|
89
|
+
messages,
|
|
90
|
+
max_completion_tokens: 15192,
|
|
91
|
+
reasoning_effort: "low",
|
|
92
|
+
stop: "|<|james|>|"
|
|
93
|
+
});
|
|
94
|
+
// Récupérer la réponse markdown
|
|
95
|
+
let markdown = response.choices[0].message.content;
|
|
96
|
+
cost += (0, princing_openai_1.calculateCost)(model, response.usage);
|
|
97
|
+
//
|
|
98
|
+
// add a regex to extract the markdown content between <thinking></thinking> tags
|
|
99
|
+
let markdownWithoutThinking = markdown.replace(/<thinking>[\s\S]*?<\/thinking>/g, '');
|
|
100
|
+
// const hragPrompt = await extractHRAGSections(markdownWithoutThinking, openai);
|
|
101
|
+
// messages.push({
|
|
102
|
+
// role: "user",
|
|
103
|
+
// content: hragPrompt
|
|
104
|
+
// });
|
|
105
|
+
// response = await openai.chat.completions.create({
|
|
106
|
+
// model: model,
|
|
107
|
+
// messages,
|
|
108
|
+
// max_completion_tokens: 15192,
|
|
109
|
+
// reasoning_effort:"low",
|
|
110
|
+
// stop:"|<|james|>|"
|
|
111
|
+
// });
|
|
112
|
+
// // Récupérer la réponse markdown
|
|
113
|
+
// markdown = response.choices[0].message.content;
|
|
114
|
+
// cost += calculateCost(model, response.usage);
|
|
115
|
+
// //
|
|
116
|
+
// // add a regex to extract the markdown content between <thinking></thinking> tags
|
|
117
|
+
// markdownWithoutThinking = markdown.replace(/<thinking>[\s\S]*?<\/thinking>/g, '');
|
|
118
|
+
return { markdown: markdownWithoutThinking, cost };
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Extracts hyperlinks from a PDF file by converting it to HTML and parsing the links.
|
|
122
|
+
*
|
|
123
|
+
* @param {string} pdfPath - The file path to the PDF document to extract links from
|
|
124
|
+
* @param {string} output - The directory output where temporary files will be created
|
|
125
|
+
* @returns {Promise<Array<{text: string, href: string}>>} - A promise that resolves to an array of link objects,
|
|
126
|
+
* each containing the link text and href attributes
|
|
127
|
+
*/
|
|
128
|
+
async function extractLinksFromPDF(pdfPath, output) {
|
|
129
|
+
const tempOut = path_1.default.join(output, `${randomFile()}`);
|
|
130
|
+
try {
|
|
131
|
+
// STEP 2: Convert the cleaned PDF to XML using pdftohtml.
|
|
132
|
+
// La commande génère un fichier XML à partir du PDF nettoyé.
|
|
133
|
+
const pdftohtmlCommand = `pdftohtml -s -nodrm -c "${pdfPath}" "${tempOut}"`;
|
|
134
|
+
await execAsync(pdftohtmlCommand);
|
|
135
|
+
const html = fs_1.default.readFileSync(tempOut + '-html.html', "utf8");
|
|
136
|
+
const dom = new jsdom_1.JSDOM(html);
|
|
137
|
+
const links = Array.from(dom.window.document.querySelectorAll('a')).map(link => ({
|
|
138
|
+
text: link.textContent?.trim() || link.href,
|
|
139
|
+
href: link.href
|
|
140
|
+
}));
|
|
141
|
+
process.stdout.write("Extracting links: " + links.length + " ");
|
|
142
|
+
return links;
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
console.error('❌ Error extracting links from PDF:', error);
|
|
146
|
+
return [];
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
if (fs_1.default.existsSync(tempOut + '-html.html')) {
|
|
150
|
+
fs_1.default.unlinkSync(tempOut + '-html.html');
|
|
151
|
+
// Clean up any PNG files that might have been generated
|
|
152
|
+
const pngFiles = fs_1.default.readdirSync(path_1.default.dirname(tempOut))
|
|
153
|
+
.filter(file => file.startsWith(path_1.default.basename(tempOut)) && file.endsWith('.png'));
|
|
154
|
+
for (const pngFile of pngFiles) {
|
|
155
|
+
const pngPath = path_1.default.join(path_1.default.dirname(tempOut), pngFile);
|
|
156
|
+
if (fs_1.default.existsSync(pngPath))
|
|
157
|
+
fs_1.default.unlinkSync(pngPath);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Convertit un document HTML en markdown en appelant le modèle GPT (ex: gpt-4o-mini)
|
|
164
|
+
* pour analyser et reformater le document.
|
|
165
|
+
*
|
|
166
|
+
* @param {any} htmlData - Le document HTML à transformer en markdown.
|
|
167
|
+
* @param {any} openai - L'instance OpenAI configurée pour appeler l'API.
|
|
168
|
+
* @param {boolean} simple - Si true, utilise un prompt simplifié.
|
|
169
|
+
* @returns {Promise<Object>} - Le contenu markdown structuré créé par le modèle LLM.
|
|
170
|
+
*/
|
|
171
|
+
async function callGPTForParsingHTML(html, openai) {
|
|
172
|
+
const htmlDataAsString = html;
|
|
173
|
+
// Créer le prompt pour décrire la tâche au LLM
|
|
174
|
+
const messages = [
|
|
175
|
+
{
|
|
176
|
+
role: "system",
|
|
177
|
+
content: prompts_1.htmlToMarkdownPrompt
|
|
178
|
+
},
|
|
179
|
+
{
|
|
180
|
+
role: "user",
|
|
181
|
+
content: `Voici le document HTML à transformer en markdown : \n${htmlDataAsString}`
|
|
182
|
+
}
|
|
183
|
+
];
|
|
184
|
+
// Appel à l'API ChatCompletion
|
|
185
|
+
const response = await openai.chat.completions.create({
|
|
186
|
+
model: "gpt-4o-mini",
|
|
187
|
+
messages,
|
|
188
|
+
max_completion_tokens: 15192,
|
|
189
|
+
temperature: 0,
|
|
190
|
+
frequency_penalty: 0.0,
|
|
191
|
+
presence_penalty: 0.0,
|
|
192
|
+
stop: "|<|james|>|"
|
|
193
|
+
});
|
|
194
|
+
const cost = (0, princing_openai_1.calculateCost)("gpt-4o-mini", response.usage);
|
|
195
|
+
console.log(`Markdown 💰 cost: ${cost}`);
|
|
196
|
+
// Récupérer la réponse markdown
|
|
197
|
+
const markdown = response.choices[0].message.content;
|
|
198
|
+
if (!markdown)
|
|
199
|
+
throw new Error("No markdown found");
|
|
200
|
+
// Extraction et suppression des balises <thinking></thinking>
|
|
201
|
+
const markdownWithoutThinking = markdown.replace(/<thinking>[\s\S]*?<\/thinking>/g, '');
|
|
202
|
+
return markdownWithoutThinking;
|
|
203
|
+
}
|
|
204
|
+
function cleanHTML(html) {
|
|
205
|
+
const dom = new jsdom_1.JSDOM(html);
|
|
206
|
+
// Instancie Readability avec le document
|
|
207
|
+
const reader = new readability_1.Readability(dom.window.document);
|
|
208
|
+
const article = reader.parse();
|
|
209
|
+
return article?.content || '';
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Parses an HTML file and converts it to markdown using GPT.
|
|
213
|
+
*
|
|
214
|
+
* @param {string} output - The directory path where the output markdown file will be saved.
|
|
215
|
+
* @param {string} file - The path to the HTML file to be parsed.
|
|
216
|
+
* @param {string} service - The service name used as part of the output filename output.
|
|
217
|
+
* @param {any} openai - The OpenAI instance to use for the GPT API calls.
|
|
218
|
+
* @returns {Promise<{markdown: string, cost: number}>} - The generated markdown content and the cost of the GPT API call.
|
|
219
|
+
*/
|
|
220
|
+
async function html2markdown(output, file, service, openai) {
|
|
221
|
+
const filename = (0, utils_1.slug)(path_1.default.basename(file, path_1.default.extname(file)));
|
|
222
|
+
const htmlraw = fs_1.default.readFileSync(file, "utf8");
|
|
223
|
+
const html = cleanHTML(htmlraw);
|
|
224
|
+
const outputfile = html.indexOf('Please sign in') > -1 ? 'unauthorized-' : (service.toLocaleLowerCase() + '-');
|
|
225
|
+
const { markdown, cost } = await callGPTForParsingPDF(file, html, openai);
|
|
226
|
+
fs_1.default.writeFileSync(path_1.default.join(output, `${outputfile + filename}.md`), markdown);
|
|
227
|
+
return { markdown, cost };
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Parse un PDF en effectuant :
|
|
231
|
+
* 1. Le nettoyage du PDF avec Ghostscript.
|
|
232
|
+
* 2. Sa conversion en XML via pdftohtml.
|
|
233
|
+
* 3. (Optionnellement) Le passage du contenu converti au modèle GPT pour analyser la structure.
|
|
234
|
+
*
|
|
235
|
+
* @param {string} file - Chemin vers le fichier PDF à analyser.
|
|
236
|
+
* @param {any} openai - L'instance configurée pour appeler l'API OpenAI.
|
|
237
|
+
* @returns {Promise<any>} - Le markdown structuré (issue de GPT) ou tout autre traitement souhaité.
|
|
238
|
+
*/
|
|
239
|
+
async function pdf2markdown(output, file, service, openai) {
|
|
240
|
+
const filename = (0, utils_1.slug)(path_1.default.basename(file, path_1.default.extname(file)));
|
|
241
|
+
// Créez des noms de fichiers temporaires pour le PDF nettoyé et le XML généré.
|
|
242
|
+
const tempPdf = path_1.default.join(output, `cleaned-${randomFile()}.pdf`);
|
|
243
|
+
const tempOut = path_1.default.join(output, `${filename}.txt`);
|
|
244
|
+
//
|
|
245
|
+
// generated output path
|
|
246
|
+
const outputPath = path_1.default.join(output, `${service.toLocaleLowerCase()}-${filename}.md`);
|
|
247
|
+
try {
|
|
248
|
+
//
|
|
249
|
+
// replace pdftotext with python script PyMuPDF
|
|
250
|
+
// Ca ne marche pas mieux que pdftotext
|
|
251
|
+
// const { stdout } = await execFileAsync("python3", ["./bin/extract_text_with_links.py", file]);
|
|
252
|
+
// const { text, links } = JSON.parse(stdout);
|
|
253
|
+
await execAsync(`pdftotext -nodiag -nopgbrk "${file}" "${outputPath}"`);
|
|
254
|
+
const links = await extractLinksFromPDF(file, output);
|
|
255
|
+
const text = fs_1.default.readFileSync(outputPath, "utf8");
|
|
256
|
+
const { markdown, cost } = await callGPTForParsingPDF(file, text, openai, links);
|
|
257
|
+
fs_1.default.writeFileSync(outputPath, markdown);
|
|
258
|
+
return { markdown, cost };
|
|
259
|
+
/**
|
|
260
|
+
|
|
261
|
+
// STEP 1: Clean the PDF using Ghostscript.
|
|
262
|
+
// La commande utilise -o pour spécifier le fichier de sortie et applique des options de mise en forme.
|
|
263
|
+
const gsCommand = `gs -o "${tempPdf}" -sDEVICE=pdfwrite -dFIXEDMEDIA -dDEVICEWIDTHPOINTS=595 -dDEVICEHEIGHTPOINTS=752 -dORIGINY=100 -dFILTERVECTOR "${file}"`;
|
|
264
|
+
console.log("Executing Ghostscript command:", gsCommand);
|
|
265
|
+
await execAsync(gsCommand);
|
|
266
|
+
|
|
267
|
+
// STEP 2: Convert the cleaned PDF to XML using pdftohtml.
|
|
268
|
+
// La commande génère un fichier XML à partir du PDF nettoyé.
|
|
269
|
+
const pdftohtmlCommand = `pdftohtml -xml -nodrm -s -c "${tempPdf}" "${tempOut}"`;
|
|
270
|
+
console.log("Executing pdftohtml command:", pdftohtmlCommand);
|
|
271
|
+
await execAsync(pdftohtmlCommand);
|
|
272
|
+
|
|
273
|
+
// Lecture du contenu XML généré
|
|
274
|
+
const xmlContent = fs.readFileSync(tempOut, "utf8");
|
|
275
|
+
|
|
276
|
+
// (OPTIONNEL) STEP 3: Utilisez GPT pour analyser la structure du contenu XML.
|
|
277
|
+
// Vous pouvez adapter le traitement en fonction du contenu généré par pdftohtml.
|
|
278
|
+
const {markdown,cost} = await callGPTForParsingPDF(file, xmlContent, openai);
|
|
279
|
+
fs.writeFileSync(outputPath, markdown);
|
|
280
|
+
return {markdown,cost}; */
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
console.error("Error during PDF parsing: ", error);
|
|
284
|
+
throw error;
|
|
285
|
+
}
|
|
286
|
+
finally {
|
|
287
|
+
if (fs_1.default.existsSync(tempPdf)) {
|
|
288
|
+
fs_1.default.unlinkSync(tempPdf);
|
|
289
|
+
}
|
|
290
|
+
if (fs_1.default.existsSync(tempOut)) {
|
|
291
|
+
fs_1.default.unlinkSync(tempOut);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { Writable } from "stream";
|
|
2
|
+
export type SessionStatus = "DISCONNECTED" | "CONNECTING" | "CONNECTED";
|
|
3
|
+
export interface ToolParameterProperty {
|
|
4
|
+
type: string;
|
|
5
|
+
description?: string;
|
|
6
|
+
enum?: string[];
|
|
7
|
+
pattern?: string;
|
|
8
|
+
properties?: Record<string, ToolParameterProperty>;
|
|
9
|
+
required?: string[];
|
|
10
|
+
additionalProperties?: boolean;
|
|
11
|
+
items?: ToolParameterProperty;
|
|
12
|
+
}
|
|
13
|
+
export interface ToolParameters {
|
|
14
|
+
type: string;
|
|
15
|
+
properties: Record<string, ToolParameterProperty>;
|
|
16
|
+
required?: string[];
|
|
17
|
+
additionalProperties?: boolean;
|
|
18
|
+
}
|
|
19
|
+
export interface Tool {
|
|
20
|
+
type: "function";
|
|
21
|
+
function: {
|
|
22
|
+
name: string;
|
|
23
|
+
description: string;
|
|
24
|
+
parameters: ToolParameters;
|
|
25
|
+
strict: boolean;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export interface AgentModelMapping {
|
|
29
|
+
[key: string]: string;
|
|
30
|
+
}
|
|
31
|
+
export interface AgentModel {
|
|
32
|
+
model: string;
|
|
33
|
+
temperature: null;
|
|
34
|
+
maxTokens: number;
|
|
35
|
+
topP?: number;
|
|
36
|
+
parallel_tool_calls: boolean;
|
|
37
|
+
frequencyPenalty?: number;
|
|
38
|
+
presencePenalty?: number;
|
|
39
|
+
stop?: string[] | string;
|
|
40
|
+
tool_choice?: "auto" | "none" | "required";
|
|
41
|
+
}
|
|
42
|
+
export interface AgentConfig {
|
|
43
|
+
name: string;
|
|
44
|
+
model?: AgentModel;
|
|
45
|
+
human?: boolean;
|
|
46
|
+
publicDescription: string;
|
|
47
|
+
instructions: string;
|
|
48
|
+
maxSteps?: number;
|
|
49
|
+
tools: Tool[];
|
|
50
|
+
toolLogic?: Record<string, (args: any, session?: AgenticContext) => Promise<any> | any>;
|
|
51
|
+
downstreamAgents?: AgentConfig[] | {
|
|
52
|
+
name: string;
|
|
53
|
+
publicDescription: string;
|
|
54
|
+
human?: boolean;
|
|
55
|
+
}[];
|
|
56
|
+
ready?: boolean;
|
|
57
|
+
}
|
|
58
|
+
export interface UserNano {
|
|
59
|
+
id: string;
|
|
60
|
+
isAnonymous?: boolean;
|
|
61
|
+
role: string;
|
|
62
|
+
}
|
|
63
|
+
export declare abstract class AgenticMemory {
|
|
64
|
+
abstract get currentAgent(): AgentConfig;
|
|
65
|
+
abstract set currentAgent(agent: AgentConfig);
|
|
66
|
+
abstract agents: AgentConfig[];
|
|
67
|
+
abstract messages: any[];
|
|
68
|
+
abstract usage: Usage;
|
|
69
|
+
abstract state?: string;
|
|
70
|
+
}
|
|
71
|
+
export interface AgenticMemorySession {
|
|
72
|
+
state: string;
|
|
73
|
+
user: UserNano;
|
|
74
|
+
currentAgent: string;
|
|
75
|
+
messages: any[];
|
|
76
|
+
usage: Usage;
|
|
77
|
+
}
|
|
78
|
+
export interface AgenticContext {
|
|
79
|
+
memory?: AgenticMemorySession;
|
|
80
|
+
user: UserNano;
|
|
81
|
+
[key: string]: any;
|
|
82
|
+
}
|
|
83
|
+
export declare class AgenticMemoryManager extends AgenticMemory {
|
|
84
|
+
#private;
|
|
85
|
+
constructor(session: {
|
|
86
|
+
memory?: AgenticMemorySession;
|
|
87
|
+
user?: UserNano;
|
|
88
|
+
}, initialAgent: string, agents: AgentConfig[]);
|
|
89
|
+
static createOrLoad(session: {
|
|
90
|
+
memory?: AgenticMemorySession;
|
|
91
|
+
user: UserNano;
|
|
92
|
+
}, agents: any[], initialAgent: string): AgenticMemoryManager;
|
|
93
|
+
get session(): AgenticMemorySession;
|
|
94
|
+
get agents(): AgentConfig[];
|
|
95
|
+
get state(): string;
|
|
96
|
+
set state(state: string);
|
|
97
|
+
get currentAgent(): AgentConfig;
|
|
98
|
+
set currentAgent(agent: AgentConfig);
|
|
99
|
+
get usage(): Usage;
|
|
100
|
+
get messages(): any[];
|
|
101
|
+
set messages(messages: any[]);
|
|
102
|
+
set usage(usage: Usage);
|
|
103
|
+
}
|
|
104
|
+
export type AllAgentConfigsType = Record<string, AgentConfig[]>;
|
|
105
|
+
export interface Usage {
|
|
106
|
+
prompt: number;
|
|
107
|
+
completion: number;
|
|
108
|
+
total: number;
|
|
109
|
+
cost: number;
|
|
110
|
+
}
|
|
111
|
+
export interface Feedback {
|
|
112
|
+
agent: string;
|
|
113
|
+
stdout: Writable;
|
|
114
|
+
description?: string;
|
|
115
|
+
usage: Usage;
|
|
116
|
+
state: string;
|
|
117
|
+
}
|
|
118
|
+
export interface TranscriptItem {
|
|
119
|
+
id: string;
|
|
120
|
+
type: "MESSAGE" | "BREADCRUMB";
|
|
121
|
+
role?: "user" | "assistant";
|
|
122
|
+
title?: string;
|
|
123
|
+
content?: string;
|
|
124
|
+
timestamp: string;
|
|
125
|
+
status: "IN_PROGRESS" | "DONE";
|
|
126
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _AgenticMemoryManager_memory, _AgenticMemoryManager_initialAgent, _AgenticMemoryManager_agents;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.AgenticMemoryManager = exports.AgenticMemory = void 0;
|
|
16
|
+
class AgenticMemory {
|
|
17
|
+
}
|
|
18
|
+
exports.AgenticMemory = AgenticMemory;
|
|
19
|
+
class AgenticMemoryManager extends AgenticMemory {
|
|
20
|
+
constructor(session, initialAgent, agents) {
|
|
21
|
+
super();
|
|
22
|
+
_AgenticMemoryManager_memory.set(this, void 0);
|
|
23
|
+
_AgenticMemoryManager_initialAgent.set(this, void 0);
|
|
24
|
+
_AgenticMemoryManager_agents.set(this, void 0);
|
|
25
|
+
__classPrivateFieldSet(this, _AgenticMemoryManager_initialAgent, initialAgent, "f");
|
|
26
|
+
__classPrivateFieldSet(this, _AgenticMemoryManager_agents, agents, "f");
|
|
27
|
+
//
|
|
28
|
+
// create sessionmemory if not exists
|
|
29
|
+
if (!session.memory) {
|
|
30
|
+
if (!session.user || !session.user.id) {
|
|
31
|
+
throw new Error('User ID is required');
|
|
32
|
+
}
|
|
33
|
+
session.memory = __classPrivateFieldSet(this, _AgenticMemoryManager_memory, {
|
|
34
|
+
state: '',
|
|
35
|
+
user: session.user,
|
|
36
|
+
messages: [],
|
|
37
|
+
currentAgent: initialAgent,
|
|
38
|
+
usage: { prompt: 0, completion: 0, total: 0, cost: 0 }
|
|
39
|
+
}, "f");
|
|
40
|
+
}
|
|
41
|
+
__classPrivateFieldSet(this, _AgenticMemoryManager_memory, session.memory, "f");
|
|
42
|
+
// this.#memory.state = session.memory.state,
|
|
43
|
+
// this.#memory.messages = session.memory.messages,
|
|
44
|
+
// this.#memory.currentAgent = session.memory.currentAgent,
|
|
45
|
+
// this.#memory.usage = session.memory.usage
|
|
46
|
+
}
|
|
47
|
+
//
|
|
48
|
+
// control and bind agent memory for one session
|
|
49
|
+
static createOrLoad(session, agents, initialAgent) {
|
|
50
|
+
return new AgenticMemoryManager(session, initialAgent, agents);
|
|
51
|
+
}
|
|
52
|
+
//
|
|
53
|
+
// get serializable session memory
|
|
54
|
+
get session() {
|
|
55
|
+
return {
|
|
56
|
+
state: __classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").state,
|
|
57
|
+
user: __classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").user,
|
|
58
|
+
messages: __classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").messages,
|
|
59
|
+
currentAgent: __classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").currentAgent,
|
|
60
|
+
usage: __classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").usage,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
get agents() {
|
|
64
|
+
return __classPrivateFieldGet(this, _AgenticMemoryManager_agents, "f");
|
|
65
|
+
}
|
|
66
|
+
get state() {
|
|
67
|
+
return __classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").state;
|
|
68
|
+
}
|
|
69
|
+
set state(state) {
|
|
70
|
+
__classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").state = state;
|
|
71
|
+
}
|
|
72
|
+
get currentAgent() {
|
|
73
|
+
const name = __classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").currentAgent || __classPrivateFieldGet(this, _AgenticMemoryManager_initialAgent, "f");
|
|
74
|
+
return __classPrivateFieldGet(this, _AgenticMemoryManager_agents, "f").find((a) => a.name == name);
|
|
75
|
+
}
|
|
76
|
+
set currentAgent(agent) {
|
|
77
|
+
__classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").currentAgent = agent.name;
|
|
78
|
+
}
|
|
79
|
+
get usage() {
|
|
80
|
+
return __classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").usage;
|
|
81
|
+
}
|
|
82
|
+
get messages() {
|
|
83
|
+
return __classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").messages;
|
|
84
|
+
}
|
|
85
|
+
set messages(messages) {
|
|
86
|
+
__classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").messages = messages;
|
|
87
|
+
}
|
|
88
|
+
set usage(usage) {
|
|
89
|
+
__classPrivateFieldGet(this, _AgenticMemoryManager_memory, "f").usage = usage;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
exports.AgenticMemoryManager = AgenticMemoryManager;
|
|
93
|
+
_AgenticMemoryManager_memory = new WeakMap(), _AgenticMemoryManager_initialAgent = new WeakMap(), _AgenticMemoryManager_agents = new WeakMap();
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { ParsedFunctionToolCall } from "openai/resources/beta/chat/completions";
|
|
2
|
+
import { AgentConfig, AgenticContext, AgenticMemory } from "./types";
|
|
3
|
+
import OpenAI from "openai";
|
|
4
|
+
export declare const openaiInstance: (openai?: OpenAI) => any;
|
|
5
|
+
export declare const slug: (text: string) => string;
|
|
6
|
+
/**
|
|
7
|
+
* This defines and adds "transferAgents" tool dynamically based on the specified downstreamAgents on each agent.
|
|
8
|
+
*/
|
|
9
|
+
export declare function injectTransferTools(agentDefs: AgentConfig[]): AgentConfig[];
|
|
10
|
+
export declare function handleTransferCall(memory: AgenticMemory, functionCallParams: ParsedFunctionToolCall, session: AgenticContext): Promise<any>;
|
|
11
|
+
/**
|
|
12
|
+
* Calls the system review agent to analyze a prompt
|
|
13
|
+
*
|
|
14
|
+
* This function sends a prompt to the system review agent and returns its analysis.
|
|
15
|
+
* The system review agent evaluates prompts based on various criteria like clarity,
|
|
16
|
+
* identity, scope, decision logic, etc.
|
|
17
|
+
*
|
|
18
|
+
* @param {string} prompt - The prompt text to be analyzed by the system review agent
|
|
19
|
+
* @param {Object} params - Parameters for the API call
|
|
20
|
+
* @param {Object} params.openai - The OpenAI client instance
|
|
21
|
+
* @param {Object} params.defaultOptions - Default options to be merged with agent model options
|
|
22
|
+
* @returns {Promise<string>} The analysis response from the system review agent
|
|
23
|
+
*/
|
|
24
|
+
export declare function callForSystemReview(prompt: string, params: any): Promise<{
|
|
25
|
+
content: any;
|
|
26
|
+
cost: number;
|
|
27
|
+
}>;
|