From 80f5bb3fbacf2fd86b1035b76edaa4dba4a9f246 Mon Sep 17 00:00:00 2001 From: harshalmore31 Date: Tue, 5 Aug 2025 00:35:49 +0530 Subject: [PATCH 1/9] docs for deployments ! --- .../cloudflare_workers.md | 581 ++++++++++++++++++ 1 file changed, 581 insertions(+) create mode 100644 docs/deployment_solutions/cloudflare_workers.md diff --git a/docs/deployment_solutions/cloudflare_workers.md b/docs/deployment_solutions/cloudflare_workers.md new file mode 100644 index 00000000..c1d12bb9 --- /dev/null +++ b/docs/deployment_solutions/cloudflare_workers.md @@ -0,0 +1,581 @@ +# Cloudflare Workers Deployment with Swarms API + +Deploy intelligent agent swarms on Cloudflare's edge network for maximum performance, global availability, and automatic scaling. This guide covers deploying both API endpoints and scheduled cron job agents using the Swarms API. + +## Overview + +Cloudflare Workers provide a serverless execution environment that runs on Cloudflare's global network, offering: + +- **Edge Computing**: Deploy agents close to users worldwide +- **Automatic Scaling**: Handle traffic spikes without configuration +- **Zero Cold Starts**: Instant response times +- **Cost Effective**: Pay only for what you use +- **Built-in Cron Jobs**: Schedule automated agent tasks + +Perfect for deploying AI agents that need global reach, low latency, and scheduled execution capabilities. + +## Prerequisites + +!!! info "Requirements" + + - Cloudflare account (free tier available) + - Wrangler CLI installed (`npm install -g wrangler`) + - Swarms API key from [Swarms Platform](https://swarms.world/platform/api-keys) + - Node.js 16+ for local development + +## Quick Start + +### 1. Project Setup + +```bash +# Create new Cloudflare Worker +npx create-cloudflare my-swarms-worker worker + +# Navigate to project +cd my-swarms-worker + +# Install dependencies +npm install +``` + +### 2. Configure Environment Variables + +Add your Swarms API key to `wrangler.toml`: + +```toml +name = "my-swarms-worker" +main = "src/index.js" +compatibility_date = "2024-01-01" + +[env.production.vars] +SWARMS_API_KEY = "your-api-key-here" + +[env.production] +# For scheduled agents +[[env.production.triggers.crons]] +cron = "0 9 * * MON-FRI" # Weekdays at 9 AM UTC +``` + +### 3. Basic Agent Worker + +=== "JavaScript" + + ```javascript + export default { + async fetch(request, env, ctx) { + // Handle CORS preflight + if (request.method === 'OPTIONS') { + return handleCORS(); + } + + try { + const { pathname } = new URL(request.url); + + if (pathname === '/api/agent' && request.method === 'POST') { + return await handleAgentRequest(request, env); + } + + if (pathname === '/api/health' && request.method === 'GET') { + return new Response(JSON.stringify({ + status: 'healthy', + service: 'Swarms Agent API', + version: '1.0.0' + }), { + status: 200, + headers: { + 'Content-Type': 'application/json', + ...getCORSHeaders() + } + }); + } + + return new Response('Not Found', { status: 404 }); + } catch (error) { + console.error('Worker error:', error); + return new Response(JSON.stringify({ + error: error.message + }), { + status: 500, + headers: { + 'Content-Type': 'application/json', + ...getCORSHeaders() + } + }); + } + }, + + // Scheduled event handler for cron jobs + async scheduled(event, env, ctx) { + ctx.waitUntil(handleScheduledEvent(event, env)); + } + }; + + async function handleAgentRequest(request, env) { + const requestData = await request.json(); + + const agentConfig = { + agent_config: { + agent_name: requestData.agent_name || "CloudflareAgent", + description: requestData.description || "Agent running on Cloudflare Workers", + system_prompt: requestData.system_prompt || "You are a helpful AI assistant.", + model_name: requestData.model_name || "gpt-4o-mini", + max_tokens: requestData.max_tokens || 2000, + temperature: requestData.temperature || 0.7 + }, + task: requestData.task + }; + + const response = await fetch('https://api.swarms.world/v1/agent/completions', { + method: 'POST', + headers: { + 'x-api-key': env.SWARMS_API_KEY, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(agentConfig) + }); + + const result = await response.json(); + + return new Response(JSON.stringify(result), { + status: response.status, + headers: { + 'Content-Type': 'application/json', + ...getCORSHeaders() + } + }); + } + + function getCORSHeaders() { + return { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization', + }; + } + + function handleCORS() { + return new Response(null, { + status: 200, + headers: getCORSHeaders() + }); + } + ``` + +=== "TypeScript" + + ```typescript + interface AgentRequest { + agent_name?: string; + description?: string; + system_prompt?: string; + model_name?: string; + max_tokens?: number; + temperature?: number; + task: string; + } + + interface AgentConfig { + agent_config: { + agent_name: string; + description: string; + system_prompt: string; + model_name: string; + max_tokens: number; + temperature: number; + }; + task: string; + } + + interface Env { + SWARMS_API_KEY: string; + } + + export interface ScheduledEvent { + scheduledTime: number; + cron: string; + } + + export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + if (request.method === 'OPTIONS') { + return handleCORS(); + } + + try { + const { pathname } = new URL(request.url); + + if (pathname === '/api/agent' && request.method === 'POST') { + return await handleAgentRequest(request, env); + } + + if (pathname === '/api/health' && request.method === 'GET') { + return new Response(JSON.stringify({ + status: 'healthy', + service: 'Swarms Agent API', + version: '1.0.0' + }), { + status: 200, + headers: { + 'Content-Type': 'application/json', + ...getCORSHeaders() + } + }); + } + + return new Response('Not Found', { status: 404 }); + } catch (error) { + console.error('Worker error:', error); + return new Response(JSON.stringify({ + error: (error as Error).message + }), { + status: 500, + headers: { + 'Content-Type': 'application/json', + ...getCORSHeaders() + } + }); + } + }, + + async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext): Promise { + ctx.waitUntil(handleScheduledEvent(event, env)); + } + }; + + async function handleAgentRequest(request: Request, env: Env): Promise { + const requestData: AgentRequest = await request.json(); + + const agentConfig: AgentConfig = { + agent_config: { + agent_name: requestData.agent_name || "CloudflareAgent", + description: requestData.description || "Agent running on Cloudflare Workers", + system_prompt: requestData.system_prompt || "You are a helpful AI assistant.", + model_name: requestData.model_name || "gpt-4o-mini", + max_tokens: requestData.max_tokens || 2000, + temperature: requestData.temperature || 0.7 + }, + task: requestData.task + }; + + const response = await fetch('https://api.swarms.world/v1/agent/completions', { + method: 'POST', + headers: { + 'x-api-key': env.SWARMS_API_KEY, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(agentConfig) + }); + + const result = await response.json(); + + return new Response(JSON.stringify(result), { + status: response.status, + headers: { + 'Content-Type': 'application/json', + ...getCORSHeaders() + } + }); + } + + function getCORSHeaders(): Record { + return { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization', + }; + } + + function handleCORS(): Response { + return new Response(null, { + status: 200, + headers: getCORSHeaders() + }); + } + ``` + +### 4. Deploy Your Worker + +```bash +# Deploy to Cloudflare +wrangler deploy + +# View logs +wrangler tail +``` + +## Scheduled Cron Job Agents + +Cloudflare Workers support scheduled events (cron jobs) that can trigger agent tasks automatically. This is perfect for periodic analysis, monitoring, reporting, and automated decision-making. + +### Stock Market Analysis Agent + +Deploy a cron job agent that analyzes stock market trends and generates daily reports: + +=== "JavaScript" + + ```javascript + // wrangler.toml configuration for stock market agent + /* + [[env.production.triggers.crons]] + cron = "0 16 * * MON-FRI" # 4 PM UTC (after US market close) + */ + + async function handleScheduledEvent(event, env) { + console.log('Stock market analysis triggered at:', new Date(event.scheduledTime)); + + try { + // Stock analysis swarm configuration + const swarmConfig = { + name: "Stock Market Analysis Swarm", + description: "Daily stock market analysis and trading insights", + agents: [ + { + agent_name: "Market Data Analyst", + description: "Analyzes market trends and price movements", + system_prompt: `You are an expert financial market analyst specializing in equity markets. + Analyze market trends, volume patterns, and price movements. + Provide technical analysis insights and identify key support/resistance levels. + Focus on major indices (S&P 500, NASDAQ, DOW) and sector performance.`, + model_name: "gpt-4o", + max_tokens: 3000, + temperature: 0.3, + role: "worker" + }, + { + agent_name: "Economic News Analyzer", + description: "Analyzes economic news impact on markets", + system_prompt: `You are a financial news analyst with expertise in market sentiment analysis. + Analyze recent economic news, earnings reports, and market-moving events. + Assess their potential impact on stock prices and market sentiment. + Identify key catalysts and risk factors for the next trading day.`, + model_name: "gpt-4o", + max_tokens: 3000, + temperature: 0.3, + role: "worker" + }, + { + agent_name: "Trading Strategy Advisor", + description: "Provides trading recommendations and risk assessment", + system_prompt: `You are a quantitative trading strategist with expertise in risk management. + Based on technical analysis and market sentiment, provide actionable trading insights. + Include risk assessment, position sizing recommendations, and key levels to watch. + Focus on risk-adjusted returns and downside protection strategies.`, + model_name: "gpt-4o", + max_tokens: 3000, + temperature: 0.4, + role: "worker" + } + ], + swarm_type: "SequentialWorkflow", + max_loops: 1, + task: `Analyze today's stock market performance and provide insights for tomorrow's trading session. + Include: 1) Market overview and key movers 2) Technical analysis of major indices + 3) Economic news impact assessment 4) Trading opportunities and risks + 5) Key levels to watch tomorrow. Format as a professional daily market report.`, + service_tier: "standard" + }; + + // Execute the swarm + const response = await fetch('https://api.swarms.world/v1/swarm/completions', { + method: 'POST', + headers: { + 'x-api-key': env.SWARMS_API_KEY, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(swarmConfig) + }); + + const result = await response.json(); + + if (response.ok) { + console.log('Stock analysis completed successfully'); + console.log('Cost:', result.metadata?.billing_info?.total_cost); + + // Store results in KV storage for retrieval + if (env.STOCK_REPORTS) { + const reportKey = `stock-report-${new Date().toISOString().split('T')[0]}`; + await env.STOCK_REPORTS.put(reportKey, JSON.stringify({ + timestamp: new Date().toISOString(), + analysis: result.output, + cost: result.metadata?.billing_info?.total_cost + })); + } + + // Optional: Send to webhook, email, or notification service + await sendNotification(env, result.output); + + } else { + console.error('Stock analysis failed:', result); + } + + } catch (error) { + console.error('Error in scheduled stock analysis:', error); + } + } + + async function sendNotification(env, analysis) { + // Example: Send to Slack webhook + if (env.SLACK_WEBHOOK_URL) { + try { + await fetch(env.SLACK_WEBHOOK_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + text: "📈 Daily Stock Market Analysis Ready", + attachments: [{ + color: "good", + text: typeof analysis === 'string' ? analysis.substring(0, 500) + '...' : 'Analysis completed', + footer: "Swarms Stock Analysis Agent" + }] + }) + }); + } catch (error) { + console.error('Failed to send Slack notification:', error); + } + } + } + + // API endpoint to retrieve stock reports + async function getStockReport(request, env) { + const url = new URL(request.url); + const date = url.searchParams.get('date') || new Date().toISOString().split('T')[0]; + const reportKey = `stock-report-${date}`; + + if (env.STOCK_REPORTS) { + const report = await env.STOCK_REPORTS.get(reportKey); + if (report) { + return new Response(report, { + headers: { 'Content-Type': 'application/json' } + }); + } + } + + return new Response(JSON.stringify({ error: 'Report not found' }), { + status: 404, + headers: { 'Content-Type': 'application/json' } + }); + } + ``` + +=== "TypeScript" + + ```typescript + interface StockAnalysisResult { + timestamp: string; + analysis: any; + cost: number; + } + + async function handleScheduledEvent(event: ScheduledEvent, env: Env): Promise { + console.log('Stock market analysis triggered at:', new Date(event.scheduledTime)); + + try { + const swarmConfig = { + name: "Stock Market Analysis Swarm", + description: "Daily stock market analysis and trading insights", + agents: [ + { + agent_name: "Market Data Analyst", + description: "Analyzes market trends and price movements", + system_prompt: `You are an expert financial market analyst specializing in equity markets. + Analyze market trends, volume patterns, and price movements. + Provide technical analysis insights and identify key support/resistance levels. + Focus on major indices (S&P 500, NASDAQ, DOW) and sector performance.`, + model_name: "gpt-4o", + max_tokens: 3000, + temperature: 0.3, + role: "worker" + }, + { + agent_name: "Economic News Analyzer", + description: "Analyzes economic news impact on markets", + system_prompt: `You are a financial news analyst with expertise in market sentiment analysis. + Analyze recent economic news, earnings reports, and market-moving events. + Assess their potential impact on stock prices and market sentiment. + Identify key catalysts and risk factors for the next trading day.`, + model_name: "gpt-4o", + max_tokens: 3000, + temperature: 0.3, + role: "worker" + }, + { + agent_name: "Trading Strategy Advisor", + description: "Provides trading recommendations and risk assessment", + system_prompt: `You are a quantitative trading strategist with expertise in risk management. + Based on technical analysis and market sentiment, provide actionable trading insights. + Include risk assessment, position sizing recommendations, and key levels to watch. + Focus on risk-adjusted returns and downside protection strategies.`, + model_name: "gpt-4o", + max_tokens: 3000, + temperature: 0.4, + role: "worker" + } + ], + swarm_type: "SequentialWorkflow" as const, + max_loops: 1, + task: `Analyze today's stock market performance and provide insights for tomorrow's trading session. + Include: 1) Market overview and key movers 2) Technical analysis of major indices + 3) Economic news impact assessment 4) Trading opportunities and risks + 5) Key levels to watch tomorrow. Format as a professional daily market report.`, + service_tier: "standard" + }; + + const response = await fetch('https://api.swarms.world/v1/swarm/completions', { + method: 'POST', + headers: { + 'x-api-key': env.SWARMS_API_KEY, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(swarmConfig) + }); + + const result = await response.json(); + + if (response.ok) { + console.log('Stock analysis completed successfully'); + console.log('Cost:', result.metadata?.billing_info?.total_cost); + + if (env.STOCK_REPORTS) { + const reportKey = `stock-report-${new Date().toISOString().split('T')[0]}`; + const reportData: StockAnalysisResult = { + timestamp: new Date().toISOString(), + analysis: result.output, + cost: result.metadata?.billing_info?.total_cost + }; + + await env.STOCK_REPORTS.put(reportKey, JSON.stringify(reportData)); + } + + await sendNotification(env, result.output); + + } else { + console.error('Stock analysis failed:', result); + } + + } catch (error) { + console.error('Error in scheduled stock analysis:', error); + } + } + + async function sendNotification(env: Env, analysis: any): Promise { + if (env.SLACK_WEBHOOK_URL) { + try { + await fetch(env.SLACK_WEBHOOK_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + text: "📈 Daily Stock Market Analysis Ready", + attachments: [{ + color: "good", + text: typeof analysis === 'string' ? analysis.substring(0, 500) + '...' : 'Analysis completed', + footer: "Swarms Stock Analysis Agent" + }] + }) + }); + } catch (error) { + console.error('Failed to send Slack notification:', error); + } + } + } + ``` + From cacc277013ac6eb6dd078c5572f1e884976c6ec1 Mon Sep 17 00:00:00 2001 From: harshalmore31 Date: Tue, 5 Aug 2025 00:43:14 +0530 Subject: [PATCH 2/9] updates --- docs/mkdocs.yml | 1 + .../{deployment_solutions => swarms_cloud}/cloudflare_workers.md | 0 2 files changed, 1 insertion(+) rename docs/{deployment_solutions => swarms_cloud}/cloudflare_workers.md (100%) diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 646acdd2..8bb7ec3e 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -345,6 +345,7 @@ nav: - Deploy on Google Cloud Run: "swarms_cloud/cloud_run.md" - Deploy on Phala: "swarms_cloud/phala_deploy.md" - CronJob: "swarms/structs/cron_job.md" + - Deploy on Cloudflare Workers: "swarms_cloud/cloudflare_workers.md" # - Deploy on FastAPI: "swarms_cloud/fastapi_deploy.md" diff --git a/docs/deployment_solutions/cloudflare_workers.md b/docs/swarms_cloud/cloudflare_workers.md similarity index 100% rename from docs/deployment_solutions/cloudflare_workers.md rename to docs/swarms_cloud/cloudflare_workers.md From c532c3c909a1abf5f705f285728b8077e35dce7d Mon Sep 17 00:00:00 2001 From: harshalmore31 Date: Tue, 5 Aug 2025 01:05:13 +0530 Subject: [PATCH 3/9] updated the docs !! --- docs/swarms_cloud/cloudflare_workers.md | 946 +++++++++++------------- 1 file changed, 426 insertions(+), 520 deletions(-) diff --git a/docs/swarms_cloud/cloudflare_workers.md b/docs/swarms_cloud/cloudflare_workers.md index c1d12bb9..085ca78b 100644 --- a/docs/swarms_cloud/cloudflare_workers.md +++ b/docs/swarms_cloud/cloudflare_workers.md @@ -1,581 +1,487 @@ -# Cloudflare Workers Deployment with Swarms API +# Cloudflare Workers with Swarms: Automated Cron Job Agents -Deploy intelligent agent swarms on Cloudflare's edge network for maximum performance, global availability, and automatic scaling. This guide covers deploying both API endpoints and scheduled cron job agents using the Swarms API. +Deploy scheduled AI agents on Cloudflare's global edge network for automated stock analysis and healthcare monitoring. This guide focuses on cron job agents that run automatically at scheduled intervals. ## Overview -Cloudflare Workers provide a serverless execution environment that runs on Cloudflare's global network, offering: +Cloudflare Workers with cron triggers enable automated agent execution for: +- **Stock Market Analysis**: Daily market reports and trading insights +- **Healthcare Monitoring**: Patient data analysis and alerts +- **Automated Reporting**: Scheduled business intelligence +- **Global Deployment**: Edge computing with zero cold starts -- **Edge Computing**: Deploy agents close to users worldwide -- **Automatic Scaling**: Handle traffic spikes without configuration -- **Zero Cold Starts**: Instant response times -- **Cost Effective**: Pay only for what you use -- **Built-in Cron Jobs**: Schedule automated agent tasks +## Quick Setup -Perfect for deploying AI agents that need global reach, low latency, and scheduled execution capabilities. - -## Prerequisites - -!!! info "Requirements" - - - Cloudflare account (free tier available) - - Wrangler CLI installed (`npm install -g wrangler`) - - Swarms API key from [Swarms Platform](https://swarms.world/platform/api-keys) - - Node.js 16+ for local development - -## Quick Start - -### 1. Project Setup +### 1. Create Worker Project ```bash -# Create new Cloudflare Worker -npx create-cloudflare my-swarms-worker worker - -# Navigate to project -cd my-swarms-worker - -# Install dependencies -npm install +npx create-cloudflare stock-agent worker +cd stock-agent ``` -### 2. Configure Environment Variables +### 2. Configure Cron Schedule -Add your Swarms API key to `wrangler.toml`: +Edit `wrangler.toml`: ```toml -name = "my-swarms-worker" +name = "stock-analysis-agent" main = "src/index.js" compatibility_date = "2024-01-01" [env.production.vars] SWARMS_API_KEY = "your-api-key-here" +SLACK_WEBHOOK_URL = "optional-slack-webhook" -[env.production] -# For scheduled agents +# Stock market analysis - after market close [[env.production.triggers.crons]] -cron = "0 9 * * MON-FRI" # Weekdays at 9 AM UTC -``` +cron = "0 21 * * MON-FRI" # 9 PM UTC (4 PM EST) -### 3. Basic Agent Worker - -=== "JavaScript" +# Healthcare monitoring - every 4 hours +[[env.production.triggers.crons]] +cron = "0 */4 * * *" +``` - ```javascript - export default { - async fetch(request, env, ctx) { - // Handle CORS preflight - if (request.method === 'OPTIONS') { - return handleCORS(); +## Stock Market Analysis Agent + +Automated daily stock analysis after market close: + +```javascript +export default { + // Cron job handler - runs automatically + async scheduled(event, env, ctx) { + ctx.waitUntil(handleStockAnalysis(event, env)); + } +}; + +async function handleStockAnalysis(event, env) { + try { + // Step 1: Fetch real market data from multiple sources + const marketData = await fetchMarketData(env); + + // Step 2: Get market news + const marketNews = await fetchMarketNews(env); + + // Step 3: Send real data to Swarms agents for analysis + const swarmConfig = { + name: "Real-Time Stock Analysis", + description: "Live market data analysis with AI agents", + agents: [ + { + agent_name: "Technical Analyst", + system_prompt: `You are a professional technical analyst. Analyze the provided real market data: + - Calculate key technical indicators (RSI, MACD, Moving Averages) + - Identify support and resistance levels + - Determine market trends and momentum + - Provide trading signals and price targets + Format your analysis professionally with specific price levels.`, + model_name: "gpt-4o-mini", + max_tokens: 3000, + temperature: 0.2 + }, + { + agent_name: "Fundamental Analyst", + system_prompt: `You are a fundamental market analyst. Using the provided market news and data: + - Analyze earnings impact and company fundamentals + - Evaluate economic indicators and Fed policy effects + - Assess sector rotation and market sentiment + - Identify value opportunities and risks + Provide investment recommendations with risk assessment.`, + model_name: "gpt-4o-mini", + max_tokens: 3000, + temperature: 0.3 } + ], + swarm_type: "ConcurrentWorkflow", + task: `Analyze the following real market data and news: + +MARKET DATA: +${JSON.stringify(marketData, null, 2)} + +MARKET NEWS: +${marketNews} + +Provide comprehensive analysis with: +1. Technical analysis with key levels +2. Fundamental analysis with catalysts +3. Trading recommendations +4. Risk assessment +5. Tomorrow's key levels to watch`, + max_loops: 1 + }; - try { - const { pathname } = new URL(request.url); - - if (pathname === '/api/agent' && request.method === 'POST') { - return await handleAgentRequest(request, env); - } - - if (pathname === '/api/health' && request.method === 'GET') { - return new Response(JSON.stringify({ - status: 'healthy', - service: 'Swarms Agent API', - version: '1.0.0' - }), { - status: 200, - headers: { - 'Content-Type': 'application/json', - ...getCORSHeaders() - } - }); - } - - return new Response('Not Found', { status: 404 }); - } catch (error) { - console.error('Worker error:', error); - return new Response(JSON.stringify({ - error: error.message - }), { - status: 500, - headers: { - 'Content-Type': 'application/json', - ...getCORSHeaders() - } - }); - } + const response = await fetch('https://api.swarms.world/v1/swarm/completions', { + method: 'POST', + headers: { + 'x-api-key': env.SWARMS_API_KEY, + 'Content-Type': 'application/json' }, - - // Scheduled event handler for cron jobs - async scheduled(event, env, ctx) { - ctx.waitUntil(handleScheduledEvent(event, env)); + body: JSON.stringify(swarmConfig) + }); + + const result = await response.json(); + + if (response.ok) { + console.log('✅ Real-time stock analysis completed'); + console.log('💰 Cost:', result.metadata?.billing_info?.total_cost); + + // Send email directly + await sendEmailReport(env, result.output, marketData); + } + } catch (error) { + console.error('❌ Real-time stock analysis failed:', error); + } +} + +// Fetch real market data from Alpha Vantage API +async function fetchMarketData(env) { + const symbols = ['SPY', 'QQQ', 'AAPL', 'MSFT', 'TSLA', 'NVDA']; + const marketData = {}; + + for (const symbol of symbols) { + try { + // Get daily prices + const priceResponse = await fetch( + `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${symbol}&apikey=${env.STOCK_API_KEY}` + ); + const priceData = await priceResponse.json(); + + // Get technical indicators (RSI) + const rsiResponse = await fetch( + `https://www.alphavantage.co/query?function=RSI&symbol=${symbol}&interval=daily&time_period=14&series_type=close&apikey=${env.STOCK_API_KEY}` + ); + const rsiData = await rsiResponse.json(); + + if (priceData['Time Series (Daily)'] && rsiData['Technical Analysis: RSI']) { + const latestDate = Object.keys(priceData['Time Series (Daily)'])[0]; + const latestPrice = priceData['Time Series (Daily)'][latestDate]; + const latestRSI = Object.values(rsiData['Technical Analysis: RSI'])[0]; + + marketData[symbol] = { + price: parseFloat(latestPrice['4. close']), + open: parseFloat(latestPrice['1. open']), + high: parseFloat(latestPrice['2. high']), + low: parseFloat(latestPrice['3. low']), + volume: parseInt(latestPrice['5. volume']), + change: parseFloat(latestPrice['4. close']) - parseFloat(latestPrice['1. open']), + change_percent: ((parseFloat(latestPrice['4. close']) - parseFloat(latestPrice['1. open'])) / parseFloat(latestPrice['1. open']) * 100).toFixed(2), + rsi: parseFloat(latestRSI?.RSI || 50), + date: latestDate + }; } - }; - - async function handleAgentRequest(request, env) { - const requestData = await request.json(); - const agentConfig = { - agent_config: { - agent_name: requestData.agent_name || "CloudflareAgent", - description: requestData.description || "Agent running on Cloudflare Workers", - system_prompt: requestData.system_prompt || "You are a helpful AI assistant.", - model_name: requestData.model_name || "gpt-4o-mini", - max_tokens: requestData.max_tokens || 2000, - temperature: requestData.temperature || 0.7 - }, - task: requestData.task - }; - - const response = await fetch('https://api.swarms.world/v1/agent/completions', { - method: 'POST', - headers: { - 'x-api-key': env.SWARMS_API_KEY, - 'Content-Type': 'application/json' - }, - body: JSON.stringify(agentConfig) - }); - - const result = await response.json(); + // Rate limiting - Alpha Vantage allows 5 requests per minute on free tier + await new Promise(resolve => setTimeout(resolve, 12000)); - return new Response(JSON.stringify(result), { - status: response.status, - headers: { - 'Content-Type': 'application/json', - ...getCORSHeaders() - } - }); + } catch (error) { + console.error(`Error fetching data for ${symbol}:`, error); + marketData[symbol] = { error: 'Failed to fetch data' }; } - - function getCORSHeaders() { - return { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', - 'Access-Control-Allow-Headers': 'Content-Type, Authorization', - }; + } + + return marketData; +} + +// Fetch market news from Financial Modeling Prep (free tier available) +async function fetchMarketNews(env) { + try { + const newsResponse = await fetch( + `https://financialmodelingprep.com/api/v3/stock_news?tickers=AAPL,MSFT,TSLA,NVDA&limit=10&apikey=${env.FMP_API_KEY || 'demo'}` + ); + const newsData = await newsResponse.json(); + + if (Array.isArray(newsData)) { + return newsData.slice(0, 5).map(article => ({ + title: article.title, + text: article.text?.substring(0, 300) + '...', + publishedDate: article.publishedDate, + symbol: article.symbol, + url: article.url + })); } + } catch (error) { + console.error('Error fetching news:', error); + } + + return "Market news temporarily unavailable"; +} + +// Send email report using Mailgun API +async function sendEmailReport(env, analysis, marketData) { + // Extract key market movers for email subject + const movers = Object.entries(marketData) + .filter(([symbol, data]) => data.change_percent && Math.abs(parseFloat(data.change_percent)) > 2) + .map(([symbol, data]) => `${symbol}: ${data.change_percent}%`) + .join(', '); + + const emailSubject = `📊 Daily Stock Analysis - ${new Date().toLocaleDateString()}`; + const emailBody = ` +

