.do
Service TypesAi

AI Analysis Services

Build AI-powered analysis services that extract insights from data, perform sentiment analysis, detect trends, identify anomalies, and provide predictive analytics using the Services-as-Software framework.

AI analysis services transform raw data into actionable insights by leveraging machine learning models to detect patterns, analyze sentiment, identify trends, predict outcomes, and extract meaningful information from structured and unstructured data.

Overview

Analysis services process data to uncover hidden patterns, relationships, and insights that would be difficult or impossible for humans to identify manually. They can analyze everything from customer feedback and market trends to financial data and operational metrics.

Key Benefits

  • Speed: Analyze massive datasets in seconds instead of weeks
  • Accuracy: Eliminate human bias and error in analysis
  • Scale: Process unlimited amounts of data consistently
  • Depth: Discover patterns and correlations humans might miss
  • Real-time: Provide instant insights as new data arrives
  • Cost-Effective: Dramatically lower cost per analysis

Service Architecture

Analysis services typically follow this pattern:

  1. Data Ingestion: Accept and validate input data
  2. Preprocessing: Clean, normalize, and structure data
  3. Analysis Execution: Run AI models to extract insights
  4. Pattern Recognition: Identify trends, anomalies, and correlations
  5. Insight Generation: Create actionable recommendations
  6. Visualization: Present results in understandable formats
  7. Delivery: Package and deliver insights with confidence scores

Market Research Analysis Service

Comprehensive market analysis with competitor intelligence and trend detection:

import $, { ai, db, on, send } from 'sdk.do'

const marketResearchService = await $.Service.create({
  id: 'market-research-analyzer',
  name: 'AI Market Research Analyzer',
  description: 'Comprehensive market analysis with competitor intelligence and growth projections',
  type: $.ServiceType.Analysis,
  subtype: 'market-research',

  capabilities: [
    'market-sizing',
    'competitor-analysis',
    'trend-identification',
    'opportunity-assessment',
    'risk-analysis',
    'growth-projections',
    'customer-segmentation',
  ],

  pricing: {
    model: 'per-analysis',
    baseRate: 100.0,
    variables: {
      dataSize: { perGB: 10.0 },
      depth: {
        basic: 1.0,
        detailed: 1.5,
        comprehensive: 2.0,
      },
      competitors: { perCompetitor: 25.0 },
      markets: { perMarket: 50.0 },
    },
    minimumCharge: 100.0,
  },

  inputSchema: {
    industry: { type: 'string', required: true },
    targetMarkets: {
      type: 'array',
      items: { type: 'string' },
      required: true,
    },
    competitors: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          name: { type: 'string' },
          website: { type: 'string' },
          focus: { type: 'string' },
        },
      },
    },
    depth: {
      type: 'string',
      enum: ['basic', 'detailed', 'comprehensive'],
      default: 'detailed',
    },
    timeframe: { type: 'string', default: '12-months' },
    includeProjections: { type: 'boolean', default: true },
  },

  outputSchema: {
    marketSize: {
      type: 'object',
      properties: {
        current: { type: 'number' },
        projected: { type: 'number' },
        cagr: { type: 'number' },
        currency: { type: 'string' },
      },
    },
    competitors: { type: 'array' },
    trends: { type: 'array' },
    opportunities: { type: 'array' },
    risks: { type: 'array' },
    recommendations: { type: 'array' },
    confidence: { type: 'number' },
  },
})

