.do
ScaleServices-as-Software

Service Examples

Service templates and real-world examples

Explore complete service examples and templates to accelerate your Services-as-Software development.

Customer Support Service

AI-powered customer support automation:

import { service, $, ai } from 'sdk.do'

export default service({
  name: 'AI Customer Support',
  description: 'Autonomous customer support with AI',

  pricing: {
    model: 'usage',
    metric: 'tickets_processed',
    tiers: [
      { up_to: 100, price_per_unit: 2.0 },
      { up_to: 1000, price_per_unit: 1.5 },
      { above: 1000, price_per_unit: 1.0 },
    ],
  },

  on: {
    '$.Ticket.created': async (event) => {
      const ticket = event.data

      // Categorize ticket
      const category = await ai.generate({
        model: 'gpt-5',
        schema: {
          category: ['billing', 'technical', 'general'],
          priority: ['low', 'medium', 'high', 'urgent'],
          sentiment: ['positive', 'neutral', 'negative'],
        },
        prompt: 'Categorize this support ticket',
        context: { ticket },
      })

      // Generate response
      const response = await ai.generate({
        model: 'claude-sonnet-4.5',
        prompt: 'Generate helpful response to customer inquiry',
        context: {
          ticket,
          category,
          knowledgeBase: await $.Knowledge.search(ticket.subject),
          customerHistory: await $.Customer.history(ticket.customerId),
        },
      })

      // Update ticket
      await ticket.update({
        category: category.category,
        priority: category.priority,
        suggestedResponse: response,
        status: category.priority === 'urgent' ? '$.Escalated' : '$.AwaitingReview',
      })

      // Auto-respond for simple queries
      if (category.priority === 'low' && category.sentiment !== 'negative') {
        await $.Email.send({
          to: ticket.customer.email,
          subject: `Re: ${ticket.subject}`,
          body: response,
        })

        await ticket.update({ status: '$.Resolved' })
      }
    },
  },
})

Content Generation Service

SEO-optimized content creation:

export default service({
  name: 'Content Generator',
  description: 'AI-powered SEO content generation',

  pricing: {
    model: 'subscription',
    plans: [
      { name: 'Starter', price: 49, features: ['10 articles/month'] },
      { name: 'Pro', price: 199, features: ['50 articles/month', 'SEO optimization'] },
      { name: 'Agency', price: 499, features: ['200 articles/month', 'Multi-brand'] },
    ],
  },

  api: {
    'POST /generate': async (req) => {
      const { topic, keywords, length, tone } = await req.json()

      // Generate article
      const article = await ai.generate({
        model: 'gpt-5',
        prompt: `Write an SEO-optimized article about ${topic}`,
        context: {
          keywords,
          targetLength: length,
          tone,
          seoGuidelines: await $.SEO.guidelines(),
        },
      })

      // Optimize for SEO
      const optimized = await ai.generate({
        model: 'gpt-5',
        prompt: 'Optimize this article for SEO',
        context: {
          article,
          keywords,
          competitors: await $.SEO.analyzeCompetitors(topic),
        },
      })

      // Generate meta tags
      const meta = await ai.generate({
        model: 'gpt-5',
        schema: {
          title: 'string',
          description: 'string',
          keywords: 'string[]',
        },
        prompt: 'Generate SEO meta tags',
        context: { article: optimized },
      })

      return {
        article: optimized,
        meta,
        seoScore: await $.SEO.score(optimized),
      }
    },
  },
})

Lead Scoring Service

Intelligent lead qualification:

export default service({
  name: 'Lead Scoring',
  description: 'AI-powered lead qualification and scoring',

  pricing: {
    model: 'outcome-based',
    outcomes: [{ metric: 'qualified_leads', price_per_outcome: 5.0 }],
  },

  on: {
    '$.Lead.created': async (event) => {
      const lead = event.data

      // Enrich lead data
      const enriched = await $.Enrichment.enrich({
        email: lead.email,
        company: lead.company,
      })

      // Score lead
      const score = await ai.generate({
        model: 'gpt-5',
        schema: {
          score: 'number', // 0-100
          signals: 'string[]',
          category: ['hot', 'warm', 'cold'],
          nextAction: 'string',
        },
        prompt: 'Score this lead',
        context: {
          lead,
          enriched,
          similarLeads: await $.Lead.findSimilar(lead),
        },
      })

      // Update lead
      await lead.update({
        score: score.score,
        category: score.category,
        enrichedData: enriched,
      })

      // Route to sales
      if (score.category === 'hot') {
        await $.send('$.Sales.assign-lead', {
          lead,
          priority: 'high',
          suggestedAction: score.nextAction,
        })
      }
    },
  },
})