Daily Market Analysis Report

+

Date: ${new Date().toLocaleString()}

+

Key Market Movers: ${movers || 'Market stable'}

+ +

AI Agent Analysis:

+
+
${analysis}
+
+ +

Market Data Summary:

+ + + + + ${Object.entries(marketData).map(([symbol, data]) => ` + + + + + + + + `).join('')} +
SymbolPriceChange %VolumeRSI
${symbol}$${data.price?.toFixed(2) || 'N/A'} + ${data.change_percent}% + ${data.volume?.toLocaleString() || 'N/A'}${data.rsi?.toFixed(1) || 'N/A'}
+ +

Generated by Swarms AI Agent System

+ `; + + // Send via Mailgun + const formData = new FormData(); + formData.append('from', `Stock Analysis Agent `); + formData.append('to', env.RECIPIENT_EMAIL); + formData.append('subject', emailSubject); + formData.append('html', emailBody); + + try { + const response = await fetch(`https://api.mailgun.net/v3/${env.MAILGUN_DOMAIN}/messages`, { + method: 'POST', + headers: { + 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}` + }, + body: formData + }); - function handleCORS() { - return new Response(null, { - status: 200, - headers: getCORSHeaders() - }); - } - ``` - -=== "TypeScript" - - ```typescript - interface AgentRequest { - agent_name?: string; - description?: string; - system_prompt?: string; - model_name?: string; - max_tokens?: number; - temperature?: number; - task: string; + if (response.ok) { + console.log('✅ Email report sent successfully'); + } else { + console.error('❌ Failed to send email:', await response.text()); } + } catch (error) { + console.error('❌ Email sending error:', error); + } +} + +async function sendSlackNotification(webhookUrl, analysis) { + await fetch(webhookUrl, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + text: "📈 Daily Stock Market Analysis", + blocks: [{ + type: "section", + text: { + type: "mrkdwn", + text: `*Market Analysis Complete*\n\`\`\`${analysis.substring(0, 500)}...\`\`\`` + } + }] + }) + }); +} +``` - interface AgentConfig { - agent_config: { - agent_name: string; - description: string; - system_prompt: string; - model_name: string; - max_tokens: number; - temperature: number; - }; - task: string; - } +## Healthcare Monitoring Agent - interface Env { - SWARMS_API_KEY: string; - } +Automated patient monitoring and health alerts: - export interface ScheduledEvent { - scheduledTime: number; - cron: string; +```javascript +export default { + async scheduled(event, env, ctx) { + // Determine which agent to run based on cron schedule + const hour = new Date().getHours(); + + if (hour % 4 === 0) { + // Every 4 hours - patient monitoring + ctx.waitUntil(handlePatientMonitoring(event, env)); } - - export default { - async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { - if (request.method === 'OPTIONS') { - return handleCORS(); - } - - try { - const { pathname } = new URL(request.url); - - if (pathname === '/api/agent' && request.method === 'POST') { - return await handleAgentRequest(request, env); - } - - if (pathname === '/api/health' && request.method === 'GET') { - return new Response(JSON.stringify({ - status: 'healthy', - service: 'Swarms Agent API', - version: '1.0.0' - }), { - status: 200, - headers: { - 'Content-Type': 'application/json', - ...getCORSHeaders() - } - }); - } - - return new Response('Not Found', { status: 404 }); - } catch (error) { - console.error('Worker error:', error); - return new Response(JSON.stringify({ - error: (error as Error).message - }), { - status: 500, - headers: { - 'Content-Type': 'application/json', - ...getCORSHeaders() - } - }); - } + } +}; + +async function handlePatientMonitoring(event, env) { + const healthcareSwarm = { + name: "Patient Monitoring System", + description: "Automated patient health analysis and alerting", + agents: [ + { + agent_name: "Vital Signs Analyst", + system_prompt: `Analyze patient vital signs data for abnormalities: + - Heart rate patterns and irregularities + - Blood pressure trends + - Oxygen saturation levels + - Temperature variations + Flag critical conditions requiring immediate attention.`, + model_name: "gpt-4o-mini", + max_tokens: 2000, + temperature: 0.1 }, - - async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext): Promise { - ctx.waitUntil(handleScheduledEvent(event, env)); + { + agent_name: "Risk Assessment Specialist", + system_prompt: `Evaluate patient risk factors and health trends: + - Medication interactions + - Chronic condition management + - Recovery progress assessment + - Early warning signs detection + Prioritize patients needing urgent care.`, + model_name: "gpt-4o-mini", + max_tokens: 2000, + temperature: 0.2 } - }; - - async function handleAgentRequest(request: Request, env: Env): Promise { - const requestData: AgentRequest = await request.json(); - - const agentConfig: AgentConfig = { - agent_config: { - agent_name: requestData.agent_name || "CloudflareAgent", - description: requestData.description || "Agent running on Cloudflare Workers", - system_prompt: requestData.system_prompt || "You are a helpful AI assistant.", - model_name: requestData.model_name || "gpt-4o-mini", - max_tokens: requestData.max_tokens || 2000, - temperature: requestData.temperature || 0.7 - }, - task: requestData.task - }; - - const response = await fetch('https://api.swarms.world/v1/agent/completions', { - method: 'POST', - headers: { - 'x-api-key': env.SWARMS_API_KEY, - 'Content-Type': 'application/json' - }, - body: JSON.stringify(agentConfig) - }); + ], + swarm_type: "ConcurrentWorkflow", + task: "Analyze current patient monitoring data and generate health status alerts for medical staff.", + max_loops: 1 + }; + + try { + const response = await fetch('https://api.swarms.world/v1/swarm/completions', { + method: 'POST', + headers: { + 'x-api-key': env.SWARMS_API_KEY, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(healthcareSwarm) + }); - const result = await response.json(); + const result = await response.json(); + + if (response.ok) { + console.log('🏥 Health monitoring completed'); - return new Response(JSON.stringify(result), { - status: response.status, - headers: { - 'Content-Type': 'application/json', - ...getCORSHeaders() - } - }); - } - - function getCORSHeaders(): Record { - return { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', - 'Access-Control-Allow-Headers': 'Content-Type, Authorization', - }; + // Send email alerts for all monitoring results + await sendHealthEmailAlert(env, result.output); } + } catch (error) { + console.error('❌ Health monitoring failed:', error); + } +} + +// Send healthcare email alerts +async function sendHealthEmailAlert(env, analysis) { + const severity = extractSeverity(analysis); + const isUrgent = severity === 'critical' || severity === 'urgent'; + + const emailSubject = `${isUrgent ? '🚨 URGENT' : '🏥'} Health Monitoring Alert - ${new Date().toLocaleString()}`; + const emailBody = ` +