on($.ServiceRequest.created, async (request) => {
  if (request.serviceId !== marketResearchService.id) return

  try {
    await send($.ServiceRequest.update, {
      requestId: request.id,
      status: 'processing',
      progress: 0.1,
    })

    // 1. Collect market data from multiple sources
    const marketData = await collectMarketData({
      industry: request.inputs.industry,
      markets: request.inputs.targetMarkets,
      timeframe: request.inputs.timeframe,
    })

    await send($.ServiceRequest.update, {
      requestId: request.id,
      progress: 0.2,
    })

    // 2. Analyze market size and growth
    const marketSize = await ai.generate({
      model: 'gpt-5',
      prompt: `Analyze the market size and growth for ${request.inputs.industry} in these markets: ${request.inputs.targetMarkets.join(', ')}.

        Available data: ${JSON.stringify(marketData)}

        Provide:
        1. Current total addressable market (TAM)
        2. Serviceable addressable market (SAM)
        3. Serviceable obtainable market (SOM)
        4. Historical growth rates (3-5 years)
        5. Projected growth (CAGR) for next ${request.inputs.timeframe}
        6. Key growth drivers
        7. Market maturity stage

        Include confidence levels for all estimates.`,
      schema: {
        tam: { type: 'number' },
        sam: { type: 'number' },
        som: { type: 'number' },
        historicalCAGR: { type: 'number' },
        projectedCAGR: { type: 'number' },
        growthDrivers: { type: 'array', items: { type: 'string' } },
        maturityStage: { type: 'string' },
        confidence: { type: 'number' },
      },
    })

    await send($.ServiceRequest.update, {
      requestId: request.id,
      progress: 0.4,
    })

    // 3. Competitor analysis
    const competitorAnalysis = await Promise.all(
      request.inputs.competitors.map(async (competitor) => {
        // Scrape competitor data
        const competitorData = await collectCompetitorData(competitor)

        // Analyze competitor position
        const analysis = await ai.generate({
          model: 'gpt-5',
          prompt: `Analyze this competitor in the ${request.inputs.industry} market:

            Competitor: ${competitor.name}
            Website: ${competitor.website}
            Focus: ${competitor.focus}
            Data: ${JSON.stringify(competitorData)}

            Provide:
            1. Market positioning
            2. Strengths and weaknesses
            3. Product/service offerings
            4. Pricing strategy
            5. Target customer segments
            6. Marketing strategy
            7. Technology stack
            8. Estimated market share
            9. Growth trajectory
            10. Competitive advantages

            Be specific and data-driven.`,
          schema: {
            name: { type: 'string' },
            positioning: { type: 'string' },
            strengths: { type: 'array', items: { type: 'string' } },
            weaknesses: { type: 'array', items: { type: 'string' } },
            offerings: { type: 'array' },
            pricingStrategy: { type: 'string' },
            targetSegments: { type: 'array' },
            marketShare: { type: 'number' },
            competitiveAdvantages: { type: 'array' },
          },
        })

        return analysis.data
      })
    )

    await send($.ServiceRequest.update, {
      requestId: request.id,
      progress: 0.6,
    })

    // 4. Trend identification
    const trends = await ai.generate({
      model: 'gpt-5',
      prompt: `Identify key trends in the ${request.inputs.industry} market:

        Market data: ${JSON.stringify(marketData)}
        Competitor insights: ${JSON.stringify(competitorAnalysis)}

        Identify:
        1. Technology trends
        2. Customer behavior trends
        3. Regulatory trends
        4. Economic trends
        5. Competitive landscape trends

        For each trend:
        - Description
        - Impact level (high/medium/low)
        - Timeframe (immediate/near-term/long-term)
        - Opportunities it creates
        - Threats it poses

        Prioritize by business impact.`,
      schema: {
        trends: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              category: { type: 'string' },
              name: { type: 'string' },
              description: { type: 'string' },
              impact: { type: 'string' },
              timeframe: { type: 'string' },
              opportunities: { type: 'array' },
              threats: { type: 'array' },
              confidence: { type: 'number' },
            },
          },
        },
      },
    })

    await send($.ServiceRequest.update, {
      requestId: request.id,
      progress: 0.7,
    })

    // 5. Opportunity assessment
    const opportunities = await ai.generate({
      model: 'gpt-5',
      prompt: `Identify market opportunities based on this analysis:

        Market size: ${JSON.stringify(marketSize.data)}
        Competitors: ${JSON.stringify(competitorAnalysis)}
        Trends: ${JSON.stringify(trends.data)}

        Find:
        1. Market gaps (unmet needs)
        2. Underserved segments
        3. Emerging opportunities
        4. Differentiation opportunities
        5. Partnership opportunities

        For each opportunity:
        - Description
        - Market size estimate
        - Competition level
        - Entry barriers
        - Success factors
        - Estimated timeframe to capitalize`,
      schema: {
        opportunities: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              type: { type: 'string' },
              description: { type: 'string' },
              marketSize: { type: 'number' },
              competition: { type: 'string' },
              barriers: { type: 'array' },
              successFactors: { type: 'array' },
              timeframe: { type: 'string' },
              potential: { type: 'string' },
            },
          },
        },
      },
    })

    await send($.ServiceRequest.update, {
      requestId: request.id,
      progress: 0.8,
    })

    // 6. Risk analysis
    const risks = await ai.generate({
      model: 'gpt-5',
      prompt: `Assess market risks:

        Market: ${request.inputs.industry}
        Analysis: ${JSON.stringify({ marketSize: marketSize.data, trends: trends.data })}

        Identify:
        1. Market risks
        2. Competitive risks
        3. Technology risks
        4. Regulatory risks
        5. Economic risks

        For each risk:
        - Description
        - Probability (high/medium/low)
        - Impact (high/medium/low)
        - Mitigation strategies`,
      schema: {
        risks: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              category: { type: 'string' },
              description: { type: 'string' },
              probability: { type: 'string' },
              impact: { type: 'string' },
              mitigation: { type: 'array' },
            },
          },
        },
      },
    })

    await send($.ServiceRequest.update, {
      requestId: request.id,
      progress: 0.9,
    })

    // 7. Generate strategic recommendations
    const recommendations = await ai.generate({
      model: 'gpt-5',
      prompt: `Provide strategic recommendations based on this market research:

        Market Size: ${JSON.stringify(marketSize.data)}
        Competitors: ${JSON.stringify(competitorAnalysis)}
        Trends: ${JSON.stringify(trends.data)}
        Opportunities: ${JSON.stringify(opportunities.data)}
        Risks: ${JSON.stringify(risks.data)}

        Provide 5-7 actionable strategic recommendations prioritized by impact.
        Include:
        - Recommendation
        - Rationale
        - Expected impact
        - Implementation complexity
        - Timeline`,
      schema: {
        recommendations: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              title: { type: 'string' },
              description: { type: 'string' },
              rationale: { type: 'string' },
              impact: { type: 'string' },
              complexity: { type: 'string' },
              timeline: { type: 'string' },
              priority: { type: 'number' },
            },
          },
        },
      },
    })

    // 8. Create visualizations
    const visualizations = await generateVisualizations({
      marketSize: marketSize.data,
      competitors: competitorAnalysis,
      trends: trends.data,
      opportunities: opportunities.data,
    })

    // 9. Deliver comprehensive report
    await send($.ServiceResult.deliver, {
      requestId: request.id,
      outputs: {
        executiveSummary: generateExecutiveSummary({
          marketSize: marketSize.data,
          competitors: competitorAnalysis,
          opportunities: opportunities.data,
          recommendations: recommendations.data,
        }),
        marketSize: marketSize.data,
        competitors: competitorAnalysis,
        trends: trends.data.trends,
        opportunities: opportunities.data.opportunities,
        risks: risks.data.risks,
        recommendations: recommendations.data.recommendations,
        visualizations,
        metadata: {
          industry: request.inputs.industry,
          markets: request.inputs.targetMarkets,
          analysisDate: new Date().toISOString(),
          depth: request.inputs.depth,
          dataSourceCount: marketData.sources?.length || 0,
        },
      },
      format: 'pdf',
    })

    // Calculate cost
    const baseCharge = marketResearchService.pricing.baseRate
    const depthMultiplier = marketResearchService.pricing.variables.depth[request.inputs.depth]
    const competitorCharge = request.inputs.competitors.length * marketResearchService.pricing.variables.competitors.perCompetitor
    const marketCharge = request.inputs.targetMarkets.length * marketResearchService.pricing.variables.markets.perMarket

    const totalCost = Math.max(baseCharge * depthMultiplier + competitorCharge + marketCharge, marketResearchService.pricing.minimumCharge)

    await send($.Payment.charge, {
      customerId: request.customerId,
      amount: totalCost,
      description: `Market Research: ${request.inputs.industry}`,
      metadata: {
        competitorCount: request.inputs.competitors.length,
        marketCount: request.inputs.targetMarkets.length,
        depth: request.inputs.depth,
      },
    })
  } catch (error) {
    await send($.ServiceRequest.fail, {
      requestId: request.id,
      error: {
        code: 'ANALYSIS_FAILED',
        message: error.message,
      },
    })
  }
})