Email Marketing Service

Automated email campaigns:

export default service({
  name: 'Email Marketing',
  description: 'AI-driven email campaigns',

  pricing: {
    model: 'hybrid',
    subscription: {
      base: 99,
      includes: 10000, // emails
    },
    overage: {
      metric: 'emails_sent',
      price_per_unit: 0.01,
    },
  },

  api: {
    'POST /campaign/create': async (req) => {
      const { audience, goal, content } = await req.json()

      // Generate campaign
      const campaign = await ai.generate({
        model: 'gpt-5',
        schema: $.EmailCampaign,
        prompt: 'Create email marketing campaign',
        context: {
          audience,
          goal,
          content,
          bestPractices: await $.Marketing.bestPractices('email'),
        },
      })

      // A/B test variants
      const variants = await Promise.all(
        [1, 2].map(() =>
          ai.generate({
            model: 'gpt-5',
            schema: $.EmailVariant,
            prompt: 'Create email variant',
            context: { campaign },
          })
        )
      )

      // Schedule campaign
      return await $.Campaign.create({
        ...campaign,
        variants,
        status: '$.Scheduled',
      })
    },
  },

  on: {
    '$.Campaign.send': async (event) => {
      const campaign = event.data
      const recipients = await $.Audience.resolve(campaign.audienceId)

      // Send emails
      for (const recipient of recipients) {
        const variant = selectVariant(campaign.variants)

        await $.Email.send({
          to: recipient.email,
          subject: variant.subject,
          body: personalize(variant.body, recipient),
          tracking: {
            campaignId: campaign.id,
            variantId: variant.id,
            recipientId: recipient.id,
          },
        })
      }
    },

    '$.Email.opened': async (event) => {
      // Track engagement
      await $.Metric.record({
        campaign: event.data.campaignId,
        variant: event.data.variantId,
        metric: 'open',
      })
    },
  },
})

Data Analysis Service

Automated insights and reporting:

export default service({
  name: 'Data Analytics',
  description: 'AI-powered data analysis and insights',

  pricing: {
    model: 'usage',
    metric: 'reports_generated',
    tiers: [
      { up_to: 10, price_per_unit: 10.0 },
      { up_to: 100, price_per_unit: 8.0 },
      { above: 100, price_per_unit: 6.0 },
    ],
  },

  api: {
    'POST /analyze': async (req) => {
      const { dataset, questions } = await req.json()

      // Analyze data
      const analysis = await ai.generate({
        model: 'gpt-5',
        schema: {
          insights: 'string[]',
          trends: 'string[]',
          anomalies: 'string[]',
          recommendations: 'string[]',
        },
        prompt: 'Analyze this dataset and answer questions',
        context: {
          dataset: await $.Data.summarize(dataset),
          questions,
        },
      })

      // Generate visualizations
      const charts = await generateCharts(dataset, analysis)

      // Create report
      const report = await ai.generate({
        model: 'gpt-5',
        prompt: 'Create executive summary report',
        context: {
          analysis,
          charts,
        },
      })

      return {
        analysis,
        charts,
        report,
      }
    },
  },
})

Social Media Manager

Automated social media posting:

export default service({
  name: 'Social Media Manager',
  description: 'AI-powered social media automation',

  pricing: {
    model: 'subscription',
    plans: [
      { name: 'Basic', price: 29, features: ['1 platform', '10 posts/month'] },
      { name: 'Pro', price: 99, features: ['3 platforms', '100 posts/month'] },
      { name: 'Agency', price: 299, features: ['All platforms', 'Unlimited posts'] },
    ],
  },

  scheduled: {
    daily: async () => {
      // Generate today's posts
      const accounts = await $.SocialAccount.findMany({
        where: { active: true },
      })

      for (const account of accounts) {
        const post = await ai.generate({
          model: 'gpt-5',
          prompt: 'Generate engaging social media post',
          context: {
            account,
            recentPosts: await account.getRecentPosts(),
            trending: await $.Social.trending(account.platform),
            brandVoice: account.brandVoice,
          },
        })

        await $.SocialPost.schedule({
          accountId: account.id,
          content: post,
          scheduledTime: findOptimalTime(account),
        })
      }
    },
  },

  on: {
    '$.Post.published': async (event) => {
      // Monitor engagement
      const post = event.data

      await $.schedule('1 hour', async () => {
        const engagement = await $.Social.getEngagement(post.id)

        if (engagement.rate < 0.02) {
          // Low engagement - analyze
          const analysis = await ai.generate({
            model: 'gpt-5',
            prompt: 'Why is this post underperforming?',
            context: { post, engagement },
          })

          // Send alert
          await $.send('$.Alert.low-engagement', {
            post,
            analysis,
          })
        }
      })
    },
  },
})

Inventory Management Service

Automated stock management:

export default service({
  name: 'Inventory Manager',
  description: 'AI-powered inventory optimization',

  pricing: {
    model: 'subscription',
    plans: [
      { name: 'Small', price: 99, features: ['Up to 1000 SKUs'] },
      { name: 'Medium', price: 299, features: ['Up to 10,000 SKUs'] },
      { name: 'Enterprise', price: 999, features: ['Unlimited SKUs'] },
    ],
  },

  scheduled: {
    hourly: async () => {
      // Check stock levels
      const lowStock = await $.Product.findMany({
        where: {
          stock: { lt: '$.reorderPoint' },
        },
      })

      for (const product of lowStock) {
        // Predict demand
        const forecast = await ai.generate({
          model: 'gpt-5',
          schema: {
            expectedDemand: 'number',
            confidence: 'number',
            seasonalFactors: 'string[]',
          },
          prompt: 'Forecast product demand',
          context: {
            product,
            salesHistory: await product.getSalesHistory(),
            trends: await $.Market.trends(product.category),
          },
        })

        // Calculate reorder quantity
        const quantity = calculateReorderQuantity(product, forecast)

        // Create purchase order
        await $.PurchaseOrder.create({
          productId: product.id,
          quantity,
          supplier: product.supplier,
          reasoning: forecast,
        })
      }
    },
  },
})

Sales Outreach Service

Automated sales development:

export default service({
  name: 'AI Sales Outreach',
  description: 'Automated sales prospecting and outreach',

  pricing: {
    model: 'per-qualified-lead',
    price: 50,
  },

  on: {
    '$.Campaign.started': async (event) => {
      const campaign = event.data

      // Get prospects matching ICP
      const prospects = await $.Prospect.findMany({
        where: campaign.targeting,
        limit: 100,
      })

      for (const prospect of prospects) {
        // Research prospect
        const research = await ai.generate({
          model: 'gpt-5',
          schema: {
            company: 'string',
            recentNews: 'string[]',
            painPoints: 'string[]',
            decisionMakers: 'string[]',
          },
          prompt: 'Research this prospect for sales outreach',
          context: { prospect },
        })

        // Generate personalized email
        const email = await ai.generate({
          model: 'claude-sonnet-4.5',
          prompt: 'Write personalized sales email',
          context: {
            prospect,
            research,
            product: campaign.product,
            sender: campaign.sender,
          },
        })

        // Send email
        await $.Email.send({
          to: prospect.email,
          from: campaign.sender.email,
          subject: email.subject,
          body: email.body,
          tracking: {
            campaignId: campaign.id,
            prospectId: prospect.id,
          },
        })

        // Schedule follow-ups
        await $.schedule('3 days', async () => {
          const opened = await $.Email.wasOpened(email.id)
          if (opened && !prospect.responded) {
            const followup = await ai.generate({
              model: 'gpt-5',
              prompt: 'Write follow-up email',
              context: { prospect, research, previousEmail: email },
            })

            await $.Email.send({
              to: prospect.email,
              from: campaign.sender.email,
              subject: followup.subject,
              body: followup.body,
            })
          }
        })
      }
    },

    '$.Email.replied': async (event) => {
      const reply = event.data

      // Analyze reply sentiment
      const analysis = await ai.generate({
        model: 'gpt-5',
        schema: {
          sentiment: ['positive', 'neutral', 'negative'],
          interested: 'boolean',
          nextAction: 'string',
        },
        prompt: 'Analyze sales reply',
        context: { reply },
      })

      if (analysis.interested) {
        // Qualify lead
        const qualified = await qualifyLead(reply.prospectId, analysis)

        if (qualified) {
          // Notify sales team
          await $.send('$.Lead.qualified', {
            prospect: reply.prospect,
            analysis,
            conversation: await $.Email.thread(reply.id),
          })
        }
      }
    },
  },
})

