.do
Implementation Guides

Service Definition Guide

Complete guide to defining service specifications with schemas, capabilities, and constraints

Learn how to define comprehensive service specifications that enable autonomous service execution, clear customer expectations, and seamless service composition.

Why Service Definition Matters

A well-defined service specification is the foundation of Services-as-Software. It serves multiple critical purposes:

  1. Customer Clarity - Clear expectations about inputs, outputs, and guarantees
  2. Autonomous Execution - Enables AI to execute services without human guidance
  3. Service Discovery - Allows customers to find the right service for their needs
  4. Composition - Enables services to work together seamlessly
  5. Quality Assurance - Defines testable criteria for service quality
  6. Pricing Transparency - Clear pricing models based on service attributes

Service Schema Fundamentals

Basic Service Structure

Every service starts with a basic structure that identifies and describes it:

// @errors: 7006
import $ from 'sdk.do'

const service = await $.Service.create({
  // Identity
  name: 'Email Summarizer',
  //      ^?
  description: 'Condense long emails into brief, actionable summaries',
  version: '1.0.0',

  // Classification
  type: $.ServiceType.ContentGeneration,
  //      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  category: $.ServiceCategory.Productivity,

  // Tags for discovery
  tags: ['email', 'summarization', 'productivity', 'ai'],
  //      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
})

Key Fields Explained:

  • name - Human-readable service name (used in UI, invoices, etc.)
  • description - Clear explanation of what the service does
  • version - Semantic version for tracking changes
  • type - Primary service classification (from ServiceType vocabulary)
  • category - Business domain or use case
  • tags - Keywords for search and discovery

Input Specifications

Define exactly what inputs your service requires:

// @errors: 7006
const service = await $.Service.create({
  name: 'Content Translator',

  // Input specification
  input: {
    // Required fields (must be provided)
    required: ['text', 'targetLanguage'],
    //            ^^^^^^^^

    // Optional fields (have defaults or can be omitted)
    optional: ['sourceLanguage', 'tone', 'formality'],

    // Field schemas with types and constraints
    schema: {
      text: {
        type: 'string',
        //            ^^^^^^^^
        minLength: 10,
        maxLength: 50000,
        description: 'Text content to translate',
      },
      targetLanguage: {
        type: 'string',
        enum: ['en', 'es', 'fr', 'de', 'it', 'pt', 'ja', 'zh', 'ko'],
        //            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        description: 'Target language code (ISO 639-1)',
      },
      sourceLanguage: {
        type: 'string',
        enum: ['auto', 'en', 'es', 'fr', 'de', 'it', 'pt', 'ja', 'zh', 'ko'],
        default: 'auto',
        //               ^^^^^^
        description: 'Source language (auto-detect if not specified)',
      },
      tone: {
        type: 'string',
        enum: ['formal', 'informal', 'neutral'],
        default: 'neutral',
        description: 'Desired tone of translation',
      },
      formality: {
        type: 'string',
        enum: ['high', 'medium', 'low'],
        default: 'medium',
        description: 'Level of formality',
      },
    },
  },
})

Output Specifications

Define what customers receive from your service:

const service = await $.Service.create({
  name: 'SEO Content Optimizer',

  // Output specification
  output: {
    // Output schema
    schema: {
      optimizedContent: {
        type: 'string',
        description: 'SEO-optimized content',
      },
      seoScore: {
        type: 'number',
        min: 0,
        max: 100,
        description: 'SEO quality score',
      },
      improvements: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            type: { type: 'string' },
            description: { type: 'string' },
            impact: { type: 'string', enum: ['high', 'medium', 'low'] },
          },
        },
        description: 'List of improvements made',
      },
      keywords: {
        type: 'array',
        items: { type: 'string' },
        description: 'Optimized keywords used',
      },
      metadata: {
        type: 'object',
        properties: {
          titleTag: { type: 'string' },
          metaDescription: { type: 'string' },
          readabilityScore: { type: 'number' },
          wordCount: { type: 'number' },
        },
        description: 'SEO metadata',
      },
    },

    // Output format options
    formats: ['json', 'html', 'markdown'],

    // Default format
    defaultFormat: 'json',
  },
})

Advanced Schema Patterns

Complex Input Validation

Implement sophisticated validation rules:

const service = await $.Service.create({
  name: 'Advanced Data Validator',

  input: {
    required: ['data', 'validationType'],

    schema: {
      data: {
        type: 'object',
        description: 'Data to validate',
      },
      validationType: {
        type: 'string',
        enum: ['email', 'phone', 'address', 'creditCard', 'custom'],
        description: 'Type of validation to perform',
      },
      validationRules: {
        type: 'object',
        description: 'Custom validation rules (required if validationType is "custom")',
        properties: {
          pattern: {
            type: 'string',
            description: 'Regex pattern for validation',
          },
          minLength: { type: 'number' },
          maxLength: { type: 'number' },
          allowedChars: { type: 'string' },
          customValidator: { type: 'string' },
        },
      },
      strictMode: {
        type: 'boolean',
        default: false,
        description: 'Enable strict validation rules',
      },
    },

    // Cross-field validation rules
    validation: {
      rules: [
        {
          // Require validationRules when validationType is custom
          condition: "validationType === 'custom'",
          requires: ['validationRules'],
          message: 'validationRules is required when validationType is "custom"',
        },
        {
          // Validate pattern is valid regex
          field: 'validationRules.pattern',
          validator: (value) => {
            try {
              new RegExp(value)
              return true
            } catch {
              return false
            }
          },
          message: 'pattern must be a valid regular expression',
        },
      ],
    },
  },
})

Conditional Outputs

Define outputs that vary based on inputs or execution:

const service = await $.Service.create({
  name: 'Multi-Format Content Generator',

  input: {
    required: ['topic'],
    optional: ['formats', 'includeImages', 'includeSources'],
  },

  output: {
    schema: {
      content: {
        type: 'object',
        description: 'Generated content in requested formats',
        // Dynamic properties based on input.formats
        dynamic: true,
      },
      images: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            url: { type: 'string' },
            alt: { type: 'string' },
            caption: { type: 'string' },
          },
        },
        // Only included if input.includeImages is true
        conditional: (inputs) => inputs.includeImages === true,
      },
      sources: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            title: { type: 'string' },
            url: { type: 'string' },
            credibility: { type: 'number' },
          },
        },
        // Only included if input.includeSources is true
        conditional: (inputs) => inputs.includeSources === true,
      },
      metadata: {
        type: 'object',
        properties: {
          generatedAt: { type: 'string', format: 'date-time' },
          model: { type: 'string' },
          tokensUsed: { type: 'number' },
          cost: { type: 'number' },
        },
      },
    },
  },
})

Capability Declaration

Defining Capabilities

Declare what your service can do:

const service = await $.Service.create({
  name: 'Comprehensive Writing Assistant',

  // Explicit capability list
  capabilities: [
    {
      name: 'grammar-correction',
      description: 'Fix grammar and spelling errors',
      accuracy: 0.98,
      languages: ['en', 'es', 'fr', 'de'],
    },
    {
      name: 'style-improvement',
      description: 'Enhance writing style and clarity',
      accuracy: 0.92,
      subjective: true,
    },
    {
      name: 'tone-adjustment',
      description: 'Adjust tone (formal, casual, professional, etc.)',
      accuracy: 0.95,
      options: ['formal', 'casual', 'professional', 'friendly', 'authoritative'],
    },
    {
      name: 'content-expansion',
      description: 'Expand content with additional details',
      accuracy: 0.9,
      multiplier: { min: 1.5, max: 3.0 },
    },
    {
      name: 'content-compression',
      description: 'Condense content while preserving key points',
      accuracy: 0.93,
      compressionRatio: { min: 0.3, max: 0.7 },
    },
  ],

  // Capability limits
  limits: {
    maxWordCount: 10000,
    maxSimultaneousCapabilities: 3,
    languagesSupported: ['en', 'es', 'fr', 'de', 'it', 'pt'],
  },
})

Capability Combinations

Define how capabilities can be combined:

const service = await $.Service.create({
  name: 'Advanced Document Processor',

  capabilities: [
    {
      id: 'translation',
      name: 'Translation',
      compatibleWith: ['style-adjustment', 'formality-control'],
      incompatibleWith: ['language-detection'],
    },
    {
      id: 'summarization',
      name: 'Summarization',
      compatibleWith: ['key-points-extraction', 'executive-summary'],
      incompatibleWith: ['content-expansion'],
    },
    {
      id: 'content-expansion',
      name: 'Content Expansion',
      compatibleWith: ['research-integration', 'example-generation'],
      incompatibleWith: ['summarization', 'compression'],
    },
  ],

  // Preset capability bundles
  presets: {
    'blog-post': ['grammar-correction', 'seo-optimization', 'readability-enhancement'],
    'legal-document': ['formal-tone', 'precision-mode', 'citation-check'],
    'marketing-copy': ['persuasive-writing', 'call-to-action', 'emotional-appeal'],
  },
})

Constraint Definition

Service Constraints

Define limitations and requirements:

const service = await $.Service.create({
  name: 'Video Transcription Service',

  // Service constraints
  constraints: {
    // Input constraints
    input: {
      maxFileSize: 5 * 1024 * 1024 * 1024, // 5GB
      supportedFormats: ['mp4', 'mov', 'avi', 'mkv', 'webm'],
      maxDuration: 4 * 60 * 60, // 4 hours in seconds
      minDuration: 10, // 10 seconds
      requiresAudioTrack: true,
    },

    // Processing constraints
    processing: {
      maxConcurrentJobs: 10,
      estimatedTimePerMinute: 0.5, // 30 seconds per minute of video
      requiresGPU: false,
      memoryRequired: 4096, // MB
    },

    // Output constraints
    output: {
      maxTranscriptLength: 500000, // characters
      supportedFormats: ['text', 'srt', 'vtt', 'json'],
      includesTimestamps: true,
      includesSpeakerLabels: true,
    },

    // Rate limits
    rateLimit: {
      requestsPerMinute: 60,
      requestsPerHour: 1000,
      requestsPerDay: 10000,
    },

    // Business constraints
    business: {
      requiresSubscription: false,
      minimumPlan: 'free',
      availableRegions: ['us', 'eu', 'asia'],
      dataRetention: 30, // days
    },
  },
})

Quality Constraints

Define quality guarantees:

const service = await $.Service.create({
  name: 'Premium Content Writer',

  // Quality constraints and SLAs
  quality: {
    // Accuracy metrics
    accuracy: {
      grammar: { min: 0.99, target: 0.995 },
      factual: { min: 0.95, target: 0.98 },
      relevance: { min: 0.9, target: 0.95 },
    },

    // Performance metrics
    performance: {
      responseTime: { max: 300, target: 180 }, // seconds
      throughput: { min: 100, target: 200 }, // words per second
    },

    // Content quality metrics
    content: {
      readabilityScore: { min: 60, target: 75 }, // Flesch Reading Ease
      uniqueness: { min: 0.95, target: 0.99 }, // No plagiarism
      coherence: { min: 0.85, target: 0.92 },
      engagement: { min: 0.75, target: 0.85 },
    },

    // Validation rules
    validation: {
      spellCheck: true,
      grammarCheck: true,
      plagiarismCheck: true,
      factCheck: true,
      toneConsistency: true,
    },

    // Quality assurance process
    qa: {
      automated: true,
      humanReview: {
        enabled: false,
        threshold: 0.9, // Request human review if score < 90%
      },
      revisionPolicy: {
        maxRevisions: 2,
        freeRevisions: 1,
      },
    },
  },
})

Service Metadata

Comprehensive Metadata

Provide rich metadata about your service:

const service = await $.Service.create({
  name: 'Enterprise Data Analysis Service',

  metadata: {
    // Business metadata
    business: {
      owner: 'Data Analytics Team',
      department: 'Engineering',
      costCenter: 'CC-1234',
      businessUnit: 'Enterprise Solutions',
    },

    // Technical metadata
    technical: {
      runtime: 'node:20',
      framework: 'sdk.do',
      dependencies: ['openai', 'pandas', 'numpy'],
      infrastructure: 'cloudflare-workers',
      region: 'global',
    },

    // Support metadata
    support: {
      documentation: 'https://docs.example.com/data-analysis',
      examples: 'https://github.com/example/data-analysis-examples',
      supportEmail: '[email protected]',
      slackChannel: '#data-analysis-support',
      onCallTeam: 'data-team',
    },

    // Compliance metadata
    compliance: {
      gdpr: true,
      hipaa: false,
      soc2: true,
      iso27001: true,
      certifications: ['SOC2-Type-II', 'ISO-27001'],
    },

    // Usage metadata
    usage: {
      recommendedFor: ['data-scientists', 'business-analysts', 'researchers'],
      notRecommendedFor: ['real-time-applications', 'high-frequency-trading'],
      typicalUseCase: 'Batch analysis of business data',
      examples: ['Sales forecasting', 'Customer segmentation', 'Trend analysis', 'Performance reporting'],
    },

    // Performance metadata
    performance: {
      avgResponseTime: 45, // seconds
      p95ResponseTime: 120,
      p99ResponseTime: 180,
      availability: 99.95,
      successRate: 99.5,
    },
  },
})