Patient Monitoring Report

+

Timestamp: ${new Date().toLocaleString()}

+

Severity Level: ${severity.toUpperCase()}

+ +

AI Health Analysis:

+
+
${analysis}
+
+ + ${isUrgent ? '

⚠️ IMMEDIATE ATTENTION REQUIRED

' : ''} + +

Generated by Swarms Healthcare Monitoring Agent

+ `; + + // Send email using Mailgun + const formData = new FormData(); + formData.append('from', `Healthcare Monitor `); + formData.append('to', env.MEDICAL_TEAM_EMAIL); + formData.append('subject', emailSubject); + formData.append('html', emailBody); + + try { + const response = await fetch(`https://api.mailgun.net/v3/${env.MAILGUN_DOMAIN}/messages`, { + method: 'POST', + headers: { + 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}` + }, + body: formData + }); - function handleCORS(): Response { - return new Response(null, { - status: 200, - headers: getCORSHeaders() - }); + if (response.ok) { + console.log('✅ Healthcare email alert sent successfully'); + } else { + console.error('❌ Failed to send healthcare email:', await response.text()); } - ``` + } catch (error) { + console.error('❌ Healthcare email error:', error); + } +} + +function extractSeverity(analysis) { + if (analysis.includes('CRITICAL')) return 'critical'; + if (analysis.includes('URGENT')) return 'urgent'; + if (analysis.includes('WARNING')) return 'warning'; + return 'normal'; +} + +function getSeverityColor(severity) { + switch(severity) { + case 'critical': return 'red'; + case 'urgent': return 'orange'; + case 'warning': return 'yellow'; + default: return 'green'; + } +} +``` -### 4. Deploy Your Worker +## Deployment ```bash -# Deploy to Cloudflare +# Deploy your cron job agents wrangler deploy -# View logs +# Monitor logs wrangler tail -``` - -## Scheduled Cron Job Agents -Cloudflare Workers support scheduled events (cron jobs) that can trigger agent tasks automatically. This is perfect for periodic analysis, monitoring, reporting, and automated decision-making. - -### Stock Market Analysis Agent - -Deploy a cron job agent that analyzes stock market trends and generates daily reports: +# Test cron trigger manually +wrangler triggers cron "0 21 * * MON-FRI" +``` -=== "JavaScript" +## Cost Optimization - ```javascript - // wrangler.toml configuration for stock market agent - /* - [[env.production.triggers.crons]] - cron = "0 16 * * MON-FRI" # 4 PM UTC (after US market close) - */ +- Use `gpt-4o-mini` for cost-effective analysis +- Set appropriate `max_tokens` limits +- Configure cron schedules to avoid unnecessary runs +- Implement error handling to prevent API waste - async function handleScheduledEvent(event, env) { - console.log('Stock market analysis triggered at:', new Date(event.scheduledTime)); - - try { - // Stock analysis swarm configuration - const swarmConfig = { - name: "Stock Market Analysis Swarm", - description: "Daily stock market analysis and trading insights", - agents: [ - { - agent_name: "Market Data Analyst", - description: "Analyzes market trends and price movements", - system_prompt: `You are an expert financial market analyst specializing in equity markets. - Analyze market trends, volume patterns, and price movements. - Provide technical analysis insights and identify key support/resistance levels. - Focus on major indices (S&P 500, NASDAQ, DOW) and sector performance.`, - model_name: "gpt-4o", - max_tokens: 3000, - temperature: 0.3, - role: "worker" - }, - { - agent_name: "Economic News Analyzer", - description: "Analyzes economic news impact on markets", - system_prompt: `You are a financial news analyst with expertise in market sentiment analysis. - Analyze recent economic news, earnings reports, and market-moving events. - Assess their potential impact on stock prices and market sentiment. - Identify key catalysts and risk factors for the next trading day.`, - model_name: "gpt-4o", - max_tokens: 3000, - temperature: 0.3, - role: "worker" - }, - { - agent_name: "Trading Strategy Advisor", - description: "Provides trading recommendations and risk assessment", - system_prompt: `You are a quantitative trading strategist with expertise in risk management. - Based on technical analysis and market sentiment, provide actionable trading insights. - Include risk assessment, position sizing recommendations, and key levels to watch. - Focus on risk-adjusted returns and downside protection strategies.`, - model_name: "gpt-4o", - max_tokens: 3000, - temperature: 0.4, - role: "worker" - } - ], - swarm_type: "SequentialWorkflow", - max_loops: 1, - task: `Analyze today's stock market performance and provide insights for tomorrow's trading session. - Include: 1) Market overview and key movers 2) Technical analysis of major indices - 3) Economic news impact assessment 4) Trading opportunities and risks - 5) Key levels to watch tomorrow. Format as a professional daily market report.`, - service_tier: "standard" - }; +## Environment Variables - // Execute the swarm - const response = await fetch('https://api.swarms.world/v1/swarm/completions', { - method: 'POST', - headers: { - 'x-api-key': env.SWARMS_API_KEY, - 'Content-Type': 'application/json' - }, - body: JSON.stringify(swarmConfig) - }); - - const result = await response.json(); - - if (response.ok) { - console.log('Stock analysis completed successfully'); - console.log('Cost:', result.metadata?.billing_info?.total_cost); - - // Store results in KV storage for retrieval - if (env.STOCK_REPORTS) { - const reportKey = `stock-report-${new Date().toISOString().split('T')[0]}`; - await env.STOCK_REPORTS.put(reportKey, JSON.stringify({ - timestamp: new Date().toISOString(), - analysis: result.output, - cost: result.metadata?.billing_info?.total_cost - })); - } - - // Optional: Send to webhook, email, or notification service - await sendNotification(env, result.output); - - } else { - console.error('Stock analysis failed:', result); - } - - } catch (error) { - console.error('Error in scheduled stock analysis:', error); - } - } +Add to `wrangler.toml`: - async function sendNotification(env, analysis) { - // Example: Send to Slack webhook - if (env.SLACK_WEBHOOK_URL) { - try { - await fetch(env.SLACK_WEBHOOK_URL, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - text: "📈 Daily Stock Market Analysis Ready", - attachments: [{ - color: "good", - text: typeof analysis === 'string' ? analysis.substring(0, 500) + '...' : 'Analysis completed', - footer: "Swarms Stock Analysis Agent" - }] - }) - }); - } catch (error) { - console.error('Failed to send Slack notification:', error); - } - } - } - - // API endpoint to retrieve stock reports - async function getStockReport(request, env) { - const url = new URL(request.url); - const date = url.searchParams.get('date') || new Date().toISOString().split('T')[0]; - const reportKey = `stock-report-${date}`; - - if (env.STOCK_REPORTS) { - const report = await env.STOCK_REPORTS.get(reportKey); - if (report) { - return new Response(report, { - headers: { 'Content-Type': 'application/json' } - }); - } - } - - return new Response(JSON.stringify({ error: 'Report not found' }), { - status: 404, - headers: { 'Content-Type': 'application/json' } - }); - } - ``` +```toml +[env.production.vars] +SWARMS_API_KEY = "your-swarms-api-key" -=== "TypeScript" +# Stock API Keys (get free keys from these providers) +STOCK_API_KEY = "your-alpha-vantage-key" # Free: https://www.alphavantage.co/support/#api-key +FMP_API_KEY = "your-fmp-key" # Free: https://financialmodelingprep.com/developer/docs - ```typescript - interface StockAnalysisResult { - timestamp: string; - analysis: any; - cost: number; - } +# Email Configuration (Mailgun) +MAILGUN_API_KEY = "your-mailgun-api-key" # Free: https://www.mailgun.com/ +MAILGUN_DOMAIN = "your-domain.com" +RECIPIENT_EMAIL = "investor@yourcompany.com" +MEDICAL_TEAM_EMAIL = "medical-team@hospital.com" +``` - async function handleScheduledEvent(event: ScheduledEvent, env: Env): Promise { - console.log('Stock market analysis triggered at:', new Date(event.scheduledTime)); - - try { - const swarmConfig = { - name: "Stock Market Analysis Swarm", - description: "Daily stock market analysis and trading insights", - agents: [ - { - agent_name: "Market Data Analyst", - description: "Analyzes market trends and price movements", - system_prompt: `You are an expert financial market analyst specializing in equity markets. - Analyze market trends, volume patterns, and price movements. - Provide technical analysis insights and identify key support/resistance levels. - Focus on major indices (S&P 500, NASDAQ, DOW) and sector performance.`, - model_name: "gpt-4o", - max_tokens: 3000, - temperature: 0.3, - role: "worker" - }, - { - agent_name: "Economic News Analyzer", - description: "Analyzes economic news impact on markets", - system_prompt: `You are a financial news analyst with expertise in market sentiment analysis. - Analyze recent economic news, earnings reports, and market-moving events. - Assess their potential impact on stock prices and market sentiment. - Identify key catalysts and risk factors for the next trading day.`, - model_name: "gpt-4o", - max_tokens: 3000, - temperature: 0.3, - role: "worker" - }, - { - agent_name: "Trading Strategy Advisor", - description: "Provides trading recommendations and risk assessment", - system_prompt: `You are a quantitative trading strategist with expertise in risk management. - Based on technical analysis and market sentiment, provide actionable trading insights. - Include risk assessment, position sizing recommendations, and key levels to watch. - Focus on risk-adjusted returns and downside protection strategies.`, - model_name: "gpt-4o", - max_tokens: 3000, - temperature: 0.4, - role: "worker" - } - ], - swarm_type: "SequentialWorkflow" as const, - max_loops: 1, - task: `Analyze today's stock market performance and provide insights for tomorrow's trading session. - Include: 1) Market overview and key movers 2) Technical analysis of major indices - 3) Economic news impact assessment 4) Trading opportunities and risks - 5) Key levels to watch tomorrow. Format as a professional daily market report.`, - service_tier: "standard" - }; +## API Endpoints Used - const response = await fetch('https://api.swarms.world/v1/swarm/completions', { - method: 'POST', - headers: { - 'x-api-key': env.SWARMS_API_KEY, - 'Content-Type': 'application/json' - }, - body: JSON.stringify(swarmConfig) - }); - - const result = await response.json(); - - if (response.ok) { - console.log('Stock analysis completed successfully'); - console.log('Cost:', result.metadata?.billing_info?.total_cost); - - if (env.STOCK_REPORTS) { - const reportKey = `stock-report-${new Date().toISOString().split('T')[0]}`; - const reportData: StockAnalysisResult = { - timestamp: new Date().toISOString(), - analysis: result.output, - cost: result.metadata?.billing_info?.total_cost - }; - - await env.STOCK_REPORTS.put(reportKey, JSON.stringify(reportData)); - } - - await sendNotification(env, result.output); - - } else { - console.error('Stock analysis failed:', result); - } - - } catch (error) { - console.error('Error in scheduled stock analysis:', error); - } - } +### Stock Data APIs +- **Alpha Vantage**: Real-time stock prices, technical indicators (RSI, MACD) +- **Financial Modeling Prep**: Market news, earnings data, company fundamentals +- **Free Tier Limits**: Alpha Vantage (5 calls/min), FMP (250 calls/day) - async function sendNotification(env: Env, analysis: any): Promise { - if (env.SLACK_WEBHOOK_URL) { - try { - await fetch(env.SLACK_WEBHOOK_URL, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - text: "📈 Daily Stock Market Analysis Ready", - attachments: [{ - color: "good", - text: typeof analysis === 'string' ? analysis.substring(0, 500) + '...' : 'Analysis completed', - footer: "Swarms Stock Analysis Agent" - }] - }) - }); - } catch (error) { - console.error('Failed to send Slack notification:', error); - } - } - } - ``` +### Real Market Data Flow +1. **Fetch Live Data**: Current prices, volume, technical indicators +2. **Get Market News**: Recent earnings, economic events, analyst reports +3. **AI Analysis**: Swarms agents analyze real data for actionable insights +4. **Email Reports**: Professional HTML emails with analysis and data tables +### Email Features +- **Stock Reports**: Daily market analysis with data tables and key movers +- **Healthcare Alerts**: Color-coded severity levels with immediate attention flags +- **HTML Formatting**: Professional email templates with styling +- **Mailgun Integration**: Reliable email delivery service From fdba766e08779661a5ac85bb0a33494c44eb5886 Mon Sep 17 00:00:00 2001 From: harshalmore31 Date: Tue, 5 Aug 2025 03:08:50 +0530 Subject: [PATCH 4/9] updated docs ! --- docs/swarms_cloud/cloudflare_workers.md | 638 +++++++++--------------- 1 file changed, 243 insertions(+), 395 deletions(-) diff --git a/docs/swarms_cloud/cloudflare_workers.md b/docs/swarms_cloud/cloudflare_workers.md index 085ca78b..ad73cce0 100644 --- a/docs/swarms_cloud/cloudflare_workers.md +++ b/docs/swarms_cloud/cloudflare_workers.md @@ -1,111 +1,176 @@ -# Cloudflare Workers with Swarms: Automated Cron Job Agents +# Cloudflare Workers with Swarms: Production AI Agents -Deploy scheduled AI agents on Cloudflare's global edge network for automated stock analysis and healthcare monitoring. This guide focuses on cron job agents that run automatically at scheduled intervals. +Deploy AI agents on Cloudflare's edge network with automatic cron scheduling and real-time data integration. This guide shows a production-ready implementation with both HTTP endpoints and scheduled triggers. -## Overview +## Architecture Overview -Cloudflare Workers with cron triggers enable automated agent execution for: -- **Stock Market Analysis**: Daily market reports and trading insights -- **Healthcare Monitoring**: Patient data analysis and alerts -- **Automated Reporting**: Scheduled business intelligence -- **Global Deployment**: Edge computing with zero cold starts +The Cloudflare Workers pattern uses two main handlers: +- **`fetch()`**: HTTP requests for testing and manual triggers +- **`scheduled()`**: Cron jobs for automated execution + +```javascript +export default { + // HTTP handler for manual testing + async fetch(request, env, ctx) { + // Handle web interface and API endpoints + }, + + // Cron handler for scheduled execution + async scheduled(event, env, ctx) { + ctx.waitUntil(handleStockAnalysis(event, env)); + } +}; +``` ## Quick Setup ### 1. Create Worker Project ```bash -npx create-cloudflare stock-agent worker +npm create cloudflare@latest stock-agent cd stock-agent ``` ### 2. Configure Cron Schedule -Edit `wrangler.toml`: - -```toml -name = "stock-analysis-agent" -main = "src/index.js" -compatibility_date = "2024-01-01" - -[env.production.vars] -SWARMS_API_KEY = "your-api-key-here" -SLACK_WEBHOOK_URL = "optional-slack-webhook" - -# Stock market analysis - after market close -[[env.production.triggers.crons]] -cron = "0 21 * * MON-FRI" # 9 PM UTC (4 PM EST) - -# Healthcare monitoring - every 4 hours -[[env.production.triggers.crons]] -cron = "0 */4 * * *" +Edit `wrangler.jsonc`: + +```jsonc +{ + "$schema": "node_modules/wrangler/config-schema.json", + "name": "stock-agent", + "main": "src/index.js", + "compatibility_date": "2025-08-03", + "observability": { + "enabled": true + }, + "triggers": { + "crons": [ + "0 */3 * * *" // Every 3 hours + ] + }, + "vars": { + "SWARMS_API_KEY": "your-api-key" + } +} ``` -## Stock Market Analysis Agent +## Complete Minimal Implementation -Automated daily stock analysis after market close: +Create `src/index.js`: ```javascript export default { - // Cron job handler - runs automatically + // HTTP handler - provides web interface and manual triggers + async fetch(request, env, ctx) { + const url = new URL(request.url); + + // Web interface for testing + if (url.pathname === '/') { + return new Response(` + + + + Stock Analysis Agent + + + +

📈 Stock Analysis Agent

+
Status: Online ✅
+ + +
+ + + + + `, { + headers: { 'Content-Type': 'text/html' } + }); + } + + // Manual trigger endpoint + if (url.pathname === '/trigger') { + try { + const result = await handleStockAnalysis(null, env); + return new Response(JSON.stringify({ + message: 'Analysis triggered', + timestamp: new Date().toISOString(), + result + }), { + headers: { 'Content-Type': 'application/json' } + }); + } catch (error) { + return new Response(JSON.stringify({ + error: error.message + }), { + status: 500, + headers: { 'Content-Type': 'application/json' } + }); + } + } + + return new Response('Not Found', { status: 404 }); + }, + + // Cron handler - runs automatically on schedule async scheduled(event, env, ctx) { ctx.waitUntil(handleStockAnalysis(event, env)); } }; +// Main analysis function used by both HTTP and cron triggers async function handleStockAnalysis(event, env) { + console.log('🚀 Starting stock analysis...'); + try { - // Step 1: Fetch real market data from multiple sources - const marketData = await fetchMarketData(env); + // Step 1: Fetch real market data (using Yahoo Finance - no API key needed) + const marketData = await fetchMarketData(); - // Step 2: Get market news - const marketNews = await fetchMarketNews(env); + // Check if we got valid data + const validSymbols = Object.keys(marketData).filter(symbol => !marketData[symbol].error); + if (validSymbols.length === 0) { + throw new Error('No valid market data retrieved'); + } - // Step 3: Send real data to Swarms agents for analysis + // Step 2: Send to Swarms AI agents const swarmConfig = { - name: "Real-Time Stock Analysis", - description: "Live market data analysis with AI agents", + name: "Stock Analysis", + description: "Real-time market analysis", agents: [ { agent_name: "Technical Analyst", - system_prompt: `You are a professional technical analyst. Analyze the provided real market data: - - Calculate key technical indicators (RSI, MACD, Moving Averages) - - Identify support and resistance levels - - Determine market trends and momentum - - Provide trading signals and price targets - Format your analysis professionally with specific price levels.`, + system_prompt: \`Analyze the provided stock data: + - Identify trends and key levels + - Provide trading signals + - Calculate technical indicators + Format analysis professionally.\`, model_name: "gpt-4o-mini", - max_tokens: 3000, + max_tokens: 1500, temperature: 0.2 - }, - { - agent_name: "Fundamental Analyst", - system_prompt: `You are a fundamental market analyst. Using the provided market news and data: - - Analyze earnings impact and company fundamentals - - Evaluate economic indicators and Fed policy effects - - Assess sector rotation and market sentiment - - Identify value opportunities and risks - Provide investment recommendations with risk assessment.`, - model_name: "gpt-4o-mini", - max_tokens: 3000, - temperature: 0.3 } ], - swarm_type: "ConcurrentWorkflow", - task: `Analyze the following real market data and news: - -MARKET DATA: -${JSON.stringify(marketData, null, 2)} - -MARKET NEWS: -${marketNews} - -Provide comprehensive analysis with: -1. Technical analysis with key levels -2. Fundamental analysis with catalysts -3. Trading recommendations -4. Risk assessment -5. Tomorrow's key levels to watch`, + swarm_type: "SequentialWorkflow", + task: \`Analyze this market data: \\${JSON.stringify(marketData, null, 2)}\`, max_loops: 1 }; @@ -118,370 +183,153 @@ Provide comprehensive analysis with: body: JSON.stringify(swarmConfig) }); - const result = await response.json(); - - if (response.ok) { - console.log('✅ Real-time stock analysis completed'); - console.log('💰 Cost:', result.metadata?.billing_info?.total_cost); - - // Send email directly - await sendEmailReport(env, result.output, marketData); + if (!response.ok) { + throw new Error(\`Swarms API error: \\${response.status}\`); } + + const result = await response.json(); + console.log('✅ Analysis completed'); + + return { + success: true, + analysis: result.output, + symbolsAnalyzed: validSymbols.length, + cost: result.usage?.billing_info?.total_cost + }; + } catch (error) { - console.error('❌ Real-time stock analysis failed:', error); + console.error('❌ Analysis failed:', error.message); + return { + success: false, + error: error.message + }; } } -// Fetch real market data from Alpha Vantage API -async function fetchMarketData(env) { - const symbols = ['SPY', 'QQQ', 'AAPL', 'MSFT', 'TSLA', 'NVDA']; +// Fetch market data from Yahoo Finance (free, no API key required) +async function fetchMarketData() { + const symbols = ['SPY', 'AAPL', 'MSFT', 'TSLA']; const marketData = {}; - for (const symbol of symbols) { + const promises = symbols.map(async (symbol) => { try { - // Get daily prices - const priceResponse = await fetch( - `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${symbol}&apikey=${env.STOCK_API_KEY}` - ); - const priceData = await priceResponse.json(); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 8000); - // Get technical indicators (RSI) - const rsiResponse = await fetch( - `https://www.alphavantage.co/query?function=RSI&symbol=${symbol}&interval=daily&time_period=14&series_type=close&apikey=${env.STOCK_API_KEY}` + const response = await fetch( + \`https://query1.finance.yahoo.com/v8/finance/chart/\\${symbol}\`, + { + signal: controller.signal, + headers: { 'User-Agent': 'Mozilla/5.0' } + } ); - const rsiData = await rsiResponse.json(); - - if (priceData['Time Series (Daily)'] && rsiData['Technical Analysis: RSI']) { - const latestDate = Object.keys(priceData['Time Series (Daily)'])[0]; - const latestPrice = priceData['Time Series (Daily)'][latestDate]; - const latestRSI = Object.values(rsiData['Technical Analysis: RSI'])[0]; - - marketData[symbol] = { - price: parseFloat(latestPrice['4. close']), - open: parseFloat(latestPrice['1. open']), - high: parseFloat(latestPrice['2. high']), - low: parseFloat(latestPrice['3. low']), - volume: parseInt(latestPrice['5. volume']), - change: parseFloat(latestPrice['4. close']) - parseFloat(latestPrice['1. open']), - change_percent: ((parseFloat(latestPrice['4. close']) - parseFloat(latestPrice['1. open'])) / parseFloat(latestPrice['1. open']) * 100).toFixed(2), - rsi: parseFloat(latestRSI?.RSI || 50), - date: latestDate - }; - } + clearTimeout(timeout); - // Rate limiting - Alpha Vantage allows 5 requests per minute on free tier - await new Promise(resolve => setTimeout(resolve, 12000)); + if (!response.ok) throw new Error(\`HTTP \\${response.status}\`); - } catch (error) { - console.error(`Error fetching data for ${symbol}:`, error); - marketData[symbol] = { error: 'Failed to fetch data' }; - } - } - - return marketData; -} - -// Fetch market news from Financial Modeling Prep (free tier available) -async function fetchMarketNews(env) { - try { - const newsResponse = await fetch( - `https://financialmodelingprep.com/api/v3/stock_news?tickers=AAPL,MSFT,TSLA,NVDA&limit=10&apikey=${env.FMP_API_KEY || 'demo'}` - ); - const newsData = await newsResponse.json(); - - if (Array.isArray(newsData)) { - return newsData.slice(0, 5).map(article => ({ - title: article.title, - text: article.text?.substring(0, 300) + '...', - publishedDate: article.publishedDate, - symbol: article.symbol, - url: article.url - })); - } - } catch (error) { - console.error('Error fetching news:', error); - } - - return "Market news temporarily unavailable"; -} - -// Send email report using Mailgun API -async function sendEmailReport(env, analysis, marketData) { - // Extract key market movers for email subject - const movers = Object.entries(marketData) - .filter(([symbol, data]) => data.change_percent && Math.abs(parseFloat(data.change_percent)) > 2) - .map(([symbol, data]) => `${symbol}: ${data.change_percent}%`) - .join(', '); - - const emailSubject = `📊 Daily Stock Analysis - ${new Date().toLocaleDateString()}`; - const emailBody = ` -

Daily Market Analysis Report

-

Date: ${new Date().toLocaleString()}

-

Key Market Movers: ${movers || 'Market stable'}

- -

AI Agent Analysis:

-
-
${analysis}
-
- -

Market Data Summary:

- - - - - ${Object.entries(marketData).map(([symbol, data]) => ` - - - - - - - - `).join('')} -
SymbolPriceChange %VolumeRSI
${symbol}$${data.price?.toFixed(2) || 'N/A'} - ${data.change_percent}% - ${data.volume?.toLocaleString() || 'N/A'}${data.rsi?.toFixed(1) || 'N/A'}
- -

Generated by Swarms AI Agent System

- `; - - // Send via Mailgun - const formData = new FormData(); - formData.append('from', `Stock Analysis Agent `); - formData.append('to', env.RECIPIENT_EMAIL); - formData.append('subject', emailSubject); - formData.append('html', emailBody); - - try { - const response = await fetch(`https://api.mailgun.net/v3/${env.MAILGUN_DOMAIN}/messages`, { - method: 'POST', - headers: { - 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}` - }, - body: formData - }); + const data = await response.json(); + const result = data.chart.result[0]; + const meta = result.meta; + + const currentPrice = meta.regularMarketPrice; + const previousClose = meta.previousClose; + const change = currentPrice - previousClose; + const changePercent = ((change / previousClose) * 100).toFixed(2); + + return [symbol, { + price: currentPrice, + change: change, + change_percent: changePercent, + volume: meta.regularMarketVolume, + currency: meta.currency + }]; - if (response.ok) { - console.log('✅ Email report sent successfully'); - } else { - console.error('❌ Failed to send email:', await response.text()); + } catch (error) { + return [symbol, { error: error.message }]; } - } catch (error) { - console.error('❌ Email sending error:', error); - } -} - -async function sendSlackNotification(webhookUrl, analysis) { - await fetch(webhookUrl, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - text: "📈 Daily Stock Market Analysis", - blocks: [{ - type: "section", - text: { - type: "mrkdwn", - text: `*Market Analysis Complete*\n\`\`\`${analysis.substring(0, 500)}...\`\`\`` - } - }] - }) }); -} -``` - -## Healthcare Monitoring Agent - -Automated patient monitoring and health alerts: -```javascript -export default { - async scheduled(event, env, ctx) { - // Determine which agent to run based on cron schedule - const hour = new Date().getHours(); - - if (hour % 4 === 0) { - // Every 4 hours - patient monitoring - ctx.waitUntil(handlePatientMonitoring(event, env)); + const results = await Promise.allSettled(promises); + results.forEach((result) => { + if (result.status === 'fulfilled' && result.value) { + const [symbol, data] = result.value; + marketData[symbol] = data; } - } -}; - -async function handlePatientMonitoring(event, env) { - const healthcareSwarm = { - name: "Patient Monitoring System", - description: "Automated patient health analysis and alerting", - agents: [ - { - agent_name: "Vital Signs Analyst", - system_prompt: `Analyze patient vital signs data for abnormalities: - - Heart rate patterns and irregularities - - Blood pressure trends - - Oxygen saturation levels - - Temperature variations - Flag critical conditions requiring immediate attention.`, - model_name: "gpt-4o-mini", - max_tokens: 2000, - temperature: 0.1 - }, - { - agent_name: "Risk Assessment Specialist", - system_prompt: `Evaluate patient risk factors and health trends: - - Medication interactions - - Chronic condition management - - Recovery progress assessment - - Early warning signs detection - Prioritize patients needing urgent care.`, - model_name: "gpt-4o-mini", - max_tokens: 2000, - temperature: 0.2 - } - ], - swarm_type: "ConcurrentWorkflow", - task: "Analyze current patient monitoring data and generate health status alerts for medical staff.", - max_loops: 1 - }; - - try { - const response = await fetch('https://api.swarms.world/v1/swarm/completions', { - method: 'POST', - headers: { - 'x-api-key': env.SWARMS_API_KEY, - 'Content-Type': 'application/json' - }, - body: JSON.stringify(healthcareSwarm) - }); + }); - const result = await response.json(); - - if (response.ok) { - console.log('🏥 Health monitoring completed'); - - // Send email alerts for all monitoring results - await sendHealthEmailAlert(env, result.output); - } - } catch (error) { - console.error('❌ Health monitoring failed:', error); - } + return marketData; } +``` -// Send healthcare email alerts -async function sendHealthEmailAlert(env, analysis) { - const severity = extractSeverity(analysis); - const isUrgent = severity === 'critical' || severity === 'urgent'; - - const emailSubject = `${isUrgent ? '🚨 URGENT' : '🏥'} Health Monitoring Alert - ${new Date().toLocaleString()}`; - const emailBody = ` -

Patient Monitoring Report

-

Timestamp: ${new Date().toLocaleString()}

-

Severity Level: ${severity.toUpperCase()}

- -

AI Health Analysis:

-
-
${analysis}
-
- - ${isUrgent ? '

⚠️ IMMEDIATE ATTENTION REQUIRED

' : ''} - -

Generated by Swarms Healthcare Monitoring Agent

- `; - - // Send email using Mailgun - const formData = new FormData(); - formData.append('from', `Healthcare Monitor `); - formData.append('to', env.MEDICAL_TEAM_EMAIL); - formData.append('subject', emailSubject); - formData.append('html', emailBody); +## Key Features Explained - try { - const response = await fetch(`https://api.mailgun.net/v3/${env.MAILGUN_DOMAIN}/messages`, { - method: 'POST', - headers: { - 'Authorization': `Basic ${btoa(`api:${env.MAILGUN_API_KEY}`)}` - }, - body: formData - }); +### 1. **Dual Handler Pattern** +- **`fetch()`**: Handles HTTP requests, provides web UI for testing +- **`scheduled()`**: Executes on cron schedule automatically +- **Shared Logic**: Both use the same `handleStockAnalysis()` function - if (response.ok) { - console.log('✅ Healthcare email alert sent successfully'); - } else { - console.error('❌ Failed to send healthcare email:', await response.text()); - } - } catch (error) { - console.error('❌ Healthcare email error:', error); - } +### 2. **Cron Configuration** +```jsonc +"triggers": { + "crons": [ + "0 */3 * * *" // Every 3 hours + "0 9 * * MON-FRI" // Weekdays at 9 AM + ] } +``` -function extractSeverity(analysis) { - if (analysis.includes('CRITICAL')) return 'critical'; - if (analysis.includes('URGENT')) return 'urgent'; - if (analysis.includes('WARNING')) return 'warning'; - return 'normal'; -} +### 3. **Real Data Integration** +- **Yahoo Finance API**: Free, no API key required +- **Error Handling**: Timeout management, fallback responses +- **Parallel Processing**: Fetch multiple symbols simultaneously -function getSeverityColor(severity) { - switch(severity) { - case 'critical': return 'red'; - case 'urgent': return 'orange'; - case 'warning': return 'yellow'; - default: return 'green'; - } -} -``` +### 4. **Production Features** +- **Web Interface**: Test manually via browser +- **Structured Responses**: Consistent JSON format +- **Error Recovery**: Graceful failure handling +- **Logging**: Console output for debugging ## Deployment ```bash -# Deploy your cron job agents +# Deploy to Cloudflare wrangler deploy -# Monitor logs +# View logs wrangler tail -# Test cron trigger manually -wrangler triggers cron "0 21 * * MON-FRI" +# Test cron manually +wrangler triggers cron "0 */3 * * *" ``` -## Cost Optimization - -- Use `gpt-4o-mini` for cost-effective analysis -- Set appropriate `max_tokens` limits -- Configure cron schedules to avoid unnecessary runs -- Implement error handling to prevent API waste - ## Environment Variables -Add to `wrangler.toml`: - -```toml -[env.production.vars] -SWARMS_API_KEY = "your-swarms-api-key" +Add to `wrangler.jsonc`: -# Stock API Keys (get free keys from these providers) -STOCK_API_KEY = "your-alpha-vantage-key" # Free: https://www.alphavantage.co/support/#api-key -FMP_API_KEY = "your-fmp-key" # Free: https://financialmodelingprep.com/developer/docs - -# Email Configuration (Mailgun) -MAILGUN_API_KEY = "your-mailgun-api-key" # Free: https://www.mailgun.com/ -MAILGUN_DOMAIN = "your-domain.com" -RECIPIENT_EMAIL = "investor@yourcompany.com" -MEDICAL_TEAM_EMAIL = "medical-team@hospital.com" +```jsonc +{ + "vars": { + "SWARMS_API_KEY": "your-swarms-api-key", + "MAILGUN_API_KEY": "optional-for-emails", + "MAILGUN_DOMAIN": "your-domain.com", + "RECIPIENT_EMAIL": "alerts@company.com" + } +} ``` -## API Endpoints Used +## Testing + +1. **Deploy**: `wrangler deploy` +2. **Visit URL**: Open your worker URL to see the web interface +3. **Manual Test**: Click "Start Analysis" button +4. **Cron Test**: `wrangler triggers cron "0 */3 * * *"` -### Stock Data APIs -- **Alpha Vantage**: Real-time stock prices, technical indicators (RSI, MACD) -- **Financial Modeling Prep**: Market news, earnings data, company fundamentals -- **Free Tier Limits**: Alpha Vantage (5 calls/min), FMP (250 calls/day) +## Production Tips -### Real Market Data Flow -1. **Fetch Live Data**: Current prices, volume, technical indicators -2. **Get Market News**: Recent earnings, economic events, analyst reports -3. **AI Analysis**: Swarms agents analyze real data for actionable insights -4. **Email Reports**: Professional HTML emails with analysis and data tables +- **Error Handling**: Always wrap API calls in try-catch +- **Timeouts**: Use AbortController for external API calls +- **Logging**: Use console.log for debugging in Cloudflare dashboard +- **Rate Limits**: Yahoo Finance is free but has rate limits +- **Cost Control**: Set appropriate `max_tokens` in agent config -### Email Features -- **Stock Reports**: Daily market analysis with data tables and key movers -- **Healthcare Alerts**: Color-coded severity levels with immediate attention flags -- **HTML Formatting**: Professional email templates with styling -- **Mailgun Integration**: Reliable email delivery service +This minimal implementation provides a solid foundation for production AI agents on Cloudflare Workers with automated scheduling and real-time data integration. \ No newline at end of file From 45f72f5a3307a9735ce8661d25c00a55c96664c2 Mon Sep 17 00:00:00 2001 From: harshalmore31 Date: Tue, 5 Aug 2025 03:27:35 +0530 Subject: [PATCH 5/9] fixed docs ! --- docs/swarms_cloud/cloudflare_workers.md | 935 ++++++++++++++++++++---- 1 file changed, 781 insertions(+), 154 deletions(-) diff --git a/docs/swarms_cloud/cloudflare_workers.md b/docs/swarms_cloud/cloudflare_workers.md index ad73cce0..a28171fc 100644 --- a/docs/swarms_cloud/cloudflare_workers.md +++ b/docs/swarms_cloud/cloudflare_workers.md @@ -1,44 +1,59 @@ -# Cloudflare Workers with Swarms: Production AI Agents +# Deploy Autonomous Cron Agents with Swarms API on Cloudflare Workers -Deploy AI agents on Cloudflare's edge network with automatic cron scheduling and real-time data integration. This guide shows a production-ready implementation with both HTTP endpoints and scheduled triggers. +Deploy intelligent, self-executing AI agents powered by Swarms API on Cloudflare's global edge network. Build production-ready autonomous agents that run on automated schedules, fetch real-time data, perform sophisticated analysis using Swarms AI, and take automated actions across 330+ cities worldwide. -## Architecture Overview +## What Are Autonomous Cron Agents? -The Cloudflare Workers pattern uses two main handlers: -- **`fetch()`**: HTTP requests for testing and manual triggers -- **`scheduled()`**: Cron jobs for automated execution +Autonomous cron agents combine **Swarms API intelligence** with **Cloudflare Workers edge computing** to create AI-powered systems that: +- **Execute automatically** on predefined schedules without human intervention +- **Fetch real-time data** from external sources (APIs, databases, IoT sensors) +- **Perform intelligent analysis** using specialized Swarms AI agents +- **Take automated actions** based on analysis findings (alerts, reports, decisions) +- **Scale globally** on Cloudflare's edge network with sub-100ms response times worldwide -```javascript -export default { - // HTTP handler for manual testing - async fetch(request, env, ctx) { - // Handle web interface and API endpoints - }, - - // Cron handler for scheduled execution - async scheduled(event, env, ctx) { - ctx.waitUntil(handleStockAnalysis(event, env)); - } -}; +## Architecture Overview + +``` +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ +│ Cloudflare │ │ Data Sources │ │ Swarms API │ +│ Workers Cron │ │ │ │ │ +│ "0 */3 * * *" │───▶│ Yahoo Finance │───▶│ Multi-Agent │ +│ │ │ Medical APIs │ │ Intelligence │ +│ scheduled() │ │ News Feeds │ │ Autonomous │ +│ Global Edge │ │ IoT Sensors │ │ Actions │ +└─────────────────┘ └─────────────────┘ └─────────────────┘ ``` -## Quick Setup +**Key Benefits:** +- **24/7 Autonomous Operation**: Zero human intervention required +- **Global Edge Deployment**: Cloudflare's 330+ city network for ultra-low latency +- **Swarms AI Intelligence**: Live data analysis with specialized AI agents +- **Automated Decision Making**: Smart actions based on Swarms agent insights +- **Enterprise Reliability**: Production-grade error handling and monitoring -### 1. Create Worker Project +## Quick Start: Deploy Autonomous Stock Analysis Agent + +Create your first autonomous financial intelligence agent powered by Swarms API and deployed on Cloudflare Workers edge network. + +### 1. Cloudflare Workers Project Setup ```bash -npm create cloudflare@latest stock-agent -cd stock-agent +# Create new Cloudflare Workers project +npm create cloudflare@latest autonomous-stock-agent +cd autonomous-stock-agent + +# Install dependencies for Swarms API integration +npm run start ``` -### 2. Configure Cron Schedule +### 2. Configure Cloudflare Workers Cron Schedule -Edit `wrangler.jsonc`: +Edit `wrangler.jsonc` to set up autonomous execution: ```jsonc { "$schema": "node_modules/wrangler/config-schema.json", - "name": "stock-agent", + "name": "autonomous-stock-agent", "main": "src/index.js", "compatibility_date": "2025-08-03", "observability": { @@ -46,58 +61,116 @@ Edit `wrangler.jsonc`: }, "triggers": { "crons": [ - "0 */3 * * *" // Every 3 hours + "0 */3 * * *" // Cloudflare Workers cron: autonomous analysis every 3 hours ] }, "vars": { - "SWARMS_API_KEY": "your-api-key" + "SWARMS_API_KEY": "your-swarms-api-key" // Your Swarms API key } } ``` -## Complete Minimal Implementation +### 3. Cloudflare Workers + Swarms API Implementation Create `src/index.js`: ```javascript export default { - // HTTP handler - provides web interface and manual triggers + // Cloudflare Workers fetch handler - Web interface for monitoring async fetch(request, env, ctx) { const url = new URL(request.url); - // Web interface for testing if (url.pathname === '/') { return new Response(` - Stock Analysis Agent + Autonomous Stock Intelligence Agent -

📈 Stock Analysis Agent

-
Status: Online ✅
- - -
+
+
+

🤖 Autonomous Stock Intelligence Agent

+

Powered by Swarms API • Running on Cloudflare Workers

+
+ Swarms AI + Cloudflare Edge + Real-time + Autonomous +
+
+ +
+ 🚀 Status: Swarms AI agents active on Cloudflare edge, monitoring markets 24/7 +
+ +
+ +
+ +
+
+

Swarms AI agents analyzing live market data on Cloudflare edge...

+
+ +
+
@@ -108,12 +181,11 @@ export default { }); } - // Manual trigger endpoint - if (url.pathname === '/trigger') { + if (url.pathname === '/execute') { try { - const result = await handleStockAnalysis(null, env); + const result = await executeAutonomousAnalysis(null, env); return new Response(JSON.stringify({ - message: 'Analysis triggered', + message: 'Autonomous analysis executed successfully', timestamp: new Date().toISOString(), result }), { @@ -121,7 +193,9 @@ export default { }); } catch (error) { return new Response(JSON.stringify({ - error: error.message + error: error.message, + timestamp: new Date().toISOString(), + system: 'autonomous-agent' }), { status: 500, headers: { 'Content-Type': 'application/json' } @@ -129,207 +203,760 @@ export default { } } - return new Response('Not Found', { status: 404 }); + return new Response('Autonomous Agent Endpoint Not Found', { status: 404 }); }, - // Cron handler - runs automatically on schedule + // Cloudflare Workers cron handler - triggered by scheduled events async scheduled(event, env, ctx) { - ctx.waitUntil(handleStockAnalysis(event, env)); + console.log('🚀 Cloudflare Workers cron triggered - executing Swarms AI analysis'); + ctx.waitUntil(executeAutonomousAnalysis(event, env)); } }; -// Main analysis function used by both HTTP and cron triggers -async function handleStockAnalysis(event, env) { - console.log('🚀 Starting stock analysis...'); +// Core function combining Cloudflare Workers execution with Swarms API intelligence +async function executeAutonomousAnalysis(event, env) { + console.log('🤖 Cloudflare Workers executing Swarms AI stock intelligence analysis...'); try { - // Step 1: Fetch real market data (using Yahoo Finance - no API key needed) - const marketData = await fetchMarketData(); + // Step 1: Autonomous data collection from multiple sources + console.log('📊 Executing autonomous data collection...'); + const marketIntelligence = await collectMarketIntelligence(); - // Check if we got valid data - const validSymbols = Object.keys(marketData).filter(symbol => !marketData[symbol].error); - if (validSymbols.length === 0) { - throw new Error('No valid market data retrieved'); + const validData = Object.keys(marketIntelligence).filter(symbol => !marketIntelligence[symbol].error); + if (validData.length === 0) { + throw new Error('Autonomous data collection failed - no valid market intelligence gathered'); } - // Step 2: Send to Swarms AI agents - const swarmConfig = { - name: "Stock Analysis", - description: "Real-time market analysis", + console.log(\`✅ Autonomous data collection successful: \${validData.length} sources\`); + + // Step 2: Deploy Swarms AI agents for autonomous analysis + console.log('🧠 Deploying Swarms AI agents for autonomous intelligence generation...'); + const swarmConfiguration = { + name: "Autonomous Market Intelligence Swarm", + description: "Self-executing financial analysis and decision support system", agents: [ { - agent_name: "Technical Analyst", - system_prompt: \`Analyze the provided stock data: - - Identify trends and key levels - - Provide trading signals - - Calculate technical indicators - Format analysis professionally.\`, + agent_name: "Autonomous Technical Intelligence Agent", + system_prompt: \`You are an autonomous technical analysis AI agent operating 24/7. Provide: + - Real-time trend identification and momentum analysis + - Dynamic support/resistance level calculations + - Technical indicator signals (RSI, MACD, moving averages) + - Autonomous price targets and risk assessments + - Self-executing trading signal recommendations + + Format your analysis as a professional autonomous intelligence briefing for automated systems.\`, model_name: "gpt-4o-mini", - max_tokens: 1500, + max_tokens: 2500, temperature: 0.2 + }, + { + agent_name: "Autonomous Market Sentiment Agent", + system_prompt: \`You are an autonomous market sentiment analysis AI agent. Continuously evaluate: + - Real-time market psychology and investor behavior patterns + - Volume analysis and institutional activity detection + - Risk-on vs risk-off sentiment shifts + - Autonomous sector rotation and leadership identification + - Self-executing market timing recommendations + + Provide actionable intelligence for autonomous decision-making systems.\`, + model_name: "gpt-4o-mini", + max_tokens: 2500, + temperature: 0.3 } ], - swarm_type: "SequentialWorkflow", - task: \`Analyze this market data: \\${JSON.stringify(marketData, null, 2)}\`, + swarm_type: "ConcurrentWorkflow", + task: \`Execute autonomous analysis of real-time market intelligence: + + LIVE MARKET INTELLIGENCE: + \${JSON.stringify(marketIntelligence, null, 2)} + + Generate comprehensive autonomous intelligence report including: + 1. Technical analysis with specific autonomous entry/exit recommendations + 2. Market sentiment assessment with timing signals for automated systems + 3. Risk management protocols for autonomous execution + 4. Self-executing action recommendations + 5. Key monitoring parameters for next autonomous cycle + + Focus on actionable intelligence for autonomous trading systems and automated decision making.\`, max_loops: 1 }; + // Execute Swarms API call from Cloudflare Workers edge const response = await fetch('https://api.swarms.world/v1/swarm/completions', { method: 'POST', headers: { 'x-api-key': env.SWARMS_API_KEY, 'Content-Type': 'application/json' }, - body: JSON.stringify(swarmConfig) + body: JSON.stringify(swarmConfiguration) }); if (!response.ok) { - throw new Error(\`Swarms API error: \\${response.status}\`); + const errorText = await response.text(); + throw new Error(\`Swarms API autonomous execution failed: \${response.status} - \${errorText}\`); } - const result = await response.json(); - console.log('✅ Analysis completed'); + const analysisResult = await response.json(); + const intelligenceReport = analysisResult.output; + + console.log('✅ Autonomous Swarms AI analysis completed successfully'); + console.log(\`💰 Autonomous execution cost: \${analysisResult.usage?.billing_info?.total_cost || 'N/A'}\`); + + // Step 3: Execute autonomous actions based on intelligence + if (env.AUTONOMOUS_ALERTS_EMAIL) { + console.log('📧 Executing autonomous alert system...'); + await executeAutonomousAlerts(env, intelligenceReport, marketIntelligence); + } return { success: true, - analysis: result.output, - symbolsAnalyzed: validSymbols.length, - cost: result.usage?.billing_info?.total_cost + analysis: intelligenceReport, + symbolsAnalyzed: validData.length, + cost: analysisResult.usage?.billing_info?.total_cost || analysisResult.metadata?.billing_info?.total_cost, + executionTime: new Date().toISOString(), + nextExecution: 'Scheduled for next autonomous cron trigger', + autonomousSystem: 'Swarms AI Agents' }; } catch (error) { - console.error('❌ Analysis failed:', error.message); + console.error('❌ Autonomous analysis execution failed:', error.message); return { success: false, - error: error.message + error: error.message, + executionTime: new Date().toISOString(), + autonomousSystem: 'Error in autonomous pipeline' }; } } -// Fetch market data from Yahoo Finance (free, no API key required) -async function fetchMarketData() { - const symbols = ['SPY', 'AAPL', 'MSFT', 'TSLA']; - const marketData = {}; +// Autonomous market intelligence collection +async function collectMarketIntelligence() { + const targetSymbols = ['SPY', 'QQQ', 'AAPL', 'MSFT', 'NVDA', 'TSLA']; + const marketIntelligence = {}; + + console.log('🎯 Executing autonomous multi-source data collection...'); - const promises = symbols.map(async (symbol) => { + const dataCollectionPromises = targetSymbols.map(async (symbol) => { try { const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 8000); + const timeout = setTimeout(() => controller.abort(), 10000); + // Autonomous data collection from Yahoo Finance API const response = await fetch( - \`https://query1.finance.yahoo.com/v8/finance/chart/\\${symbol}\`, + \`https://query1.finance.yahoo.com/v8/finance/chart/\${symbol}\`, { signal: controller.signal, - headers: { 'User-Agent': 'Mozilla/5.0' } + headers: { + 'User-Agent': 'Mozilla/5.0 (autonomous-swarms-agent) AppleWebKit/537.36' + } } ); clearTimeout(timeout); - if (!response.ok) throw new Error(\`HTTP \\${response.status}\`); + if (!response.ok) { + throw new Error(\`Autonomous data collection failed: HTTP \${response.status}\`); + } const data = await response.json(); - const result = data.chart.result[0]; - const meta = result.meta; + const chartResult = data.chart.result[0]; + const meta = chartResult.meta; + + if (!meta) { + throw new Error('Invalid market intelligence structure received'); + } const currentPrice = meta.regularMarketPrice; const previousClose = meta.previousClose; - const change = currentPrice - previousClose; - const changePercent = ((change / previousClose) * 100).toFixed(2); + const dayChange = currentPrice - previousClose; + const changePercent = ((dayChange / previousClose) * 100).toFixed(2); + + console.log(\`📈 \${symbol}: $\${currentPrice} (\${changePercent}%) - Autonomous collection successful\`); return [symbol, { price: currentPrice, - change: change, + change: dayChange, change_percent: changePercent, - volume: meta.regularMarketVolume, - currency: meta.currency + volume: meta.regularMarketVolume || 0, + market_cap: meta.marketCap || 0, + pe_ratio: meta.trailingPE || 0, + day_high: meta.regularMarketDayHigh, + day_low: meta.regularMarketDayLow, + fifty_two_week_high: meta.fiftyTwoWeekHigh, + fifty_two_week_low: meta.fiftyTwoWeekLow, + currency: meta.currency || 'USD', + market_state: meta.marketState, + autonomous_collection_time: new Date().toISOString(), + data_quality: 'high' }]; } catch (error) { - return [symbol, { error: error.message }]; + console.error(\`❌ Autonomous collection failed for \${symbol}:\`, error.message); + return [symbol, { + error: \`Autonomous collection failed: \${error.message}\`, + autonomous_collection_time: new Date().toISOString(), + data_quality: 'failed' + }]; } }); - const results = await Promise.allSettled(promises); + const results = await Promise.allSettled(dataCollectionPromises); results.forEach((result) => { if (result.status === 'fulfilled' && result.value) { const [symbol, data] = result.value; - marketData[symbol] = data; + marketIntelligence[symbol] = data; } }); - return marketData; + const successfulCollections = Object.keys(marketIntelligence).filter(k => !marketIntelligence[k]?.error).length; + console.log(\`📊 Autonomous intelligence collection completed: \${successfulCollections}/\${targetSymbols.length} successful\`); + + return marketIntelligence; } -``` -## Key Features Explained +// Autonomous alert and notification system +async function executeAutonomousAlerts(env, intelligenceReport, marketIntelligence) { + if (!env.MAILGUN_API_KEY || !env.MAILGUN_DOMAIN || !env.AUTONOMOUS_ALERTS_EMAIL) { + console.log('⚠️ Autonomous alert system not configured - skipping notifications'); + return; + } -### 1. **Dual Handler Pattern** -- **`fetch()`**: Handles HTTP requests, provides web UI for testing -- **`scheduled()`**: Executes on cron schedule automatically -- **Shared Logic**: Both use the same `handleStockAnalysis()` function + try { + // Autonomous detection of significant market movements + const significantMovements = Object.entries(marketIntelligence) + .filter(([symbol, data]) => data.change_percent && Math.abs(parseFloat(data.change_percent)) > 3) + .map(([symbol, data]) => \`\${symbol}: \${data.change_percent}%\`) + .join(', '); -### 2. **Cron Configuration** -```jsonc -"triggers": { - "crons": [ - "0 */3 * * *" // Every 3 hours - "0 9 * * MON-FRI" // Weekdays at 9 AM - ] + const alertSubject = \`🤖 Autonomous Market Intelligence Alert - \${new Date().toLocaleDateString()}\`; + + const alertBody = \` + + + + + + +
+
+