Meeting Scheduling Service

AI meeting coordinator:

export default service({
  name: 'Meeting Scheduler',
  description: 'AI-powered meeting coordination',

  pricing: {
    model: 'subscription',
    plans: [
      { name: 'Basic', price: 9, features: ['10 meetings/month'] },
      { name: 'Pro', price: 29, features: ['Unlimited meetings'] },
    ],
  },

  on: {
    '$.Meeting.requested': async (event) => {
      const request = event.data

      // Find available times
      const availability = await Promise.all(
        request.attendees.map((attendee) =>
          $.Calendar.getAvailability(attendee.calendarId, {
            startDate: request.preferredStart,
            endDate: request.preferredEnd,
            timezone: request.timezone,
          })
        )
      )

      // Find overlapping slots
      const slots = findOverlappingSlots(availability)

      // Generate meeting options
      const options = await ai.generate({
        model: 'gpt-5',
        schema: {
          slots: 'array',
          reasoning: 'string',
        },
        prompt: 'Select best meeting times',
        context: {
          slots,
          preferences: request.preferences,
          attendees: request.attendees,
        },
      })

      // Send calendar invites
      for (const slot of options.slots.slice(0, 3)) {
        const invite = await $.Calendar.createInvite({
          title: request.title,
          start: slot.start,
          end: slot.end,
          attendees: request.attendees,
          location: request.location || 'Video Call',
          description: request.description,
        })

        // Send email with calendar invite
        await $.Email.send({
          to: request.organizer.email,
          subject: `Meeting scheduled: ${request.title}`,
          body: generateInviteEmail(invite),
          attachments: [invite.ics],
        })
      }
    },

    '$.Meeting.rescheduled': async (event) => {
      const meeting = event.data

      // Cancel old meeting
      await $.Calendar.cancel(meeting.oldEventId)

      // Create new meeting
      await $.send('$.Meeting.requested', {
        ...meeting,
        reason: 'rescheduled',
      })

      // Notify attendees
      await notifyAttendees(meeting, 'rescheduled')
    },
  },
})

Invoice Processing Service

Automated accounts payable:

export default service({
  name: 'Invoice Processor',
  description: 'AI-powered invoice processing',

  pricing: {
    model: 'usage',
    metric: 'invoices_processed',
    tiers: [
      { up_to: 100, price_per_unit: 0.5 },
      { up_to: 1000, price_per_unit: 0.3 },
      { above: 1000, price_per_unit: 0.2 },
    ],
  },

  on: {
    '$.Invoice.received': async (event) => {
      const invoice = event.data

      // Extract data from invoice (PDF/image)
      const extracted = await ai.generate({
        model: 'gpt-5',
        schema: $.InvoiceData,
        prompt: 'Extract invoice data',
        context: {
          document: invoice.document,
          format: invoice.format,
        },
      })

      // Validate invoice
      const validation = await ai.generate({
        model: 'gpt-5',
        schema: {
          valid: 'boolean',
          issues: 'string[]',
          confidence: 'number',
        },
        prompt: 'Validate invoice data',
        context: {
          extracted,
          purchaseOrders: await $.PurchaseOrder.findMany({
            where: { vendor: extracted.vendor },
          }),
        },
      })

      if (validation.valid && validation.confidence > 0.95) {
        // Match to purchase order
        const po = await $.PurchaseOrder.match(extracted)

        // Create payment
        await $.Payment.create({
          vendor: extracted.vendor,
          amount: extracted.total,
          dueDate: extracted.dueDate,
          invoiceId: invoice.id,
          purchaseOrderId: po?.id,
        })

        // Schedule payment
        await $.schedule(extracted.dueDate, async () => {
          await $.Payment.process(invoice.id)
        })

        // Update accounting
        await $.Accounting.recordExpense({
          category: extracted.category,
          amount: extracted.total,
          vendor: extracted.vendor,
          date: new Date(),
        })
      } else {
        // Flag for review
        await $.send('$.Invoice.needsReview', {
          invoice,
          extracted,
          validation,
        })
      }
    },
  },
})

