UNPKG

@nestbox-ai/cli

Version:

The cli tools that helps developers to build agents

203 lines 9.53 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DEFAULT_MODEL = void 0; exports.runReportComposerAgentWithOpenAI = runReportComposerAgentWithOpenAI; const openai_1 = __importDefault(require("openai")); const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); const js_yaml_1 = __importDefault(require("js-yaml")); const ajv_1 = __importDefault(require("ajv")); // ─── Constants ──────────────────────────────────────────────────────────────── const AGENTS_DIR = __dirname; exports.DEFAULT_MODEL = 'gpt-4o'; const DEFAULT_MAX_ITERATIONS = 5; // ─── Helpers ───────────────────────────────────────────────────────────────── function readLocalFile(filename) { return fs_1.default.readFileSync(path_1.default.join(AGENTS_DIR, filename), 'utf8'); } function validateYaml(content, schemaContent) { var _a; const preprocessed = content.replace(/\$\{[^}]+\}/g, 'env-var-placeholder'); let data; try { data = js_yaml_1.default.load(preprocessed); } catch (e) { return { valid: false, errors: [`YAML parse error: ${e.message}`] }; } let schema; try { schema = js_yaml_1.default.load(schemaContent); } catch (e) { return { valid: false, errors: [`Schema parse error: ${e.message}`] }; } // Remove $schema so AJV doesn't try to resolve the meta-schema URI // (AJV 8 defaults to draft-07 and doesn't recognise draft 2020-12). delete schema['$schema']; const ajv = new ajv_1.default({ strict: false, allErrors: true }); ajv.addFormat('uri', () => true); const validate = ajv.compile(schema); const ok = validate(data); if (ok) return { valid: true, errors: [] }; const errors = ((_a = validate.errors) !== null && _a !== void 0 ? _a : []).map((err) => { const loc = err.instancePath || '(root)'; return `[${loc}] ${err.message}`; }); return { valid: false, errors }; } // ─── System Prompt ──────────────────────────────────────────────────────────── function buildSystemPrompt() { const systemPrompt = readLocalFile('SYSTEM_PROMPT.md'); const configGuide = readLocalFile('REPORT_CONFIG_GUIDE.md'); const example1 = readLocalFile('annual_report_10k.yaml'); const example2 = readLocalFile('vc_portfolio_monitoring.yaml'); return [ systemPrompt, '---', configGuide, '---', '# Example 1: Annual Report / 10-K Analysis\n\n```yaml\n' + example1 + '\n```', '---', '# Example 2: VC Portfolio Monitoring\n\n```yaml\n' + example2 + '\n```', ].join('\n\n'); } // ─── Tool Definitions ───────────────────────────────────────────────────────── const TOOLS = [ { type: 'function', function: { name: 'write_and_validate_report', description: 'Write the report.yaml content and validate it against the schema. Returns "VALID" on success or a list of validation errors to fix.', parameters: { type: 'object', properties: { yaml_content: { type: 'string', description: 'The complete YAML content for report.yaml', }, }, required: ['yaml_content'], }, }, }, { type: 'function', function: { name: 'finish', description: 'Signal that the report.yaml is complete and valid. Call this only after write_and_validate_report has returned "VALID".', parameters: { type: 'object', properties: { summary: { type: 'string', description: 'Brief summary of what was generated and why key choices were made', }, }, required: ['summary'], }, }, }, ]; // ─── Agent ──────────────────────────────────────────────────────────────────── function runReportComposerAgentWithOpenAI(options) { return __awaiter(this, void 0, void 0, function* () { var _a; const { instructions, openAiApiKey, model = exports.DEFAULT_MODEL, maxIterations = DEFAULT_MAX_ITERATIONS, onProgress = () => { }, } = options; const reportSchema = readLocalFile('report_config.schema.yaml'); const client = new openai_1.default({ apiKey: openAiApiKey }); let latestReport = ''; let reportValid = false; let finished = false; let iteration = 0; function executeTool(name, input) { var _a; if (name === 'write_and_validate_report') { const content = (_a = input.yaml_content) !== null && _a !== void 0 ? _a : ''; latestReport = content; const result = validateYaml(content, reportSchema); reportValid = result.valid; if (result.valid) return 'VALID'; return `VALIDATION ERRORS — fix all of these before calling again:\n${result.errors.map((e) => ` • ${e}`).join('\n')}`; } if (name === 'finish') { if (!reportValid) { return 'Cannot finish: the report has not passed schema validation yet. Call write_and_validate_report first and ensure it returns "VALID".'; } finished = true; return 'Done.'; } return `Unknown tool: ${name}`; } const systemPromptText = buildSystemPrompt(); const messages = [ { role: 'system', content: systemPromptText }, { role: 'user', content: `Here are the instructions for the report you need to configure:\n\n${instructions}\n\nGenerate the report.yaml file now. Use the tools to write and validate it.`, }, ]; onProgress('Starting agent...'); while (iteration < maxIterations && !finished) { iteration++; onProgress(`Iteration ${iteration}/${maxIterations} — calling OpenAI...`); const response = yield client.chat.completions.create({ model, messages, tools: TOOLS, // Force the model to call a tool every turn. tool_choice: 'required', }); const message = response.choices[0].message; messages.push(message); if (response.choices[0].finish_reason !== 'tool_calls') { onProgress(`Agent stopped unexpectedly: ${response.choices[0].finish_reason}`); break; } const toolResultMessages = []; for (const toolCall of (_a = message.tool_calls) !== null && _a !== void 0 ? _a : []) { if (toolCall.type !== 'function') continue; onProgress(` → tool: ${toolCall.function.name}`); const input = JSON.parse(toolCall.function.arguments); const result = executeTool(toolCall.function.name, input); onProgress(` ${result.startsWith('VALID') ? '✓ valid' : result.split('\n')[0]}`); toolResultMessages.push({ role: 'tool', tool_call_id: toolCall.id, content: result, }); if (finished) break; } if (toolResultMessages.length > 0) { messages.push(...toolResultMessages); } if (finished) break; } if (iteration >= maxIterations && !finished) { onProgress(`Warning: reached max iterations (${maxIterations}) without finishing.`); } return { reportYaml: latestReport, iterations: iteration, reportValid, }; }); } //# sourceMappingURL=openai.js.map