async function collectMarketData(params: any) {
  // Collect data from various sources
  return {
    industryReports: await fetchIndustryReports(params.industry),
    financialData: await fetchMarketFinancials(params.markets),
    newsArticles: await fetchRelevantNews(params.industry, params.timeframe),
    statistics: await fetchMarketStatistics(params.markets),
    sources: ['IBISWorld', 'Statista', 'Bloomberg', 'Company filings'],
  }
}

async function collectCompetitorData(competitor: any) {
  return {
    website: await scrapeWebsite(competitor.website),
    products: await extractProducts(competitor.website),
    pricing: await extractPricing(competitor.website),
    team: await getTeamInfo(competitor.name),
    funding: await getFundingInfo(competitor.name),
    reviews: await getCustomerReviews(competitor.name),
  }
}

function generateExecutiveSummary(data: any): string {
  return `
# Executive Summary

## Market Opportunity
The ${data.marketSize.tam / 1000000}M market is projected to grow at ${data.marketSize.projectedCAGR}% CAGR.

## Competitive Landscape
${data.competitors.length} key competitors analyzed, with market fragmentation creating opportunities for new entrants.

## Key Opportunities
${data.opportunities.opportunities
  .slice(0, 3)
  .map((o: any) => `- ${o.description}`)
  .join('\n')}

## Strategic Recommendations
${data.recommendations.recommendations
  .slice(0, 5)
  .map((r: any) => `${r.priority}. ${r.title}`)
  .join('\n')}
  `.trim()
}

