UNPKG

tinyagent-ts

Version:

Modern TypeScript framework for building AI agents with pluggable tools and ReAct reasoning

255 lines • 12.7 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.StockResearchAgent = exports.StockResearchTools = void 0; // Load environment variables from .env file const dotenv = __importStar(require("dotenv")); dotenv.config(); console.log('šŸ”‘ Environment loaded, API Key available:', !!process.env.OPENROUTER_API_KEY); const agent_1 = require("../src/agent"); const decorators_1 = require("../src/decorators"); const zod_1 = require("zod"); const yahoo_finance2_1 = __importDefault(require("yahoo-finance2")); // npm i yahoo-finance2 const duck_duck_scrape_1 = require("duck-duck-scrape"); // npm i duck-duck-scrape const node_fetch_1 = __importDefault(require("node-fetch")); // npm i node-fetch@^2 const jsdom_1 = require("jsdom"); // npm i jsdom /* ───────────────────────── TOOL DEFINITIONS ───────────────────────── */ // Simple sleep utility (for rate limiting/retries) function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } class StockResearchTools { /* 1. Get latest quote ------------------------------------------------ */ async stockQuote({ symbol }) { console.log('šŸ“ˆ Getting stock quote for:', symbol); const q = await yahoo_finance2_1.default.quote(symbol); console.log('šŸ“ˆ Stock data received:', { symbol: q.symbol, price: q.regularMarketPrice, changePercent: q.regularMarketChangePercent, marketCap: q.marketCap }); return { symbol: q.symbol, price: q.regularMarketPrice, changePercent: q.regularMarketChangePercent, marketCap: q.marketCap, }; } /* 2. DuckDuckGo news search ------------------------------------------ */ async topNewsUrl({ query }) { console.log('šŸ” Searching for news about:', query); // Limit DuckDuckGo search attempts to 1 to avoid being blocked. Increase if needed, but risk rate-limiting. const maxAttempts = 1; let attempt = 0; let lastError = null; let delay = 1000; while (attempt < maxAttempts) { try { if (attempt > 0) { console.log(`šŸ”„ Retrying DDG search (attempt ${attempt + 1}) after ${delay}ms...`); await sleep(delay); delay *= 2; // Exponential backoff } const { results } = await (0, duck_duck_scrape_1.search)(query, { maxResults: 3 }); console.log('šŸ” Search results received:', results.length, 'results'); // pick first non-ad / non-Wikipedia const r = results.find((r) => !r.url.includes("wikipedia")); console.log('šŸ” Selected news URL:', r?.url); return r?.url ?? ""; } catch (err) { lastError = err; console.error('šŸ›‘ Error in duck-duck-scrape:', err); attempt++; } } return `Tool topNewsUrl failed: DDG blocked or too many requests. Last error: ${lastError?.message || lastError}`; } /* 3. Fetch raw page text --------------------------------------------- */ async fetchPage({ url, maxLength, }) { console.log('🌐 Fetching page content from:', url); console.log('🌐 Max content length:', maxLength); const res = await (0, node_fetch_1.default)(url); const html = await res.text(); // very lightweight text extraction const dom = new jsdom_1.JSDOM(html); const text = dom.window.document.body.textContent ?? ""; const trimmedText = text.trim().slice(0, maxLength); console.log('🌐 Extracted text length:', trimmedText.length); return trimmedText; } } exports.StockResearchTools = StockResearchTools; __decorate([ (0, decorators_1.tool)("Get the latest stock quote (price, change %, market cap)", zod_1.z.object({ symbol: zod_1.z.string() })), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StockResearchTools.prototype, "stockQuote", null); __decorate([ (0, decorators_1.tool)("DuckDuckGo search and return the URL of the top news result", zod_1.z.object({ query: zod_1.z.string(), })), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StockResearchTools.prototype, "topNewsUrl", null); __decorate([ (0, decorators_1.tool)("Download HTML and return plain text content", zod_1.z.object({ url: zod_1.z.string().url(), maxLength: zod_1.z.number().int().max(4000).optional().default(2500), })), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StockResearchTools.prototype, "fetchPage", null); /* ──────────────────────── AGENT WIRING ────────────────────────────── */ let StockResearchAgent = class StockResearchAgent extends agent_1.Agent { constructor() { console.log('šŸ¤– Initializing StockResearchAgent'); super(); this.tools = new StockResearchTools(); console.log('šŸ¤– StockResearchAgent initialized with model:', this.getModelName()); } async stockQuote(args) { console.log('šŸ’¼ Agent.stockQuote called with args:', args); const result = await this.tools.stockQuote(args); console.log('šŸ’¼ Agent.stockQuote result:', result); return result; } async topNewsUrl(args) { console.log('šŸ“° Agent.topNewsUrl called with args:', args); const result = await this.tools.topNewsUrl(args); console.log('šŸ“° Agent.topNewsUrl result:', result); return result; } async fetchPage(args) { console.log('šŸ“š Agent.fetchPage called with args:', args); const result = await this.tools.fetchPage(args); console.log('šŸ“š Agent.fetchPage result length:', result.length); console.log('šŸ“š Agent.fetchPage result preview:', result.substring(0, 100) + '...'); return result; } }; exports.StockResearchAgent = StockResearchAgent; __decorate([ (0, decorators_1.tool)("Get the latest stock quote (price, change %, market cap)", zod_1.z.object({ symbol: zod_1.z.string() })), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StockResearchAgent.prototype, "stockQuote", null); __decorate([ (0, decorators_1.tool)("DuckDuckGo search and return the URL of the top news result", zod_1.z.object({ query: zod_1.z.string() })), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StockResearchAgent.prototype, "topNewsUrl", null); __decorate([ (0, decorators_1.tool)("Download HTML and return plain text content", zod_1.z.object({ url: zod_1.z.string().url(), maxLength: zod_1.z.number().int().max(4000).optional().default(2500), })), __metadata("design:type", Function), __metadata("design:paramtypes", [Object]), __metadata("design:returntype", Promise) ], StockResearchAgent.prototype, "fetchPage", null); exports.StockResearchAgent = StockResearchAgent = __decorate([ (0, decorators_1.model)("openai/gpt-4.1-mini"), __metadata("design:paramtypes", []) ], StockResearchAgent); /* ───────────────────────── QUICK DEMO ─────────────────────────────── */ if (require.main === module) { (async () => { console.log('šŸ”„ Starting StockResearch demo'); const agent = new StockResearchAgent(); try { const query = "Create a concise research note on AMC Entertainment (ticker AMC): " + "include current price info, percent change, market cap, and a one-paragraph " + "summary of the latest news article you find. Format your response as a JSON object with " + "'stockInformation' and 'latestNewsSummary' fields."; console.log('šŸ’¬ Query to agent:', query); console.log('šŸ• Starting agent.run() at', new Date().toLocaleTimeString()); const result = await agent.run(query); console.log('šŸ• Finished agent.run() at', new Date().toLocaleTimeString()); console.log('šŸ’¾ Response type:', typeof result); // With the new final_answer workflow, result will be an object with answer property let answer = ''; if (typeof result === 'object' && result && 'answer' in result) { answer = result.answer; } else { answer = String(result); } // Try to parse the response as JSON if it's a string let formattedAnswer = answer; if (typeof answer === 'string') { try { // Check if the answer contains a JSON code block const jsonMatch = answer.match(/```(?:json)?\s*({[\s\S]*?})\s*```/); if (jsonMatch && jsonMatch[1]) { formattedAnswer = JSON.parse(jsonMatch[1]); console.log('šŸ’¾ Extracted JSON from code block'); } else if (answer.trim().startsWith('{') && answer.trim().endsWith('}')) { // Try to parse the entire string as JSON formattedAnswer = JSON.parse(answer); console.log('šŸ’¾ Parsed entire response as JSON'); } } catch (e) { console.log('šŸ’¾ Could not parse as JSON, using raw string'); } } console.log("\n=== GENERATED REPORT ===\n" + JSON.stringify(formattedAnswer, null, 2)); } catch (error) { console.error("\nšŸ’„ Error running agent:\n", error); } })(); } //# sourceMappingURL=web-search.js.map