Competitor Monitoring Service

Track competitor activity:

export default service({
  name: 'Competitor Monitor',
  description: 'AI-powered competitive intelligence',

  pricing: {
    model: 'subscription',
    plans: [
      { name: 'Starter', price: 99, features: ['5 competitors'] },
      { name: 'Pro', price: 299, features: ['20 competitors', 'alerts'] },
      { name: 'Enterprise', price: 999, features: ['Unlimited', 'API'] },
    ],
  },

  scheduled: {
    hourly: async () => {
      const competitors = await $.Competitor.findMany({
        where: { active: true },
      })

      for (const competitor of competitors) {
        // Check website for changes
        const changes = await $.Web.detectChanges({
          url: competitor.website,
          lastChecked: competitor.lastChecked,
        })

        if (changes.detected) {
          // Analyze changes
          const analysis = await ai.generate({
            model: 'gpt-5',
            schema: {
              changes: 'string[]',
              significance: ['low', 'medium', 'high'],
              actionable: 'boolean',
              insights: 'string[]',
            },
            prompt: 'Analyze competitor website changes',
            context: {
              changes: changes.diff,
              competitor,
              ourProduct: await $.Product.get('ours'),
            },
          })

          // Store analysis
          await $.CompetitorUpdate.create({
            competitorId: competitor.id,
            type: 'website_change',
            changes: changes.diff,
            analysis,
            detectedAt: new Date(),
          })

          // Alert if significant
          if (analysis.significance === 'high' || analysis.actionable) {
            await $.send('$.Alert.competitor-activity', {
              competitor,
              analysis,
              changes,
            })
          }
        }

        // Check social media
        const social = await $.Social.getLatestPosts(competitor.socialAccounts)

        for (const post of social) {
          if (post.isNew) {
            const sentiment = await ai.generate({
              model: 'gpt-5',
              schema: {
                topic: 'string',
                sentiment: 'string',
                engagement: 'number',
                implications: 'string[]',
              },
              prompt: 'Analyze competitor social post',
              context: { post, competitor },
            })

            await $.CompetitorUpdate.create({
              competitorId: competitor.id,
              type: 'social_post',
              content: post,
              analysis: sentiment,
            })
          }
        }

        // Check for news mentions
        const news = await $.News.search({
          query: competitor.name,
          since: competitor.lastChecked,
        })

        for (const article of news) {
          const summary = await ai.generate({
            model: 'gpt-5',
            prompt: 'Summarize news article',
            context: { article, competitor },
          })

          await $.CompetitorUpdate.create({
            competitorId: competitor.id,
            type: 'news_mention',
            content: article,
            summary,
          })
        }

        // Update last checked
        await competitor.update({
          lastChecked: new Date(),
        })
      }
    },

    // Weekly summary
    weekly: async () => {
      const competitors = await $.Competitor.findMany()

      for (const competitor of competitors) {
        const updates = await $.CompetitorUpdate.findMany({
          where: {
            competitorId: competitor.id,
            createdAt: { gte: sevenDaysAgo() },
          },
        })

        // Generate weekly summary
        const summary = await ai.generate({
          model: 'claude-sonnet-4.5',
          prompt: 'Create weekly competitor intelligence summary',
          context: {
            competitor,
            updates,
            ourActivity: await getOurActivity(),
          },
        })

        // Send to stakeholders
        await $.Email.send({
          to: await $.Team.emails('competitive-intel'),
          subject: `Weekly Intelligence: ${competitor.name}`,
          body: summary,
        })
      }
    },
  },
})