async function generateVisualizations(data: any) {
  return {
    marketSizeChart: await createMarketSizeChart(data.marketSize),
    competitorMatrix: await createCompetitorMatrix(data.competitors),
    trendGraph: await createTrendGraph(data.trends),
    opportunityMap: await createOpportunityMap(data.opportunities),
  }
}

Sentiment Analysis Service

Analyze customer feedback, reviews, and social media sentiment:

import $, { ai, db, on, send } from 'sdk.do'

const sentimentAnalysisService = await $.Service.create({
  id: 'sentiment-analyzer',
  name: 'AI Sentiment Analyzer',
  description: 'Analyze sentiment in customer feedback, reviews, and social media',
  type: $.ServiceType.Analysis,
  subtype: 'sentiment-analysis',

  pricing: {
    model: 'per-analysis',
    tiers: [
      { documents: { min: 1, max: 100 }, rate: 0.1 },
      { documents: { min: 101, max: 1000 }, rate: 0.08 },
      { documents: { min: 1001, max: Infinity }, rate: 0.05 },
    ],
    minimumCharge: 10.0,
    realTime: {
      enabled: true,
      multiplier: 1.5,
    },
  },
})

on($.ServiceRequest.created, async (request) => {
  if (request.serviceId !== sentimentAnalysisService.id) return

  const { documents, includeEmotions, includEntities, includeThemes } = request.inputs
  const results = []

  for (const doc of documents) {
    // 1. Overall sentiment analysis
    const sentiment = await ai.generate({
      model: 'gpt-5',
      prompt: `Analyze the sentiment of this text:

        "${doc.text}"

        Provide:
        1. Overall sentiment (positive/negative/neutral)
        2. Sentiment score (-1 to 1)
        3. Confidence level (0 to 1)
        4. Key phrases that influenced the sentiment`,
      schema: {
        sentiment: { type: 'string', enum: ['positive', 'negative', 'neutral', 'mixed'] },
        score: { type: 'number' },
        confidence: { type: 'number' },
        keyPhrases: { type: 'array', items: { type: 'string' } },
      },
    })

    // 2. Emotional analysis (if requested)
    let emotions = null
    if (includeEmotions) {
      emotions = await ai.generate({
        model: 'gpt-5',
        prompt: `Identify emotions expressed in this text:

          "${doc.text}"

          For each emotion present (joy, sadness, anger, fear, surprise, disgust):
          - Intensity (0 to 1)
          - Supporting phrases`,
        schema: {
          emotions: {
            type: 'object',
            properties: {
              joy: { type: 'number' },
              sadness: { type: 'number' },
              anger: { type: 'number' },
              fear: { type: 'number' },
              surprise: { type: 'number' },
              disgust: { type: 'number' },
            },
          },
          primary: { type: 'string' },
          intensity: { type: 'number' },
        },
      })
    }

    // 3. Entity extraction (if requested)
    let entities = null
    if (includEntities) {
      entities = await ai.generate({
        model: 'gpt-5',
        prompt: `Extract entities from this text:

          "${doc.text}"

          Identify:
          - Products mentioned
          - Features mentioned
          - People mentioned
          - Companies mentioned
          - Locations mentioned

          Include sentiment towards each entity.`,
        schema: {
          products: { type: 'array' },
          features: { type: 'array' },
          people: { type: 'array' },
          companies: { type: 'array' },
          locations: { type: 'array' },
        },
      })
    }

    // 4. Theme extraction (if requested)
    let themes = null
    if (includeThemes) {
      themes = await ai.generate({
        model: 'gpt-5',
        prompt: `Extract main themes from this text:

          "${doc.text}"

          Identify 3-5 main themes with:
          - Theme name
          - Description
          - Sentiment towards theme
          - Relevance score`,
        schema: {
          themes: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                name: { type: 'string' },
                description: { type: 'string' },
                sentiment: { type: 'string' },
                relevance: { type: 'number' },
              },
            },
          },
        },
      })
    }

    results.push({
      documentId: doc.id,
      sentiment: sentiment.data,
      emotions: emotions?.data || null,
      entities: entities?.data || null,
      themes: themes?.data || null,
      analyzedAt: new Date().toISOString(),
    })
  }

  // Aggregate sentiment across all documents
  const aggregate = {
    totalDocuments: results.length,
    overallSentiment: calculateOverallSentiment(results),
    sentimentDistribution: {
      positive: results.filter((r) => r.sentiment.sentiment === 'positive').length,
      negative: results.filter((r) => r.sentiment.sentiment === 'negative').length,
      neutral: results.filter((r) => r.sentiment.sentiment === 'neutral').length,
      mixed: results.filter((r) => r.sentiment.sentiment === 'mixed').length,
    },
    averageScore: results.reduce((sum, r) => sum + r.sentiment.score, 0) / results.length,
    topPositiveThemes: extractTopThemes(results, 'positive'),
    topNegativeThemes: extractTopThemes(results, 'negative'),
    mostMentionedEntities: extractTopEntities(results),
  }

  await send($.ServiceResult.deliver, {
    requestId: request.id,
    outputs: {
      individual: results,
      aggregate,
      insights: generateSentimentInsights(aggregate),
    },
  })

  // Calculate cost
  const docCount = documents.length
  const tier = sentimentAnalysisService.pricing.tiers.find((t) => docCount >= t.documents.min && docCount <= t.documents.max)
  const rate = tier?.rate || 0.1
  const multiplier = request.inputs.realTime ? 1.5 : 1.0
  const cost = Math.max(docCount * rate * multiplier, 10.0)

  await send($.Payment.charge, {
    customerId: request.customerId,
    amount: cost,
    description: `Sentiment Analysis: ${docCount} documents`,
  })
})