Version Management

Semantic Versioning

Implement proper version management:

// Version 1.0.0 - Initial release
const serviceV1 = await $.Service.create({
  name: 'Email Summarizer',
  version: '1.0.0',

  input: {
    required: ['emailContent'],
  },

  output: {
    schema: {
      summary: { type: 'string' },
    },
  },
})

// Version 1.1.0 - Backward-compatible addition
const serviceV1_1 = await $.Service.create({
  name: 'Email Summarizer',
  version: '1.1.0',

  input: {
    required: ['emailContent'],
    optional: ['maxLength'], // NEW: Optional parameter
  },

  output: {
    schema: {
      summary: { type: 'string' },
      keyPoints: { type: 'array' }, // NEW: Additional output
    },
  },

  // Backward compatibility
  compatibility: {
    backwardCompatible: true,
    compatibleWith: ['1.0.0'],
  },
})

// Version 2.0.0 - Breaking changes
const serviceV2 = await $.Service.create({
  name: 'Email Summarizer',
  version: '2.0.0',

  input: {
    required: ['content'], // CHANGED: Renamed from emailContent
    optional: ['maxLength', 'style'], // NEW: Style option
  },

  output: {
    schema: {
      summary: { type: 'string' },
      keyPoints: { type: 'array' },
      actionItems: { type: 'array' }, // NEW: Action items
      sentiment: { type: 'string' }, // NEW: Sentiment analysis
    },
  },

  // Breaking changes
  compatibility: {
    backwardCompatible: false,
    migratesFrom: ['1.0.0', '1.1.0'],
    breaking: ['Renamed input field: emailContent -> content', 'Changed output structure'],
  },

  // Migration helper
  migration: {
    from: '1.x',
    transformer: async (oldInput) => ({
      content: oldInput.emailContent,
      maxLength: oldInput.maxLength,
    }),
  },
})

Version Deprecation

Properly deprecate old versions:

// Mark version as deprecated
await $.Service.deprecate({
  serviceId: serviceV1.id,
  version: '1.0.0',

  deprecation: {
    date: new Date('2025-12-31'),
    reason: 'Superseded by version 2.0.0 with enhanced features',
    alternative: {
      serviceId: serviceV2.id,
      version: '2.0.0',
      migrationGuide: 'https://docs.example.com/migration-v1-to-v2',
    },

    sunset: {
      date: new Date('2026-06-30'),
      notice: 'Service will be discontinued on June 30, 2026',
    },
  },
})

Complete Service Examples

Example 1: Simple Service

import $ from 'sdk.do'

const textSummarizerService = await $.Service.create({
  // Basic info
  name: 'Text Summarizer',
  description: 'Create concise summaries of long text documents',
  version: '1.0.0',

  // Classification
  type: $.ServiceType.ContentGeneration,
  category: $.ServiceCategory.Productivity,
  tags: ['summarization', 'text', 'nlp'],

  // Inputs
  input: {
    required: ['text'],
    optional: ['maxLength'],
    schema: {
      text: {
        type: 'string',
        minLength: 100,
        maxLength: 100000,
        description: 'Text to summarize',
      },
      maxLength: {
        type: 'number',
        min: 50,
        max: 1000,
        default: 200,
        description: 'Maximum summary length in words',
      },
    },
  },

  // Outputs
  output: {
    schema: {
      summary: {
        type: 'string',
        description: 'Concise summary of the text',
      },
      originalLength: {
        type: 'number',
        description: 'Length of original text in words',
      },
      summaryLength: {
        type: 'number',
        description: 'Length of summary in words',
      },
      compressionRatio: {
        type: 'number',
        description: 'Ratio of summary to original length',
      },
    },
  },

  // Quality guarantees
  sla: {
    responseTime: 30, // seconds
    accuracy: 0.9,
    availability: 99.9,
  },

  // Pricing
  pricing: {
    model: 'per-summary',
    rate: 0.1,
    currency: 'USD',
  },
})