Resume Screening Service

Automated candidate screening:

export default service({
  name: 'Resume Screener',
  description: 'AI-powered resume screening and ranking',

  pricing: {
    model: 'per-candidate',
    price: 2,
  },

  on: {
    '$.Application.submitted': async (event) => {
      const application = event.data

      // Extract resume data
      const parsed = await ai.generate({
        model: 'gpt-5',
        schema: $.ResumeData,
        prompt: 'Parse resume',
        context: {
          resume: application.resume,
          format: application.format,
        },
      })

      // Score against job requirements
      const score = await ai.generate({
        model: 'gpt-5',
        schema: {
          overallScore: 'number',  // 0-100
          categoryScores: {
            experience: 'number',
            education: 'number',
            skills: 'number',
            culture: 'number',
          },
          strengths: 'string[]',
          concerns: 'string[]',
          recommendation: ['reject', 'maybe', 'interview', 'strong_yes'],
        },
        prompt: 'Score candidate against job requirements',
        context: {
          candidate: parsed,
          jobDescription: application.job,
          requirements: application.job.requirements,
          company: await $.Company.get(),
        },
      })

      // Update application
      await application.update({
        parsed,
        score: score.overallScore,
        recommendation: score.recommendation,
        analysis: score,
      })

      // Auto-actions based on score
      if (score.recommendation === 'reject') {
        // Send rejection email
        await $.Email.send({
          to: application.email,
          template: 'application-rejected',
          data: { application },
        })

        await application.update({ status: '$.Rejected' })
      } else if (score.recommendation === 'strong_yes') {
        // Auto-schedule screening call
        await $.send('$.Interview.schedule', {
          applicationId: application.id,
          type: 'phone-screen',
          priority: 'high',
        })

        // Notify hiring manager
        await $.send('$.Notification.sent', {
          to: application.job.hiringManager,
          type: 'strong-candidate',
          data: { application, score },
        })
      } else {
        // Add to review queue
        await $.send('$.Application.needsReview', {
          application,
          score,
        })
      }

      // Record for analytics
      await $.Metric.record('application_processed', {
        jobId: application.job.id,
        score: score.overallScore,
        recommendation: score.recommendation,
      })
    },
  },

  api: {
    'GET /rankings/:jobId': async (req) => {
      const { jobId } = req.params
      const { limit = 20 } = req.query

      const applications = await $.Application.findMany({
        where: { jobId },
        orderBy: { score: 'desc' },
        limit,
      })

      return {
        job: await $.Job.get(jobId),
        topCandidates: applications,
        stats: await $.Application.stats(jobId),
      }
    },
  },
})

Knowledge Base Service

Automated documentation and Q&A:

export default service({
  name: 'Knowledge Base',
  description: 'AI-powered knowledge management',

  pricing: {
    model: 'subscription',
    plans: [
      { name: 'Team', price: 49, features: ['100 articles', '1K queries'] },
      { name: 'Business', price: 199, features: ['1K articles', '10K queries'] },
      { name: 'Enterprise', price: 499, features: ['Unlimited'] },
    ],
  },

  on: {
    '$.Document.created': async (event) => {
      const document = event.data

      // Generate searchable index
      const index = await ai.generate({
        model: 'gpt-5',
        schema: {
          summary: 'string',
          topics: 'string[]',
          keywords: 'string[]',
          relatedDocs: 'string[]',
        },
        prompt: 'Index document for search',
        context: {
          document,
          existingDocs: await $.Document.list(),
        },
      })

      // Store index
      await $.Index.create({
        documentId: document.id,
        ...index,
        embedding: await $.ai.embed(document.content),
      })

      // Generate suggested FAQs
      const faqs = await ai.generate({
        model: 'gpt-5',
        schema: {
          questions: 'array',
        },
        prompt: 'Generate FAQ questions from document',
        context: { document },
      })

      for (const faq of faqs.questions) {
        await $.FAQ.create({
          question: faq.question,
          answer: faq.answer,
          documentId: document.id,
          source: 'auto-generated',
        })
      }
    },

    '$.Query.asked': async (event) => {
      const query = event.data

      // Search knowledge base
      const results = await $.Search.semantic({
        query: query.question,
        limit: 5,
        threshold: 0.7,
      })

      // Generate answer
      const answer = await ai.generate({
        model: 'claude-sonnet-4.5',
        prompt: 'Answer question using knowledge base',
        context: {
          question: query.question,
          documents: results.map((r) => r.content),
          sources: results.map((r) => r.source),
        },
      })

      // Store Q&A
      await $.QA.create({
        question: query.question,
        answer: answer,
        sources: results.map((r) => r.id),
        confidence: results[0]?.score || 0,
      })

      // Return to user
      return {
        answer,
        sources: results,
        confidence: results[0]?.score || 0,
      }
    },
  },

  api: {
    'POST /search': async (req) => {
      const { query, limit = 10 } = await req.json()

      const results = await $.Search.semantic({
        query,
        limit,
      })

      return { results }
    },

    'POST /ask': async (req) => {
      const { question } = await req.json()

      return await $.send('$.Query.asked', { question })
    },
  },
})