function calculateOverallSentiment(results: any[]): string {
  const avgScore = results.reduce((sum, r) => sum + r.sentiment.score, 0) / results.length
  if (avgScore > 0.2) return 'positive'
  if (avgScore < -0.2) return 'negative'
  return 'neutral'
}

function extractTopThemes(results: any[], sentiment: string) {
  const themes = new Map()
  results.forEach((r) => {
    r.themes?.themes?.forEach((theme: any) => {
      if (theme.sentiment === sentiment) {
        const count = themes.get(theme.name) || 0
        themes.set(theme.name, count + theme.relevance)
      }
    })
  })
  return Array.from(themes.entries())
    .sort((a, b) => b[1] - a[1])
    .slice(0, 5)
    .map(([name, score]) => ({ name, score }))
}

function extractTopEntities(results: any[]) {
  const entities = new Map()
  results.forEach((r) => {
    if (r.entities) {
      Object.values(r.entities)
        .flat()
        .forEach((entity: any) => {
          const count = entities.get(entity) || 0
          entities.set(entity, count + 1)
        })
    }
  })
  return Array.from(entities.entries())
    .sort((a, b) => b[1] - a[1])
    .slice(0, 10)
}

function generateSentimentInsights(aggregate: any): string[] {
  const insights = []

  if (aggregate.sentimentDistribution.positive > aggregate.totalDocuments * 0.7) {
    insights.push('Overwhelmingly positive sentiment across all documents')
  }

  if (aggregate.sentimentDistribution.negative > aggregate.totalDocuments * 0.3) {
    insights.push('Significant negative sentiment requiring attention')
  }

  if (aggregate.topNegativeThemes.length > 0) {
    insights.push(`Primary concerns: ${aggregate.topNegativeThemes.map((t: any) => t.name).join(', ')}`)
  }

  return insights
}

Financial Analysis Service

Analyze financial statements and provide business intelligence:

import $, { ai, db, on, send } from 'sdk.do'

const financialAnalysisService = await $.Service.create({
  id: 'financial-analyzer',
  name: 'Financial Analysis Service',
  description: 'Analyze financial statements, ratios, and business performance',
  type: $.ServiceType.Analysis,
  subtype: 'financial-analysis',

  pricing: {
    model: 'per-analysis',
    tiers: [
      { name: 'basic', price: 150, features: ['ratio-analysis', 'trend-analysis'] },
      { name: 'professional', price: 500, features: ['all-basic', 'forecasting', 'benchmarking'] },
      { name: 'enterprise', price: 1500, features: ['all-professional', 'scenario-modeling', 'valuation'] },
    ],
  },
})