Example 2: Complex Multi-Stage Service

import $ from 'sdk.do'

const contentMarketingService = await $.Service.create({
  // Identity
  name: 'Complete Content Marketing Suite',
  description: 'End-to-end content marketing from research to publication',
  version: '2.0.0',

  // Classification
  type: $.ServiceType.Composite,
  category: $.ServiceCategory.Marketing,
  tags: ['content-marketing', 'seo', 'blog', 'social-media'],

  // Multi-stage workflow
  workflow: {
    stages: [
      {
        id: 'research',
        name: 'Topic Research',
        description: 'Research topic and gather insights',
        required: true,
        estimatedDuration: 120, // seconds
        inputs: ['topic', 'targetKeywords'],
        outputs: ['researchData', 'competitorAnalysis', 'trendInsights'],
      },
      {
        id: 'outline',
        name: 'Content Outline',
        description: 'Create detailed content outline',
        required: true,
        estimatedDuration: 60,
        dependsOn: ['research'],
        inputs: ['researchData', 'contentType'],
        outputs: ['outline', 'structuredPlan'],
      },
      {
        id: 'content',
        name: 'Content Creation',
        description: 'Write high-quality content',
        required: true,
        estimatedDuration: 300,
        dependsOn: ['outline'],
        inputs: ['outline', 'tone', 'length'],
        outputs: ['content', 'metadata'],
      },
      {
        id: 'seo',
        name: 'SEO Optimization',
        description: 'Optimize content for search engines',
        required: true,
        estimatedDuration: 120,
        dependsOn: ['content'],
        inputs: ['content', 'targetKeywords'],
        outputs: ['optimizedContent', 'seoScore', 'recommendations'],
      },
      {
        id: 'images',
        name: 'Image Generation',
        description: 'Generate relevant images',
        required: false,
        estimatedDuration: 180,
        dependsOn: ['content'],
        inputs: ['content', 'imageCount', 'imageStyle'],
        outputs: ['images'],
      },
      {
        id: 'social',
        name: 'Social Media Posts',
        description: 'Create social media promotions',
        required: false,
        estimatedDuration: 90,
        dependsOn: ['content'],
        inputs: ['content', 'platforms'],
        outputs: ['socialPosts'],
      },
    ],

    // Workflow configuration
    configuration: {
      parallel: ['images', 'social'], // Can run in parallel
      sequential: ['research', 'outline', 'content', 'seo'], // Must run in order
      retryable: ['research', 'images'], // Can retry on failure
      maxDuration: 900, // 15 minutes total
    },
  },

  // Comprehensive inputs
  input: {
    required: ['topic', 'targetKeywords', 'targetAudience'],
    optional: ['tone', 'length', 'includeImages', 'generateSocial', 'contentType', 'urgency'],

    schema: {
      topic: {
        type: 'string',
        minLength: 5,
        maxLength: 200,
        description: 'Main topic for content',
      },
      targetKeywords: {
        type: 'array',
        items: { type: 'string' },
        minItems: 1,
        maxItems: 10,
        description: 'Keywords to target for SEO',
      },
      targetAudience: {
        type: 'object',
        properties: {
          demographic: { type: 'string' },
          industry: { type: 'string' },
          expertiseLevel: { type: 'string', enum: ['beginner', 'intermediate', 'expert'] },
        },
        description: 'Target audience characteristics',
      },
      tone: {
        type: 'string',
        enum: ['professional', 'casual', 'technical', 'conversational', 'authoritative'],
        default: 'professional',
      },
      length: {
        type: 'number',
        min: 500,
        max: 5000,
        default: 1500,
        description: 'Target word count',
      },
      includeImages: {
        type: 'boolean',
        default: false,
      },
      generateSocial: {
        type: 'boolean',
        default: false,
      },
      contentType: {
        type: 'string',
        enum: ['blog-post', 'article', 'guide', 'tutorial', 'case-study'],
        default: 'blog-post',
      },
      urgency: {
        type: 'string',
        enum: ['low', 'medium', 'high'],
        default: 'medium',
        description: 'Priority level for processing',
      },
    },
  },

  // Rich outputs
  output: {
    schema: {
      research: {
        type: 'object',
        properties: {
          insights: { type: 'array' },
          competitors: { type: 'array' },
          trends: { type: 'array' },
          opportunities: { type: 'array' },
        },
      },
      outline: {
        type: 'object',
        properties: {
          sections: { type: 'array' },
          structure: { type: 'object' },
          keyPoints: { type: 'array' },
        },
      },
      content: {
        type: 'string',
        description: 'Final optimized content',
      },
      seo: {
        type: 'object',
        properties: {
          score: { type: 'number', min: 0, max: 100 },
          titleTag: { type: 'string' },
          metaDescription: { type: 'string' },
          recommendations: { type: 'array' },
          keywords: { type: 'object' },
        },
      },
      images: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            url: { type: 'string' },
            alt: { type: 'string' },
            caption: { type: 'string' },
          },
        },
        conditional: (inputs) => inputs.includeImages,
      },
      socialPosts: {
        type: 'object',
        properties: {
          twitter: { type: 'array' },
          linkedin: { type: 'array' },
          facebook: { type: 'array' },
        },
        conditional: (inputs) => inputs.generateSocial,
      },
      metadata: {
        type: 'object',
        properties: {
          wordCount: { type: 'number' },
          readabilityScore: { type: 'number' },
          estimatedReadTime: { type: 'number' },
          quality: { type: 'number' },
        },
      },
    },
  },

  // Capabilities
  capabilities: [
    {
      name: 'topic-research',
      accuracy: 0.92,
      sources: ['web', 'news', 'academic'],
    },
    {
      name: 'content-generation',
      accuracy: 0.95,
      languages: ['en'],
    },
    {
      name: 'seo-optimization',
      accuracy: 0.93,
      metrics: ['keyword-density', 'readability', 'structure'],
    },
    {
      name: 'image-generation',
      accuracy: 0.9,
      styles: ['professional', 'creative', 'minimalist'],
    },
    {
      name: 'social-media-creation',
      accuracy: 0.94,
      platforms: ['twitter', 'linkedin', 'facebook'],
    },
  ],

  // Constraints
  constraints: {
    input: {
      maxTopicLength: 200,
      maxKeywords: 10,
      supportedLanguages: ['en'],
    },
    processing: {
      maxDuration: 900, // 15 minutes
      maxConcurrentStages: 2,
    },
    output: {
      maxContentLength: 10000,
      maxImages: 5,
      maxSocialPosts: 10,
    },
  },

  // Quality guarantees
  sla: {
    responseTime: 900, // 15 minutes
    accuracy: 0.93,
    availability: 99.9,

    metrics: {
      contentQuality: { min: 0.9 },
      seoScore: { min: 75 },
      readability: { min: 60 },
    },
  },

  // Flexible pricing
  pricing: {
    model: 'bundled',
    baseRate: 100.0,
    options: {
      images: 25.0,
      socialPosts: 15.0,
      urgent: 50.0, // Rush fee
    },
    currency: 'USD',

    // Discounts
    discounts: {
      volume: {
        '10-50': 0.1, // 10% off
        '50-100': 0.15, // 15% off
        '100+': 0.2, // 20% off
      },
      subscription: 0.25, // 25% off for subscribers
    },
  },

  // Rich metadata
  metadata: {
    business: {
      owner: 'Marketing Team',
      department: 'Product',
    },
    support: {
      documentation: 'https://docs.example.com/content-marketing',
      examples: 'https://github.com/example/content-examples',
    },
    compliance: {
      gdpr: true,
      soc2: true,
    },
    performance: {
      avgResponseTime: 600, // 10 minutes
      successRate: 98.5,
    },
  },
})