🤖 Autonomous Market Intelligence

+

AI-Powered Autonomous Financial Analysis • Swarms API

+
+ Autonomous + Real-time + AI-Powered + Global Edge +
+

Generated: \${new Date().toLocaleString()}

+
+ +
+
+

🚀 Autonomous Analysis Execution Complete

+

Significant Market Movements Detected: \${significantMovements || 'Market within normal volatility parameters'}

+

Next Autonomous Cycle: Scheduled automatically

+
+ +
+

🧠 Autonomous AI Intelligence Report

+

Generated by autonomous Swarms AI agents with real-time market intelligence:

+
\${intelligenceReport}
+
+ +
+

📊 Real-Time Market Intelligence

+ + + + + + + + + + + + + \${Object.entries(marketIntelligence) + .filter(([symbol, data]) => !data.error) + .map(([symbol, data]) => \` + + + + + + + + + \`).join('')} + +
SymbolPriceChangeVolumeMarket StateData Quality
\${symbol}$\${data.price?.toFixed(2) || 'N/A'} + \${parseFloat(data.change_percent) >= 0 ? '+' : ''}\${data.change_percent}% + \${data.volume?.toLocaleString() || 'N/A'}\${data.market_state || 'N/A'}\${data.data_quality || 'N/A'}
+
+
+ + +
+ + + \`; + + const formData = new FormData(); + formData.append('from', \`Autonomous Market Intelligence \`); + formData.append('to', env.AUTONOMOUS_ALERTS_EMAIL); + formData.append('subject', alertSubject); + formData.append('html', alertBody); + + const response = await fetch(\`https://api.mailgun.net/v3/\${env.MAILGUN_DOMAIN}/messages\`, { + method: 'POST', + headers: { + 'Authorization': \`Basic \${btoa(\`api:\${env.MAILGUN_API_KEY}\`)}\` + }, + body: formData + }); + + if (response.ok) { + console.log('✅ Autonomous alert system executed successfully'); + } else { + console.error('❌ Autonomous alert system execution failed:', await response.text()); + } + + } catch (error) { + console.error('❌ Autonomous alert system error:', error.message); + } } ``` -### 3. **Real Data Integration** -- **Yahoo Finance API**: Free, no API key required -- **Error Handling**: Timeout management, fallback responses -- **Parallel Processing**: Fetch multiple symbols simultaneously +## Autonomous Healthcare Intelligence Agent -### 4. **Production Features** -- **Web Interface**: Test manually via browser -- **Structured Responses**: Consistent JSON format -- **Error Recovery**: Graceful failure handling -- **Logging**: Console output for debugging +Deploy autonomous healthcare agents that provide 24/7 patient monitoring with intelligent analysis: -## Deployment +```javascript +export default { + async fetch(request, env, ctx) { + const url = new URL(request.url); + + if (url.pathname === '/') { + return new Response(` + + + + Autonomous Healthcare Intelligence + + + +
+
+

🏥 Autonomous Healthcare Intelligence

+

AI-Powered 24/7 Patient Monitoring • Autonomous Medical Analysis

+
+ Autonomous + 24/7 Monitoring + AI-Powered + Real-time +
+
+ +
+
+

✅ Normal Status

+

Patients: 15

+

Stable vital signs

+

Autonomous monitoring active

+
+
+

⚠️ Monitoring Required

+

Patients: 3

+

Elevated parameters

+

Enhanced surveillance

+
+
+

🚨 Critical Alert

+

Patients: 1

+

Immediate intervention

+

Emergency protocols active

+
+
+ +
+ +
+ +
+
+ + + + + `, { + headers: { 'Content-Type': 'text/html' } + }); + } + + if (url.pathname === '/health-intelligence') { + try { + const result = await executeAutonomousHealthIntelligence(null, env); + return new Response(JSON.stringify({ + message: 'Autonomous health intelligence analysis executed', + timestamp: new Date().toISOString(), + result + }), { + headers: { 'Content-Type': 'application/json' } + }); + } catch (error) { + return new Response(JSON.stringify({ + error: error.message, + system: 'autonomous-healthcare-intelligence' + }), { + status: 500, + headers: { 'Content-Type': 'application/json' } + }); + } + } + + return new Response('Autonomous Healthcare Intelligence Endpoint Not Found', { status: 404 }); + }, -```bash -# Deploy to Cloudflare -wrangler deploy + // Autonomous healthcare monitoring - every 30 minutes + async scheduled(event, env, ctx) { + console.log('🏥 Autonomous healthcare intelligence system triggered'); + ctx.waitUntil(executeAutonomousHealthIntelligence(event, env)); + } +}; -# View logs -wrangler tail +async function executeAutonomousHealthIntelligence(event, env) { + console.log('🏥 Autonomous healthcare intelligence system executing...'); + + try { + // Autonomous patient data collection + const patientIntelligence = await collectPatientIntelligence(); + + // Deploy autonomous Swarms healthcare AI agents + const healthIntelligenceConfig = { + name: "Autonomous Healthcare Intelligence Swarm", + description: "24/7 autonomous patient monitoring and medical analysis system", + agents: [ + { + agent_name: "Autonomous Vital Signs Intelligence Agent", + system_prompt: \`You are an autonomous healthcare AI agent providing 24/7 patient monitoring. Analyze: + - Continuous heart rate monitoring and arrhythmia detection (Normal: 60-100 bpm) + - Autonomous blood pressure trend analysis (Normal: <140/90 mmHg) + - Real-time oxygen saturation monitoring (Normal: >95%) + - Continuous temperature surveillance (Normal: 97-99°F) + + Classify each patient autonomously as: NORMAL_MONITORING, ENHANCED_SURVEILLANCE, or CRITICAL_INTERVENTION + For critical findings, trigger autonomous emergency protocols.\`, + model_name: "gpt-4o-mini", + max_tokens: 2500, + temperature: 0.05 + }, + { + agent_name: "Autonomous Medical Risk Assessment Agent", + system_prompt: \`You are an autonomous medical AI providing continuous risk assessment. Monitor: + - Autonomous drug interaction analysis and medication safety + - Real-time disease progression and complication detection + - Continuous fall risk and mobility assessment + - Autonomous emergency intervention requirements + + Provide autonomous risk stratification and intervention priorities. + Focus on predictive analytics and early autonomous warning systems.\`, + model_name: "gpt-4o-mini", + max_tokens: 2500, + temperature: 0.05 + } + ], + swarm_type: "ConcurrentWorkflow", + task: \`Execute autonomous 24/7 healthcare intelligence analysis: + + PATIENT INTELLIGENCE DATA: + \${JSON.stringify(patientIntelligence, null, 2)} + + Generate autonomous healthcare intelligence including: + 1. Individual patient autonomous risk assessment and monitoring status + 2. Critical autonomous intervention requirements and emergency protocols + 3. Autonomous alert recommendations and escalation procedures + 4. Predictive health analytics and preventive care suggestions + 5. Next autonomous monitoring cycle parameters and priorities + + Focus on autonomous decision support for medical staff and emergency response systems.\`, + max_loops: 1 + }; -# Test cron manually -wrangler triggers cron "0 */3 * * *" + const response = await fetch('https://api.swarms.world/v1/swarm/completions', { + method: 'POST', + headers: { + 'x-api-key': env.SWARMS_API_KEY, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(healthIntelligenceConfig) + }); + + if (!response.ok) { + throw new Error(\`Autonomous healthcare intelligence failed: \${response.status}\`); + } + + const result = await response.json(); + const healthIntelligence = result.output; + + // Autonomous severity assessment + const severity = assessAutonomousHealthSeverity(healthIntelligence); + + console.log(\`✅ Autonomous healthcare intelligence completed - Severity: \${severity}\`); + + // Autonomous emergency response system + if (severity === 'critical' && env.HEALTHCARE_EMERGENCY_EMAIL) { + console.log('🚨 Executing autonomous emergency response protocol...'); + await executeAutonomousEmergencyResponse(env, healthIntelligence, patientIntelligence); + } + + return { + success: true, + analysis: healthIntelligence, + severity: severity, + patientsAnalyzed: Object.keys(patientIntelligence).length, + executionTime: new Date().toISOString(), + nextAutonomousMonitoring: 'Scheduled for next autonomous cycle', + autonomousSystem: 'Swarms Healthcare AI' + }; + + } catch (error) { + console.error('❌ Autonomous healthcare intelligence failed:', error.message); + return { + success: false, + error: error.message, + severity: 'autonomous_system_error', + executionTime: new Date().toISOString() + }; + } +} + +// Autonomous patient intelligence collection +async function collectPatientIntelligence() { + // In production, connect to EMR systems, IoT devices, and medical databases + return { + "ICU_Autonomous_001": { + name: "Sarah Johnson", + age: 68, + room: "ICU-205", + condition: "Post-cardiac surgery - autonomous monitoring", + vitals: { + heart_rate: 95, + blood_pressure_systolic: 135, + blood_pressure_diastolic: 88, + oxygen_saturation: 97, + temperature: 98.8, + respiratory_rate: 16 + }, + medications: ["Metoprolol", "Warfarin", "Furosemide"], + risk_factors: ["Diabetes", "Hypertension", "Previous MI"], + autonomous_monitoring_level: "enhanced", + last_updated: new Date().toISOString() + }, + "Ward_Autonomous_002": { + name: "Michael Chen", + age: 45, + room: "Ward-301", + condition: "Pneumonia recovery - autonomous surveillance", + vitals: { + heart_rate: 88, + blood_pressure_systolic: 128, + blood_pressure_diastolic: 82, + oxygen_saturation: 94, // Slightly low - autonomous flag + temperature: 100.1, // Mild fever - autonomous flag + respiratory_rate: 20 + }, + medications: ["Azithromycin", "Albuterol"], + risk_factors: ["Asthma", "Smoking history"], + autonomous_monitoring_level: "standard", + last_updated: new Date().toISOString() + }, + "Critical_Autonomous_003": { + name: "Elena Rodriguez", + age: 72, + room: "ICU-208", + condition: "Sepsis - autonomous critical monitoring", + vitals: { + heart_rate: 115, // Elevated - autonomous critical flag + blood_pressure_systolic: 85, // Low - autonomous critical flag + blood_pressure_diastolic: 55, // Low - autonomous critical flag + oxygen_saturation: 89, // Critical - autonomous emergency flag + temperature: 103.2, // High fever - autonomous critical flag + respiratory_rate: 28 // Elevated - autonomous critical flag + }, + medications: ["Vancomycin", "Norepinephrine", "Hydrocortisone"], + risk_factors: ["Sepsis", "Multi-organ dysfunction", "Advanced age"], + autonomous_monitoring_level: "critical", + last_updated: new Date().toISOString() + } + }; +} + +function assessAutonomousHealthSeverity(intelligenceReport) { + const reportText = typeof intelligenceReport === 'string' ? intelligenceReport : JSON.stringify(intelligenceReport); + + if (reportText.includes('CRITICAL_INTERVENTION') || + reportText.includes('EMERGENCY') || + reportText.includes('IMMEDIATE_ACTION') || + reportText.includes('SEPSIS') || + reportText.includes('CARDIAC_ARREST') || + reportText.includes('RESPIRATORY_FAILURE')) { + return 'critical'; + } else if (reportText.includes('ENHANCED_SURVEILLANCE') || + reportText.includes('ELEVATED') || + reportText.includes('CONCERNING') || + reportText.includes('ABNORMAL') || + reportText.includes('MONITORING_REQUIRED')) { + return 'warning'; + } + return 'normal'; +} + +async function executeAutonomousEmergencyResponse(env, intelligenceReport, patientIntelligence) { + console.log('🚨 Autonomous emergency response protocol executing...'); + + // Autonomous emergency response would include: + // - Immediate medical team notifications + // - Automated equipment preparation alerts + // - Emergency response coordination + // - Real-time escalation to on-call physicians + // - Integration with hospital emergency systems +} ``` -## Environment Variables +## Deployment & Configuration -Add to `wrangler.jsonc`: +### Environment Variables + +Configure your Cloudflare Workers deployment with Swarms API: ```jsonc { "vars": { "SWARMS_API_KEY": "your-swarms-api-key", - "MAILGUN_API_KEY": "optional-for-emails", - "MAILGUN_DOMAIN": "your-domain.com", - "RECIPIENT_EMAIL": "alerts@company.com" + "AUTONOMOUS_ALERTS_EMAIL": "intelligence@yourcompany.com", + "HEALTHCARE_EMERGENCY_EMAIL": "emergency@hospital.com", + "MAILGUN_API_KEY": "your-mailgun-key", + "MAILGUN_DOMAIN": "intelligence.yourcompany.com" + } +} +``` + +### Cloudflare Workers Cron Scheduling Patterns + +```jsonc +{ + "triggers": { + "crons": [ + "0 */3 * * *", // Financial Swarms agents every 3 hours + "*/30 * * * *", // Healthcare Swarms monitoring every 30 minutes + "0 9,15,21 * * *", // Daily Swarms intelligence briefings + "*/5 * * * *" // Critical Swarms systems every 5 minutes + ] } } ``` -## Testing +### Cloudflare Workers Deployment Commands + +```bash +# Deploy Swarms AI agents to Cloudflare Workers +wrangler deploy + +# Monitor Cloudflare Workers execution logs +wrangler tail + +# Test Cloudflare Workers cron triggers manually +wrangler triggers cron "0 */3 * * *" + +``` + +## Production Best Practices + +### 1. **Cloudflare Workers + Swarms API Integration** +- Implement comprehensive error handling for both platforms +- Use Cloudflare Workers KV for caching Swarms API responses +- Leverage Cloudflare Workers analytics for monitoring -1. **Deploy**: `wrangler deploy` -2. **Visit URL**: Open your worker URL to see the web interface -3. **Manual Test**: Click "Start Analysis" button -4. **Cron Test**: `wrangler triggers cron "0 */3 * * *"` +### 2. **Cost Optimization** +- Monitor Swarms API usage and costs +- Use Cloudflare Workers free tier (100K requests/day) +- Implement intelligent batching for Swarms API efficiency +- Use cost-effective Swarms models (gpt-4o-mini recommended) -## Production Tips +### 3. **Security & Compliance** +- Secure Swarms API keys in Cloudflare Workers environment variables +- Use Cloudflare Workers secrets for sensitive data +- Audit AI decisions and maintain compliance logs +- HIPAA compliance for healthcare applications -- **Error Handling**: Always wrap API calls in try-catch -- **Timeouts**: Use AbortController for external API calls -- **Logging**: Use console.log for debugging in Cloudflare dashboard -- **Rate Limits**: Yahoo Finance is free but has rate limits -- **Cost Control**: Set appropriate `max_tokens` in agent config +### 4. **Monitoring & Observability** +- Track Cloudflare Workers performance metrics +- Monitor Swarms API response times and success rates +- Use Cloudflare Workers analytics dashboard +- Set up alerts for system failures and anomalies -This minimal implementation provides a solid foundation for production AI agents on Cloudflare Workers with automated scheduling and real-time data integration. \ No newline at end of file +This deployment architecture combines **Swarms API's advanced multi-agent intelligence** with **Cloudflare Workers' global edge infrastructure**, enabling truly intelligent, self-executing AI agents that operate continuously across 330+ cities worldwide, providing real-time intelligence and automated decision-making capabilities with ultra-low latency. \ No newline at end of file From 01c60e56c71528860a0067752d9b3443e70e9b67 Mon Sep 17 00:00:00 2001 From: harshalmore31 Date: Tue, 5 Aug 2025 03:44:33 +0530 Subject: [PATCH 6/9] cleanup ! --- docs/swarms_cloud/cloudflare_workers.md | 515 +++++------------------- 1 file changed, 97 insertions(+), 418 deletions(-) diff --git a/docs/swarms_cloud/cloudflare_workers.md b/docs/swarms_cloud/cloudflare_workers.md index a28171fc..4d339da9 100644 --- a/docs/swarms_cloud/cloudflare_workers.md +++ b/docs/swarms_cloud/cloudflare_workers.md @@ -1,15 +1,16 @@ -# Deploy Autonomous Cron Agents with Swarms API on Cloudflare Workers +# Deploy Cron Agents with Swarms API on Cloudflare Workers -Deploy intelligent, self-executing AI agents powered by Swarms API on Cloudflare's global edge network. Build production-ready autonomous agents that run on automated schedules, fetch real-time data, perform sophisticated analysis using Swarms AI, and take automated actions across 330+ cities worldwide. +Deploy intelligent, self-executing AI agents powered by Swarms API on Cloudflare's global edge network. Build production-ready cron agents that run on automated schedules, fetch real-time data, perform sophisticated analysis using Swarms AI, and take automated actions across 330+ cities worldwide. -## What Are Autonomous Cron Agents? +## What Are Cron Agents? -Autonomous cron agents combine **Swarms API intelligence** with **Cloudflare Workers edge computing** to create AI-powered systems that: -- **Execute automatically** on predefined schedules without human intervention -- **Fetch real-time data** from external sources (APIs, databases, IoT sensors) -- **Perform intelligent analysis** using specialized Swarms AI agents -- **Take automated actions** based on analysis findings (alerts, reports, decisions) -- **Scale globally** on Cloudflare's edge network with sub-100ms response times worldwide +Cron agents combine **Swarms API intelligence** with **Cloudflare Workers edge computing** to create AI-powered systems that: + +* **Execute automatically** on predefined schedules without human intervention +* **Fetch real-time data** from external sources (APIs, databases, IoT sensors) +* **Perform intelligent analysis** using specialized Swarms AI agents +* **Take automated actions** based on analysis findings (alerts, reports, decisions) +* **Scale globally** on Cloudflare's edge network with sub-100ms response times worldwide ## Architecture Overview @@ -25,35 +26,36 @@ Autonomous cron agents combine **Swarms API intelligence** with **Cloudflare Wor ``` **Key Benefits:** -- **24/7 Autonomous Operation**: Zero human intervention required -- **Global Edge Deployment**: Cloudflare's 330+ city network for ultra-low latency -- **Swarms AI Intelligence**: Live data analysis with specialized AI agents -- **Automated Decision Making**: Smart actions based on Swarms agent insights -- **Enterprise Reliability**: Production-grade error handling and monitoring -## Quick Start: Deploy Autonomous Stock Analysis Agent +* **24/7 Operation**: Zero human intervention required +* **Global Edge Deployment**: Cloudflare's 330+ city network for ultra-low latency +* **Swarms AI Intelligence**: Live data analysis with specialized AI agents +* **Automated Decision Making**: Smart actions based on Swarms agent insights +* **Enterprise Reliability**: Production-grade error handling and monitoring + +## Quick Start: Deploy Stock Analysis Cron Agent -Create your first autonomous financial intelligence agent powered by Swarms API and deployed on Cloudflare Workers edge network. +Create your first financial intelligence cron agent powered by Swarms API and deployed on Cloudflare Workers edge network. ### 1. Cloudflare Workers Project Setup ```bash # Create new Cloudflare Workers project -npm create cloudflare@latest autonomous-stock-agent -cd autonomous-stock-agent +npm create cloudflare@latest stock-cron-agent +cd stock-cron-agent # Install dependencies for Swarms API integration -npm run start +npm install ``` ### 2. Configure Cloudflare Workers Cron Schedule -Edit `wrangler.jsonc` to set up autonomous execution: +Edit `wrangler.jsonc` to set up cron execution: ```jsonc { "$schema": "node_modules/wrangler/config-schema.json", - "name": "autonomous-stock-agent", + "name": "stock-cron-agent", "main": "src/index.js", "compatibility_date": "2025-08-03", "observability": { @@ -61,7 +63,7 @@ Edit `wrangler.jsonc` to set up autonomous execution: }, "triggers": { "crons": [ - "0 */3 * * *" // Cloudflare Workers cron: autonomous analysis every 3 hours + "0 */3 * * *" // Cloudflare Workers cron: analysis every 3 hours ] }, "vars": { @@ -82,95 +84,22 @@ export default { if (url.pathname === '/') { return new Response(` - - - Autonomous Stock Intelligence Agent - - -
-
-

🤖 Autonomous Stock Intelligence Agent

-

Powered by Swarms API • Running on Cloudflare Workers

-
- Swarms AI - Cloudflare Edge - Real-time - Autonomous -
-
- -
- 🚀 Status: Swarms AI agents active on Cloudflare edge, monitoring markets 24/7 -
- -
- -
- -
-
-

Swarms AI agents analyzing live market data on Cloudflare edge...

-
- -
-
- +

Stock Cron Agent

+

Status: Active |

+
@@ -183,7 +112,7 @@ export default { if (url.pathname === '/execute') { try { - const result = await executeAutonomousAnalysis(null, env); + const result = await executeAnalysis(null, env); return new Response(JSON.stringify({ message: 'Autonomous analysis executed successfully', timestamp: new Date().toISOString(), @@ -209,13 +138,13 @@ export default { // Cloudflare Workers cron handler - triggered by scheduled events async scheduled(event, env, ctx) { console.log('🚀 Cloudflare Workers cron triggered - executing Swarms AI analysis'); - ctx.waitUntil(executeAutonomousAnalysis(event, env)); + ctx.waitUntil(executeAnalysis(event, env)); } }; // Core function combining Cloudflare Workers execution with Swarms API intelligence -async function executeAutonomousAnalysis(event, env) { - console.log('🤖 Cloudflare Workers executing Swarms AI stock intelligence analysis...'); +async function executeAnalysis(event, env) { + console.log('🤖 Cloudflare Workers executing Swarms AI analysis...'); try { // Step 1: Autonomous data collection from multiple sources @@ -547,343 +476,89 @@ async function executeAutonomousAlerts(env, intelligenceReport, marketIntelligen } ``` -## Autonomous Healthcare Intelligence Agent +## Healthcare Cron Agent Example -Deploy autonomous healthcare agents that provide 24/7 patient monitoring with intelligent analysis: +Healthcare monitoring cron agent with Swarms AI: ```javascript export default { async fetch(request, env, ctx) { - const url = new URL(request.url); - - if (url.pathname === '/') { - return new Response(` - - - - Autonomous Healthcare Intelligence - - - -
-
-

🏥 Autonomous Healthcare Intelligence

-

AI-Powered 24/7 Patient Monitoring • Autonomous Medical Analysis

-
- Autonomous - 24/7 Monitoring - AI-Powered - Real-time -
-
- -
-
-

✅ Normal Status

-

Patients: 15

-

Stable vital signs

-

Autonomous monitoring active

-
-
-

⚠️ Monitoring Required

-

Patients: 3

-

Elevated parameters

-

Enhanced surveillance

-
-
-

🚨 Critical Alert

-

Patients: 1

-

Immediate intervention

-

Emergency protocols active

-
-
- -
- -
- -
-
- - - - - `, { - headers: { 'Content-Type': 'text/html' } + if (request.url.includes('/health')) { + return new Response(JSON.stringify({ + status: 'Healthcare cron agent active', + next_check: 'Every 30 minutes' + }), { + headers: { 'Content-Type': 'application/json' } }); } - - if (url.pathname === '/health-intelligence') { - try { - const result = await executeAutonomousHealthIntelligence(null, env); - return new Response(JSON.stringify({ - message: 'Autonomous health intelligence analysis executed', - timestamp: new Date().toISOString(), - result - }), { - headers: { 'Content-Type': 'application/json' } - }); - } catch (error) { - return new Response(JSON.stringify({ - error: error.message, - system: 'autonomous-healthcare-intelligence' - }), { - status: 500, - headers: { 'Content-Type': 'application/json' } - }); - } - } - - return new Response('Autonomous Healthcare Intelligence Endpoint Not Found', { status: 404 }); + return new Response('Healthcare Cron Agent'); }, - // Autonomous healthcare monitoring - every 30 minutes + // Healthcare monitoring - every 30 minutes async scheduled(event, env, ctx) { - console.log('🏥 Autonomous healthcare intelligence system triggered'); - ctx.waitUntil(executeAutonomousHealthIntelligence(event, env)); + console.log('🏥 Healthcare cron agent triggered'); + ctx.waitUntil(executeHealthAnalysis(event, env)); } }; -async function executeAutonomousHealthIntelligence(event, env) { - console.log('🏥 Autonomous healthcare intelligence system executing...'); - +async function executeHealthAnalysis(event, env) { try { - // Autonomous patient data collection - const patientIntelligence = await collectPatientIntelligence(); + // Collect patient data (from EMR, IoT devices, etc.) + const patientData = await getPatientData(); - // Deploy autonomous Swarms healthcare AI agents - const healthIntelligenceConfig = { - name: "Autonomous Healthcare Intelligence Swarm", - description: "24/7 autonomous patient monitoring and medical analysis system", + // Configure Swarms healthcare agents + const healthConfig = { + name: "Healthcare Monitoring Swarm", agents: [ { - agent_name: "Autonomous Vital Signs Intelligence Agent", - system_prompt: \`You are an autonomous healthcare AI agent providing 24/7 patient monitoring. Analyze: - - Continuous heart rate monitoring and arrhythmia detection (Normal: 60-100 bpm) - - Autonomous blood pressure trend analysis (Normal: <140/90 mmHg) - - Real-time oxygen saturation monitoring (Normal: >95%) - - Continuous temperature surveillance (Normal: 97-99°F) - - Classify each patient autonomously as: NORMAL_MONITORING, ENHANCED_SURVEILLANCE, or CRITICAL_INTERVENTION - For critical findings, trigger autonomous emergency protocols.\`, - model_name: "gpt-4o-mini", - max_tokens: 2500, - temperature: 0.05 - }, - { - agent_name: "Autonomous Medical Risk Assessment Agent", - system_prompt: \`You are an autonomous medical AI providing continuous risk assessment. Monitor: - - Autonomous drug interaction analysis and medication safety - - Real-time disease progression and complication detection - - Continuous fall risk and mobility assessment - - Autonomous emergency intervention requirements - - Provide autonomous risk stratification and intervention priorities. - Focus on predictive analytics and early autonomous warning systems.\`, + agent_name: "Vital Signs Monitor", + system_prompt: "Monitor patient vital signs and detect anomalies. Alert on critical values.", model_name: "gpt-4o-mini", - max_tokens: 2500, - temperature: 0.05 + max_tokens: 1000 } ], swarm_type: "ConcurrentWorkflow", - task: \`Execute autonomous 24/7 healthcare intelligence analysis: - - PATIENT INTELLIGENCE DATA: - \${JSON.stringify(patientIntelligence, null, 2)} - - Generate autonomous healthcare intelligence including: - 1. Individual patient autonomous risk assessment and monitoring status - 2. Critical autonomous intervention requirements and emergency protocols - 3. Autonomous alert recommendations and escalation procedures - 4. Predictive health analytics and preventive care suggestions - 5. Next autonomous monitoring cycle parameters and priorities - - Focus on autonomous decision support for medical staff and emergency response systems.\`, + task: `Analyze patient data: ${JSON.stringify(patientData, null, 2)}`, max_loops: 1 }; + // Call Swarms API const response = await fetch('https://api.swarms.world/v1/swarm/completions', { method: 'POST', headers: { 'x-api-key': env.SWARMS_API_KEY, 'Content-Type': 'application/json' }, - body: JSON.stringify(healthIntelligenceConfig) + body: JSON.stringify(healthConfig) }); - if (!response.ok) { - throw new Error(\`Autonomous healthcare intelligence failed: \${response.status}\`); - } - const result = await response.json(); - const healthIntelligence = result.output; - // Autonomous severity assessment - const severity = assessAutonomousHealthSeverity(healthIntelligence); - - console.log(\`✅ Autonomous healthcare intelligence completed - Severity: \${severity}\`); - - // Autonomous emergency response system - if (severity === 'critical' && env.HEALTHCARE_EMERGENCY_EMAIL) { - console.log('🚨 Executing autonomous emergency response protocol...'); - await executeAutonomousEmergencyResponse(env, healthIntelligence, patientIntelligence); + // Send alerts if critical conditions detected + if (result.output.includes('CRITICAL')) { + await sendHealthAlert(env, result.output); } - return { - success: true, - analysis: healthIntelligence, - severity: severity, - patientsAnalyzed: Object.keys(patientIntelligence).length, - executionTime: new Date().toISOString(), - nextAutonomousMonitoring: 'Scheduled for next autonomous cycle', - autonomousSystem: 'Swarms Healthcare AI' - }; - + return { success: true, analysis: result.output }; } catch (error) { - console.error('❌ Autonomous healthcare intelligence failed:', error.message); - return { - success: false, - error: error.message, - severity: 'autonomous_system_error', - executionTime: new Date().toISOString() - }; + console.error('Healthcare analysis failed:', error); + return { success: false, error: error.message }; } } -// Autonomous patient intelligence collection -async function collectPatientIntelligence() { - // In production, connect to EMR systems, IoT devices, and medical databases +async function getPatientData() { + // Mock patient data - replace with real EMR/IoT integration return { - "ICU_Autonomous_001": { - name: "Sarah Johnson", - age: 68, - room: "ICU-205", - condition: "Post-cardiac surgery - autonomous monitoring", - vitals: { - heart_rate: 95, - blood_pressure_systolic: 135, - blood_pressure_diastolic: 88, - oxygen_saturation: 97, - temperature: 98.8, - respiratory_rate: 16 - }, - medications: ["Metoprolol", "Warfarin", "Furosemide"], - risk_factors: ["Diabetes", "Hypertension", "Previous MI"], - autonomous_monitoring_level: "enhanced", - last_updated: new Date().toISOString() - }, - "Ward_Autonomous_002": { - name: "Michael Chen", - age: 45, - room: "Ward-301", - condition: "Pneumonia recovery - autonomous surveillance", - vitals: { - heart_rate: 88, - blood_pressure_systolic: 128, - blood_pressure_diastolic: 82, - oxygen_saturation: 94, // Slightly low - autonomous flag - temperature: 100.1, // Mild fever - autonomous flag - respiratory_rate: 20 - }, - medications: ["Azithromycin", "Albuterol"], - risk_factors: ["Asthma", "Smoking history"], - autonomous_monitoring_level: "standard", - last_updated: new Date().toISOString() - }, - "Critical_Autonomous_003": { - name: "Elena Rodriguez", - age: 72, - room: "ICU-208", - condition: "Sepsis - autonomous critical monitoring", - vitals: { - heart_rate: 115, // Elevated - autonomous critical flag - blood_pressure_systolic: 85, // Low - autonomous critical flag - blood_pressure_diastolic: 55, // Low - autonomous critical flag - oxygen_saturation: 89, // Critical - autonomous emergency flag - temperature: 103.2, // High fever - autonomous critical flag - respiratory_rate: 28 // Elevated - autonomous critical flag - }, - medications: ["Vancomycin", "Norepinephrine", "Hydrocortisone"], - risk_factors: ["Sepsis", "Multi-organ dysfunction", "Advanced age"], - autonomous_monitoring_level: "critical", - last_updated: new Date().toISOString() + patient_001: { + heart_rate: 115, // Elevated + oxygen_saturation: 89 // Low - critical } }; } -function assessAutonomousHealthSeverity(intelligenceReport) { - const reportText = typeof intelligenceReport === 'string' ? intelligenceReport : JSON.stringify(intelligenceReport); - - if (reportText.includes('CRITICAL_INTERVENTION') || - reportText.includes('EMERGENCY') || - reportText.includes('IMMEDIATE_ACTION') || - reportText.includes('SEPSIS') || - reportText.includes('CARDIAC_ARREST') || - reportText.includes('RESPIRATORY_FAILURE')) { - return 'critical'; - } else if (reportText.includes('ENHANCED_SURVEILLANCE') || - reportText.includes('ELEVATED') || - reportText.includes('CONCERNING') || - reportText.includes('ABNORMAL') || - reportText.includes('MONITORING_REQUIRED')) { - return 'warning'; - } - return 'normal'; -} - -async function executeAutonomousEmergencyResponse(env, intelligenceReport, patientIntelligence) { - console.log('🚨 Autonomous emergency response protocol executing...'); - - // Autonomous emergency response would include: - // - Immediate medical team notifications - // - Automated equipment preparation alerts - // - Emergency response coordination - // - Real-time escalation to on-call physicians - // - Integration with hospital emergency systems +async function sendHealthAlert(env, analysis) { + // Send emergency alerts via email/SMS + console.log('🚨 Critical health alert sent'); } ``` @@ -937,26 +612,30 @@ wrangler triggers cron "0 */3 * * *" ## Production Best Practices ### 1. **Cloudflare Workers + Swarms API Integration** -- Implement comprehensive error handling for both platforms -- Use Cloudflare Workers KV for caching Swarms API responses -- Leverage Cloudflare Workers analytics for monitoring + +* Implement comprehensive error handling for both platforms +* Use Cloudflare Workers KV for caching Swarms API responses +* Leverage Cloudflare Workers analytics for monitoring ### 2. **Cost Optimization** -- Monitor Swarms API usage and costs -- Use Cloudflare Workers free tier (100K requests/day) -- Implement intelligent batching for Swarms API efficiency -- Use cost-effective Swarms models (gpt-4o-mini recommended) + +* Monitor Swarms API usage and costs +* Use Cloudflare Workers free tier (100K requests/day) +* Implement intelligent batching for Swarms API efficiency +* Use cost-effective Swarms models (gpt-4o-mini recommended) ### 3. **Security & Compliance** -- Secure Swarms API keys in Cloudflare Workers environment variables -- Use Cloudflare Workers secrets for sensitive data -- Audit AI decisions and maintain compliance logs -- HIPAA compliance for healthcare applications + +* Secure Swarms API keys in Cloudflare Workers environment variables +* Use Cloudflare Workers secrets for sensitive data +* Audit AI decisions and maintain compliance logs +* HIPAA compliance for healthcare applications ### 4. **Monitoring & Observability** -- Track Cloudflare Workers performance metrics -- Monitor Swarms API response times and success rates -- Use Cloudflare Workers analytics dashboard -- Set up alerts for system failures and anomalies + +* Track Cloudflare Workers performance metrics +* Monitor Swarms API response times and success rates +* Use Cloudflare Workers analytics dashboard +* Set up alerts for system failures and anomalies This deployment architecture combines **Swarms API's advanced multi-agent intelligence** with **Cloudflare Workers' global edge infrastructure**, enabling truly intelligent, self-executing AI agents that operate continuously across 330+ cities worldwide, providing real-time intelligence and automated decision-making capabilities with ultra-low latency. \ No newline at end of file From 3473080babb746e9dc7334bbe82b23254b242435 Mon Sep 17 00:00:00 2001 From: harshalmore31 Date: Tue, 5 Aug 2025 03:54:17 +0530 Subject: [PATCH 7/9] updates ! --- docs/swarms_cloud/cloudflare_workers.md | 131 +++++------------------- 1 file changed, 27 insertions(+), 104 deletions(-) diff --git a/docs/swarms_cloud/cloudflare_workers.md b/docs/swarms_cloud/cloudflare_workers.md index 4d339da9..fde8c094 100644 --- a/docs/swarms_cloud/cloudflare_workers.md +++ b/docs/swarms_cloud/cloudflare_workers.md @@ -96,10 +96,10 @@ export default { const res = await fetch('/execute'); const data = await res.json(); document.getElementById('result').innerHTML = data.result?.success - ? \`✅ Success: \${data.result.analysis}\` - : \`❌ Error: \${data.error}\`; + ? '✅ Success: ' + data.result.analysis + : '❌ Error: ' + data.error; } catch (e) { - document.getElementById('result').innerHTML = \`❌ Failed: \${e.message}\`; + document.getElementById('result').innerHTML = '❌ Failed: ' + e.message; } } @@ -156,7 +156,7 @@ async function executeAnalysis(event, env) { throw new Error('Autonomous data collection failed - no valid market intelligence gathered'); } - console.log(\`✅ Autonomous data collection successful: \${validData.length} sources\`); + console.log('✅ Autonomous data collection successful: ' + validData.length + ' sources'); // Step 2: Deploy Swarms AI agents for autonomous analysis console.log('🧠 Deploying Swarms AI agents for autonomous intelligence generation...'); @@ -222,14 +222,14 @@ async function executeAnalysis(event, env) { if (!response.ok) { const errorText = await response.text(); - throw new Error(\`Swarms API autonomous execution failed: \${response.status} - \${errorText}\`); + throw new Error('Swarms API autonomous execution failed: ' + response.status + ' - ' + errorText); } const analysisResult = await response.json(); const intelligenceReport = analysisResult.output; console.log('✅ Autonomous Swarms AI analysis completed successfully'); - console.log(\`💰 Autonomous execution cost: \${analysisResult.usage?.billing_info?.total_cost || 'N/A'}\`); + console.log('💰 Autonomous execution cost: ' + (analysisResult.usage?.billing_info?.total_cost || 'N/A')); // Step 3: Execute autonomous actions based on intelligence if (env.AUTONOMOUS_ALERTS_EMAIL) { @@ -272,7 +272,7 @@ async function collectMarketIntelligence() { // Autonomous data collection from Yahoo Finance API const response = await fetch( - \`https://query1.finance.yahoo.com/v8/finance/chart/\${symbol}\`, + 'https://query1.finance.yahoo.com/v8/finance/chart/' + symbol, { signal: controller.signal, headers: { @@ -283,7 +283,7 @@ async function collectMarketIntelligence() { clearTimeout(timeout); if (!response.ok) { - throw new Error(\`Autonomous data collection failed: HTTP \${response.status}\`); + throw new Error('Autonomous data collection failed: HTTP ' + response.status); } const data = await response.json(); @@ -299,7 +299,7 @@ async function collectMarketIntelligence() { const dayChange = currentPrice - previousClose; const changePercent = ((dayChange / previousClose) * 100).toFixed(2); - console.log(\`📈 \${symbol}: $\${currentPrice} (\${changePercent}%) - Autonomous collection successful\`); + console.log('📈 ' + symbol + ': $' + currentPrice + ' (' + changePercent + '%) - Autonomous collection successful'); return [symbol, { price: currentPrice, @@ -319,9 +319,9 @@ async function collectMarketIntelligence() { }]; } catch (error) { - console.error(\`❌ Autonomous collection failed for \${symbol}:\`, error.message); + console.error('❌ Autonomous collection failed for ' + symbol + ':', error.message); return [symbol, { - error: \`Autonomous collection failed: \${error.message}\`, + error: 'Autonomous collection failed: ' + error.message, autonomous_collection_time: new Date().toISOString(), data_quality: 'failed' }]; @@ -337,7 +337,7 @@ async function collectMarketIntelligence() { }); const successfulCollections = Object.keys(marketIntelligence).filter(k => !marketIntelligence[k]?.error).length; - console.log(\`📊 Autonomous intelligence collection completed: \${successfulCollections}/\${targetSymbols.length} successful\`); + console.log('📊 Autonomous intelligence collection completed: ' + successfulCollections + '/' + targetSymbols.length + ' successful'); return marketIntelligence; } @@ -353,113 +353,36 @@ async function executeAutonomousAlerts(env, intelligenceReport, marketIntelligen // Autonomous detection of significant market movements const significantMovements = Object.entries(marketIntelligence) .filter(([symbol, data]) => data.change_percent && Math.abs(parseFloat(data.change_percent)) > 3) - .map(([symbol, data]) => \`\${symbol}: \${data.change_percent}%\`) + .map(([symbol, data]) => symbol + ': ' + data.change_percent + '%') .join(', '); - const alertSubject = \`🤖 Autonomous Market Intelligence Alert - \${new Date().toLocaleDateString()}\`; + const alertSubject = '🤖 Autonomous Market Intelligence Alert - ' + new Date().toLocaleDateString(); - const alertBody = \` - + const alertBody = ` - - - - -
-
-

🤖 Autonomous Market Intelligence

-

AI-Powered Autonomous Financial Analysis • Swarms API

-
- Autonomous - Real-time - AI-Powered - Global Edge -
-

Generated: \${new Date().toLocaleString()}

-
+ +

🤖 Market Intelligence Alert

+

Date: ${new Date().toLocaleString()}

+

Movements: ${significantMovements || 'Normal volatility'}

-
-
-

🚀 Autonomous Analysis Execution Complete

-

Significant Market Movements Detected: \${significantMovements || 'Market within normal volatility parameters'}

-

Next Autonomous Cycle: Scheduled automatically

-
- -
-

🧠 Autonomous AI Intelligence Report

-

Generated by autonomous Swarms AI agents with real-time market intelligence:

-
\${intelligenceReport}
-
- -
-

📊 Real-Time Market Intelligence

- - - - - - - - - - - - - \${Object.entries(marketIntelligence) - .filter(([symbol, data]) => !data.error) - .map(([symbol, data]) => \` - - - - - - - - - \`).join('')} - -
SymbolPriceChangeVolumeMarket StateData Quality
\${symbol}$\${data.price?.toFixed(2) || 'N/A'} - \${parseFloat(data.change_percent) >= 0 ? '+' : ''}\${data.change_percent}% - \${data.volume?.toLocaleString() || 'N/A'}\${data.market_state || 'N/A'}\${data.data_quality || 'N/A'}
-
-
+

Analysis Report:

+
${intelligenceReport}
- -
- +

Powered by Swarms API

+ - \`; + `; const formData = new FormData(); - formData.append('from', \`Autonomous Market Intelligence \`); + formData.append('from', 'Autonomous Market Intelligence '); formData.append('to', env.AUTONOMOUS_ALERTS_EMAIL); formData.append('subject', alertSubject); formData.append('html', alertBody); - const response = await fetch(\`https://api.mailgun.net/v3/\${env.MAILGUN_DOMAIN}/messages\`, { + const response = await fetch('https://api.mailgun.net/v3/' + env.MAILGUN_DOMAIN + '/messages', { method: 'POST', headers: { - 'Authorization': \`Basic \${btoa(\`api:\${env.MAILGUN_API_KEY}\`)}\` + 'Authorization': 'Basic ' + btoa('api:' + env.MAILGUN_API_KEY) }, body: formData }); From 6544500f8ff529e3e144bd244ac3a59fdea9b842 Mon Sep 17 00:00:00 2001 From: harshalmore31 Date: Tue, 5 Aug 2025 04:01:24 +0530 Subject: [PATCH 8/9] fixed mkdocs formatting --- docs/swarms_cloud/cloudflare_workers.md | 32 +++---------------------- 1 file changed, 3 insertions(+), 29 deletions(-) diff --git a/docs/swarms_cloud/cloudflare_workers.md b/docs/swarms_cloud/cloudflare_workers.md index fde8c094..d2df71b7 100644 --- a/docs/swarms_cloud/cloudflare_workers.md +++ b/docs/swarms_cloud/cloudflare_workers.md @@ -166,47 +166,21 @@ async function executeAnalysis(event, env) { agents: [ { agent_name: "Autonomous Technical Intelligence Agent", - system_prompt: \`You are an autonomous technical analysis AI agent operating 24/7. Provide: - - Real-time trend identification and momentum analysis - - Dynamic support/resistance level calculations - - Technical indicator signals (RSI, MACD, moving averages) - - Autonomous price targets and risk assessments - - Self-executing trading signal recommendations - - Format your analysis as a professional autonomous intelligence briefing for automated systems.\`, + system_prompt: "You are an autonomous technical analysis AI agent operating 24/7. Provide: Real-time trend identification and momentum analysis, dynamic support/resistance level calculations, technical indicator signals (RSI, MACD, moving averages), autonomous price targets and risk assessments, and self-executing trading signal recommendations. Format your analysis as a professional autonomous intelligence briefing for automated systems.", model_name: "gpt-4o-mini", max_tokens: 2500, temperature: 0.2 }, { agent_name: "Autonomous Market Sentiment Agent", - system_prompt: \`You are an autonomous market sentiment analysis AI agent. Continuously evaluate: - - Real-time market psychology and investor behavior patterns - - Volume analysis and institutional activity detection - - Risk-on vs risk-off sentiment shifts - - Autonomous sector rotation and leadership identification - - Self-executing market timing recommendations - - Provide actionable intelligence for autonomous decision-making systems.\`, + system_prompt: "You are an autonomous market sentiment analysis AI agent. Continuously evaluate: Real-time market psychology and investor behavior patterns, volume analysis and institutional activity detection, risk-on vs risk-off sentiment shifts, autonomous sector rotation and leadership identification, and self-executing market timing recommendations. Provide actionable intelligence for autonomous decision-making systems.", model_name: "gpt-4o-mini", max_tokens: 2500, temperature: 0.3 } ], swarm_type: "ConcurrentWorkflow", - task: \`Execute autonomous analysis of real-time market intelligence: - - LIVE MARKET INTELLIGENCE: - \${JSON.stringify(marketIntelligence, null, 2)} - - Generate comprehensive autonomous intelligence report including: - 1. Technical analysis with specific autonomous entry/exit recommendations - 2. Market sentiment assessment with timing signals for automated systems - 3. Risk management protocols for autonomous execution - 4. Self-executing action recommendations - 5. Key monitoring parameters for next autonomous cycle - - Focus on actionable intelligence for autonomous trading systems and automated decision making.\`, + task: `Execute autonomous analysis of real-time market intelligence: ${JSON.stringify(marketIntelligence, null, 2)} Generate comprehensive autonomous intelligence report including: 1. Technical analysis with specific autonomous entry/exit recommendations 2. Market sentiment assessment with timing signals for automated systems 3. Risk management protocols for autonomous execution 4. Self-executing action recommendations 5. Key monitoring parameters for next autonomous cycle Focus on actionable intelligence for autonomous trading systems and automated decision making.`, max_loops: 1 }; From 1dc56536368e02e5845565736e8c8aa45ed49e7c Mon Sep 17 00:00:00 2001 From: harshalmore31 Date: Tue, 5 Aug 2025 07:51:55 +0530 Subject: [PATCH 9/9] fixed ! --- docs/swarms_cloud/cloudflare_workers.md | 133 ------------------------ 1 file changed, 133 deletions(-) diff --git a/docs/swarms_cloud/cloudflare_workers.md b/docs/swarms_cloud/cloudflare_workers.md index d2df71b7..cc265a77 100644 --- a/docs/swarms_cloud/cloudflare_workers.md +++ b/docs/swarms_cloud/cloudflare_workers.md @@ -373,139 +373,6 @@ async function executeAutonomousAlerts(env, intelligenceReport, marketIntelligen } ``` -## Healthcare Cron Agent Example - -Healthcare monitoring cron agent with Swarms AI: - -```javascript -export default { - async fetch(request, env, ctx) { - if (request.url.includes('/health')) { - return new Response(JSON.stringify({ - status: 'Healthcare cron agent active', - next_check: 'Every 30 minutes' - }), { - headers: { 'Content-Type': 'application/json' } - }); - } - return new Response('Healthcare Cron Agent'); - }, - - // Healthcare monitoring - every 30 minutes - async scheduled(event, env, ctx) { - console.log('🏥 Healthcare cron agent triggered'); - ctx.waitUntil(executeHealthAnalysis(event, env)); - } -}; - -async function executeHealthAnalysis(event, env) { - try { - // Collect patient data (from EMR, IoT devices, etc.) - const patientData = await getPatientData(); - - // Configure Swarms healthcare agents - const healthConfig = { - name: "Healthcare Monitoring Swarm", - agents: [ - { - agent_name: "Vital Signs Monitor", - system_prompt: "Monitor patient vital signs and detect anomalies. Alert on critical values.", - model_name: "gpt-4o-mini", - max_tokens: 1000 - } - ], - swarm_type: "ConcurrentWorkflow", - task: `Analyze patient data: ${JSON.stringify(patientData, null, 2)}`, - max_loops: 1 - }; - - // Call Swarms API - const response = await fetch('https://api.swarms.world/v1/swarm/completions', { - method: 'POST', - headers: { - 'x-api-key': env.SWARMS_API_KEY, - 'Content-Type': 'application/json' - }, - body: JSON.stringify(healthConfig) - }); - - const result = await response.json(); - - // Send alerts if critical conditions detected - if (result.output.includes('CRITICAL')) { - await sendHealthAlert(env, result.output); - } - - return { success: true, analysis: result.output }; - } catch (error) { - console.error('Healthcare analysis failed:', error); - return { success: false, error: error.message }; - } -} - -async function getPatientData() { - // Mock patient data - replace with real EMR/IoT integration - return { - patient_001: { - heart_rate: 115, // Elevated - oxygen_saturation: 89 // Low - critical - } - }; -} - -async function sendHealthAlert(env, analysis) { - // Send emergency alerts via email/SMS - console.log('🚨 Critical health alert sent'); -} -``` - -## Deployment & Configuration - -### Environment Variables - -Configure your Cloudflare Workers deployment with Swarms API: - -```jsonc -{ - "vars": { - "SWARMS_API_KEY": "your-swarms-api-key", - "AUTONOMOUS_ALERTS_EMAIL": "intelligence@yourcompany.com", - "HEALTHCARE_EMERGENCY_EMAIL": "emergency@hospital.com", - "MAILGUN_API_KEY": "your-mailgun-key", - "MAILGUN_DOMAIN": "intelligence.yourcompany.com" - } -} -``` - -### Cloudflare Workers Cron Scheduling Patterns - -```jsonc -{ - "triggers": { - "crons": [ - "0 */3 * * *", // Financial Swarms agents every 3 hours - "*/30 * * * *", // Healthcare Swarms monitoring every 30 minutes - "0 9,15,21 * * *", // Daily Swarms intelligence briefings - "*/5 * * * *" // Critical Swarms systems every 5 minutes - ] - } -} -``` - -### Cloudflare Workers Deployment Commands - -```bash -# Deploy Swarms AI agents to Cloudflare Workers -wrangler deploy - -# Monitor Cloudflare Workers execution logs -wrangler tail - -# Test Cloudflare Workers cron triggers manually -wrangler triggers cron "0 */3 * * *" - -``` - ## Production Best Practices ### 1. **Cloudflare Workers + Swarms API Integration**