on($.ServiceRequest.created, async (request) => {
  if (request.serviceId !== financialAnalysisService.id) return

  const { financialStatements, industry, comparables, tier } = request.inputs

  // 1. Extract and validate financial data
  const financialData = await ai.generate({
    model: 'gpt-5',
    prompt: `Extract key financial metrics from these statements:

      ${JSON.stringify(financialStatements)}

      Extract:
      - Revenue (by period)
      - Gross profit
      - Operating income
      - Net income
      - Total assets
      - Total liabilities
      - Equity
      - Cash flow from operations
      - Free cash flow`,
    schema: {
      periods: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            period: { type: 'string' },
            revenue: { type: 'number' },
            grossProfit: { type: 'number' },
            operatingIncome: { type: 'number' },
            netIncome: { type: 'number' },
            assets: { type: 'number' },
            liabilities: { type: 'number' },
            equity: { type: 'number' },
            operatingCashFlow: { type: 'number' },
            freeCashFlow: { type: 'number' },
          },
        },
      },
    },
  })

  // 2. Calculate financial ratios
  const ratios = calculateFinancialRatios(financialData.data)

  // 3. Trend analysis
  const trends = await ai.generate({
    model: 'gpt-5',
    prompt: `Analyze financial trends:

      Data: ${JSON.stringify(financialData.data)}
      Ratios: ${JSON.stringify(ratios)}

      Analyze:
      - Revenue growth trends
      - Profitability trends
      - Efficiency trends
      - Leverage trends
      - Liquidity trends

      Identify concerning or positive patterns.`,
    schema: {
      trends: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            metric: { type: 'string' },
            direction: { type: 'string' },
            strength: { type: 'string' },
            analysis: { type: 'string' },
            concern: { type: 'boolean' },
          },
        },
      },
    },
  })

  // 4. Industry benchmarking
  let benchmarking = null
  if (tier !== 'basic') {
    const industryData = await fetchIndustryBenchmarks(industry)
    benchmarking = await ai.generate({
      model: 'gpt-5',
      prompt: `Compare financial performance to industry benchmarks:

        Company ratios: ${JSON.stringify(ratios)}
        Industry averages: ${JSON.stringify(industryData)}

        For each key ratio:
        - How does company compare?
        - Is it outperforming or underperforming?
        - What might explain the difference?`,
      schema: {
        comparisons: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              metric: { type: 'string' },
              companyValue: { type: 'number' },
              industryAverage: { type: 'number' },
              percentile: { type: 'number' },
              assessment: { type: 'string' },
            },
          },
        },
      },
    })
  }

  // 5. Forecasting
  let forecasts = null
  if (tier === 'professional' || tier === 'enterprise') {
    forecasts = await ai.generate({
      model: 'gpt-5',
      prompt: `Forecast future financial performance:

        Historical data: ${JSON.stringify(financialData.data)}
        Trends: ${JSON.stringify(trends.data)}

        Forecast next 3 years:
        - Revenue
        - EBITDA
        - Net income
        - Cash flow

        Include best case and worst case scenarios.`,
      schema: {
        forecasts: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              year: { type: 'number' },
              base: { type: 'object' },
              optimistic: { type: 'object' },
              pessimistic: { type: 'object' },
              assumptions: { type: 'array' },
            },
          },
        },
      },
    })
  }

  // 6. Generate insights and recommendations
  const insights = await ai.generate({
    model: 'gpt-5',
    prompt: `Provide financial insights and recommendations:

      Financial data: ${JSON.stringify(financialData.data)}
      Ratios: ${JSON.stringify(ratios)}
      Trends: ${JSON.stringify(trends.data)}
      Benchmarking: ${JSON.stringify(benchmarking?.data)}

      Provide:
      1. Key strengths
      2. Areas of concern
      3. Specific recommendations
      4. Risk factors
      5. Opportunities`,
    schema: {
      strengths: { type: 'array' },
      concerns: { type: 'array' },
      recommendations: { type: 'array' },
      risks: { type: 'array' },
      opportunities: { type: 'array' },
    },
  })

  await send($.ServiceResult.deliver, {
    requestId: request.id,
    outputs: {
      financialData: financialData.data,
      ratios,
      trends: trends.data,
      benchmarking: benchmarking?.data || null,
      forecasts: forecasts?.data || null,
      insights: insights.data,
      visualizations: await generateFinancialCharts({
        data: financialData.data,
        ratios,
        trends: trends.data,
      }),
    },
  })

  const pricing = financialAnalysisService.pricing.tiers.find((t) => t.name === tier)
  await send($.Payment.charge, {
    customerId: request.customerId,
    amount: pricing!.price,
    description: `Financial Analysis (${tier})`,
  })
})

function calculateFinancialRatios(data: any) {
  const latest = data.periods[data.periods.length - 1]

  return {
    profitability: {
      grossMargin: (latest.grossProfit / latest.revenue) * 100,
      operatingMargin: (latest.operatingIncome / latest.revenue) * 100,
      netMargin: (latest.netIncome / latest.revenue) * 100,
      roa: (latest.netIncome / latest.assets) * 100,
      roe: (latest.netIncome / latest.equity) * 100,
    },
    liquidity: {
      currentRatio: latest.assets / latest.liabilities,
      quickRatio: (latest.assets - latest.inventory || 0) / latest.liabilities,
    },
    efficiency: {
      assetTurnover: latest.revenue / latest.assets,
      revenuePerEmployee: latest.revenue / (latest.employeeCount || 1),
    },
    leverage: {
      debtToEquity: latest.liabilities / latest.equity,
      debtToAssets: latest.liabilities / latest.assets,
    },
    growth: {
      revenueGrowth: calculateGrowthRate(data.periods.map((p: any) => p.revenue)),
      profitGrowth: calculateGrowthRate(data.periods.map((p: any) => p.netIncome)),
    },
  }
}