Example 3: Real-Time Service

import $ from 'sdk.do'

const liveTranslationService = await $.Service.create({
  // Identity
  name: 'Real-Time Translation Service',
  description: 'Live translation with streaming support',
  version: '1.0.0',

  // Classification
  type: $.ServiceType.Translation,
  category: $.ServiceCategory.Communication,
  tags: ['translation', 'real-time', 'streaming', 'multilingual'],

  // Execution mode
  executionMode: 'streaming',

  // Inputs
  input: {
    required: ['sourceLanguage', 'targetLanguage'],
    optional: ['streaming', 'formality', 'domain'],

    schema: {
      sourceLanguage: {
        type: 'string',
        enum: ['en', 'es', 'fr', 'de', 'it', 'pt', 'ja', 'zh', 'ko', 'ru', 'ar'],
        description: 'Source language code',
      },
      targetLanguage: {
        type: 'string',
        enum: ['en', 'es', 'fr', 'de', 'it', 'pt', 'ja', 'zh', 'ko', 'ru', 'ar'],
        description: 'Target language code',
      },
      streaming: {
        type: 'boolean',
        default: true,
        description: 'Enable streaming mode',
      },
      formality: {
        type: 'string',
        enum: ['formal', 'informal', 'neutral'],
        default: 'neutral',
      },
      domain: {
        type: 'string',
        enum: ['general', 'business', 'technical', 'medical', 'legal'],
        default: 'general',
        description: 'Domain-specific terminology',
      },
    },
  },

  // Streaming configuration
  streaming: {
    enabled: true,
    chunkSize: 100, // characters
    bufferSize: 500,
    latency: 200, // milliseconds
    protocol: 'websocket',
  },

  // Outputs
  output: {
    schema: {
      translatedText: {
        type: 'string',
        description: 'Translated text (full or chunk)',
      },
      confidence: {
        type: 'number',
        min: 0,
        max: 1,
        description: 'Translation confidence score',
      },
      alternatives: {
        type: 'array',
        items: { type: 'string' },
        description: 'Alternative translations',
      },
      metadata: {
        type: 'object',
        properties: {
          chunkId: { type: 'number' },
          timestamp: { type: 'string' },
          latency: { type: 'number' },
        },
      },
    },
  },

  // Capabilities
  capabilities: [
    {
      name: 'real-time-translation',
      accuracy: 0.94,
      latency: 200, // milliseconds
      languages: 11,
    },
    {
      name: 'domain-adaptation',
      accuracy: 0.89,
      domains: ['business', 'technical', 'medical', 'legal'],
    },
  ],

  // Constraints
  constraints: {
    streaming: {
      maxSessionDuration: 3600, // 1 hour
      maxChunkSize: 1000,
      maxConcurrentSessions: 100,
    },
    rateLimit: {
      chunksPerSecond: 10,
      sessionsPerUser: 5,
    },
  },

  // SLA
  sla: {
    latency: 200, // milliseconds
    accuracy: 0.94,
    availability: 99.95,
  },

  // Pricing
  pricing: {
    model: 'per-minute',
    rate: 0.5,
    currency: 'USD',
    minimumCharge: 1.0, // Minimum 2 minutes
  },
})