Translation Service

Multi-language content translation:

export default service({
  name: 'Translation Service',
  description: 'AI-powered translation with context awareness',

  pricing: {
    model: 'usage',
    metric: 'words_translated',
    tiers: [
      { up_to: 100000, price_per_unit: 0.01 },
      { up_to: 1000000, price_per_unit: 0.008 },
      { above: 1000000, price_per_unit: 0.005 },
    ],
  },

  api: {
    'POST /translate': async (req) => {
      const { text, sourceLang, targetLang, context, domain } = await req.json()

      // Translate with context
      const translation = await ai.generate({
        model: 'gpt-5',
        prompt: `Translate from ${sourceLang} to ${targetLang}`,
        context: {
          text,
          domain,  // e.g., 'technical', 'marketing', 'legal'
          context,  // Additional context for better translation
          glossary: await $.Glossary.get(domain),
        },
      })

      // Validate translation
      const validation = await ai.generate({
        model: 'claude-sonnet-4.5',
        schema: {
          quality: 'number',  // 0-1
          issues: 'string[]',
          suggestions: 'string[]',
        },
        prompt: 'Validate translation quality',
        context: {
          original: text,
          translation,
          sourceLang,
          targetLang,
        },
      })

      // Record usage
      const wordCount = text.split(/\s+/).length
      await $.Usage.record({
        metric: 'words_translated',
        quantity: wordCount,
        metadata: { sourceLang, targetLang, domain },
      })

      return {
        translation,
        quality: validation.quality,
        wordCount,
        cost: calculateCost(wordCount),
      }
    },

    'POST /translate/batch': async (req) => {
      const { texts, sourceLang, targetLangs, domain } = await req.json()

      const results = await Promise.all(
        targetLangs.map(async (targetLang) => {
          const translations = await Promise.all(
            texts.map((text) =>
              ai.generate({
                model: 'gpt-5',
                prompt: `Translate from ${sourceLang} to ${targetLang}`,
                context: {
                  text,
                  domain,
                  glossary: await $.Glossary.get(domain),
                },
              })
            )
          )

          return {
            targetLang,
            translations,
          }
        })
      )

      return { results }
    },
  },
})

Template Service Starter

Blank template to start from:

import { service, $, ai } from 'sdk.do'

export default service({
  name: 'My Service',
  description: 'Service description',
  version: '1.0.0',

  // Choose pricing model
  pricing: {
    model: 'subscription',
    plans: [
      {
        name: 'Basic',
        price: 29,
        interval: 'month',
        features: ['Feature 1', 'Feature 2'],
      },
    ],
  },

  // Event handlers
  on: {
    '$.Event.type': async (event) => {
      // Handle event
    },
  },

  // API endpoints
  api: {
    'GET /health': () => ({ status: 'ok' }),
  },

  // Scheduled jobs
  scheduled: {
    daily: async () => {
      // Run daily job
    },
  },
})

Next Steps