function calculateGrowthRate(values: number[]): number {
  if (values.length < 2) return 0
  const first = values[0]
  const last = values[values.length - 1]
  const periods = values.length - 1
  return (Math.pow(last / first, 1 / periods) - 1) * 100
}

Anomaly Detection Service

Detect unusual patterns and outliers in data streams:

import $, { ai, db, on, send } from 'sdk.do'

const anomalyDetectionService = await $.Service.create({
  id: 'anomaly-detector',
  name: 'Anomaly Detection Service',
  description: 'Detect anomalies and unusual patterns in time-series data',
  type: $.ServiceType.Analysis,
  subtype: 'anomaly-detection',

  pricing: {
    model: 'subscription',
    tiers: [
      {
        name: 'starter',
        price: 99,
        dataPoints: 100000,
        alerts: 100,
      },
      {
        name: 'professional',
        price: 299,
        dataPoints: 1000000,
        alerts: 1000,
      },
      {
        name: 'enterprise',
        price: 999,
        dataPoints: 10000000,
        alerts: 'unlimited',
      },
    ],
    overage: {
      perThousandDataPoints: 0.01,
    },
  },
})

// Real-time anomaly detection
on($.DataPoint.created, async (dataPoint) => {
  // Get the metric configuration
  const metric = await db.get($.Metric, dataPoint.metricId)
  if (!metric.anomalyDetectionEnabled) return

  // Get historical data
  const history = await db.list($.DataPoint, {
    where: {
      metricId: dataPoint.metricId,
      timestamp: { gt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) }, // Last 30 days
    },
    orderBy: { timestamp: 'asc' },
  })

  // Detect anomaly
  const analysis = await ai.generate({
    model: 'gpt-5',
    prompt: `Analyze this data point for anomalies:

      Current value: ${dataPoint.value}
      Timestamp: ${dataPoint.timestamp}
      Metric: ${metric.name}

      Historical data (last 30 days):
      ${JSON.stringify(history.slice(-100))}

      Determine:
      1. Is this an anomaly?
      2. Type of anomaly (spike, drop, pattern change, outlier)
      3. Severity (low, medium, high, critical)
      4. Possible causes
      5. Recommended actions

      Consider:
      - Normal variation ranges
      - Seasonal patterns
      - Day of week patterns
      - Recent trends`,
    schema: {
      isAnomaly: { type: 'boolean' },
      type: { type: 'string' },
      severity: { type: 'string' },
      confidence: { type: 'number' },
      expectedRange: {
        type: 'object',
        properties: {
          min: { type: 'number' },
          max: { type: 'number' },
        },
      },
      deviation: { type: 'number' },
      causes: { type: 'array' },
      recommendations: { type: 'array' },
    },
  })

  if (analysis.data.isAnomaly) {
    // Log anomaly
    const anomaly = await db.create($.Anomaly, {
      metricId: dataPoint.metricId,
      dataPointId: dataPoint.id,
      type: analysis.data.type,
      severity: analysis.data.severity,
      confidence: analysis.data.confidence,
      expectedRange: analysis.data.expectedRange,
      actualValue: dataPoint.value,
      deviation: analysis.data.deviation,
      causes: analysis.data.causes,
      recommendations: analysis.data.recommendations,
      detectedAt: new Date(),
    })

    // Send alert if severity warrants it
    if (analysis.data.severity === 'high' || analysis.data.severity === 'critical') {
      await send($.Alert.create, {
        type: 'anomaly-detected',
        severity: analysis.data.severity,
        title: `Anomaly detected in ${metric.name}`,
        description: `${analysis.data.type}: ${dataPoint.value} (expected: ${analysis.data.expectedRange.min}-${analysis.data.expectedRange.max})`,
        anomalyId: anomaly.id,
        metadata: analysis.data,
      })
    }
  }
})

Customer Behavior Analysis Service

Analyze user behavior patterns and predict churn:

import $, { ai, db, on, send } from 'sdk.do'

const behaviorAnalysisService = await $.Service.create({
  id: 'behavior-analyzer',
  name: 'Customer Behavior Analysis',
  description: 'Analyze customer behavior patterns, predict churn, and identify upsell opportunities',
  type: $.ServiceType.Analysis,
  subtype: 'behavior-analysis',

  pricing: {
    model: 'per-customer',
    baseRate: 0.5,
    minimumCharge: 100.0,
    tiers: [
      { customers: { min: 1, max: 1000 }, rate: 0.5 },
      { customers: { min: 1001, max: 10000 }, rate: 0.3 },
      { customers: { min: 10001, max: Infinity }, rate: 0.1 },
    ],
  },
})