Best Practices

1. Clear and Specific Descriptions

Write descriptions that help customers understand exactly what your service does:

// ❌ Bad: Vague description
description: 'Helps with content'

// ✅ Good: Specific description
description: 'Generates SEO-optimized blog posts from topics and keywords, including research, writing, and optimization'

2. Comprehensive Input Validation

Define thorough input validation to prevent errors:

// ✅ Good: Detailed validation
input: {
  schema: {
    email: {
      type: 'string',
      pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$',
      maxLength: 255,
      description: 'Valid email address',
      errorMessages: {
        pattern: 'Please provide a valid email address',
        maxLength: 'Email address is too long',
      },
    },
  },
}

3. Realistic SLAs

Set achievable SLAs based on actual performance:

// ❌ Bad: Unrealistic
sla: {
  responseTime: 1, // 1 second for complex task
  accuracy: 1.0, // 100% accuracy
}

// ✅ Good: Realistic
sla: {
  responseTime: 180, // 3 minutes for complex task
  accuracy: 0.95, // 95% accuracy
  availability: 99.9, // Allow for maintenance
}

4. Version Changes Carefully

Plan version changes to minimize disruption:

// Maintain backward compatibility when possible
// Use minor versions (1.1.0) for additions
// Use major versions (2.0.0) for breaking changes
// Always provide migration guides

5. Document Everything

Provide comprehensive documentation:

Next Steps