on($.ServiceRequest.created, async (request) => {
  if (request.serviceId !== behaviorAnalysisService.id) return

  const { customerIds, analysisType } = request.inputs
  const results = []

  for (const customerId of customerIds) {
    // Gather customer data
    const customer = await db.get($.Customer, customerId)
    const events = await db.list($.Event, {
      where: { customerId },
      orderBy: { timestamp: 'desc' },
      limit: 1000,
    })
    const purchases = await db.list($.Purchase, {
      where: { customerId },
      orderBy: { date: 'desc' },
    })

    // Analyze behavior patterns
    const analysis = await ai.generate({
      model: 'gpt-5',
      prompt: `Analyze customer behavior:

        Customer: ${JSON.stringify(customer)}
        Recent events (${events.length}): ${JSON.stringify(events.slice(0, 50))}
        Purchase history: ${JSON.stringify(purchases)}

        Provide:
        1. Engagement level (high/medium/low)
        2. Usage patterns
        3. Feature adoption
        4. Churn risk (0-1 score)
        5. Churn indicators
        6. Upsell opportunities
        7. Recommended actions`,
      schema: {
        engagement: { type: 'string' },
        usagePatterns: { type: 'array' },
        featureAdoption: { type: 'object' },
        churnRisk: { type: 'number' },
        churnIndicators: { type: 'array' },
        upsellOpportunities: { type: 'array' },
        recommendations: { type: 'array' },
        insights: { type: 'array' },
      },
    })

    results.push({
      customerId,
      analysis: analysis.data,
    })

    // Create alerts for high churn risk
    if (analysis.data.churnRisk > 0.7) {
      await send($.Alert.create, {
        type: 'high-churn-risk',
        severity: 'high',
        customerId,
        churnRisk: analysis.data.churnRisk,
        indicators: analysis.data.churnIndicators,
        recommendations: analysis.data.recommendations,
      })
    }
  }

  await send($.ServiceResult.deliver, {
    requestId: request.id,
    outputs: {
      analyses: results,
      summary: {
        totalCustomers: results.length,
        highChurnRisk: results.filter((r) => r.analysis.churnRisk > 0.7).length,
        mediumChurnRisk: results.filter((r) => r.analysis.churnRisk > 0.4 && r.analysis.churnRisk <= 0.7).length,
        upsellOpportunities: results.filter((r) => r.analysis.upsellOpportunities.length > 0).length,
      },
    },
  })

  // Calculate cost
  const tier = behaviorAnalysisService.pricing.tiers.find((t) => customerIds.length >= t.customers.min && customerIds.length <= t.customers.max)
  const cost = Math.max(customerIds.length * (tier?.rate || 0.5), behaviorAnalysisService.pricing.minimumCharge)

  await send($.Payment.charge, {
    customerId: request.customerId,
    amount: cost,
    description: `Behavior Analysis: ${customerIds.length} customers`,
  })
})

Pricing Models

Per-Analysis Pricing

const pricing = {
  model: 'per-analysis',
  baseRate: 100.0,
  variables: {
    dataSize: { perGB: 10.0 },
    depth: { basic: 1.0, detailed: 1.5, comprehensive: 2.0 },
    realTime: { multiplier: 1.5 },
  },
}

Subscription Pricing

const pricing = {
  model: 'subscription',
  tiers: [
    { name: 'starter', price: 99, analyses: 100, dataPoints: 100000 },
    { name: 'professional', price: 299, analyses: 1000, dataPoints: 1000000 },
    { name: 'enterprise', price: 999, analyses: 'unlimited', dataPoints: 10000000 },
  ],
}

Per-Dataset Pricing

const pricing = {
  model: 'per-dataset',
  tiers: [
    { size: { max: 1 }, rate: 50.0 }, // < 1GB
    { size: { min: 1, max: 10 }, rate: 30.0 }, // 1-10GB
    { size: { min: 10 }, rate: 20.0 }, // > 10GB
  ],
}

Best Practices

  1. Validate Input Data: Always check data quality before analysis
  2. Provide Confidence Scores: Include uncertainty in results
  3. Enable Comparisons: Support benchmarking and historical comparison
  4. Generate Visualizations: Make insights easy to understand
  5. Include Recommendations: Don't just analyze, provide actionable advice
  6. Handle Edge Cases: Gracefully handle insufficient or anomalous data
  7. Monitor Performance: Track analysis quality and accuracy over time