mdxui

Functions

Understanding the four function types - Code, Generative, Agentic, and Human

Functions

A Function is executable logic in the system. There are four types of functions, each with different execution characteristics and requirements.


The Function Type System

Functions are categorized by how they execute and which actor runs them:

TypeActorExecution StyleAutonomyExample
CodeServiceAccountDeterministic, directNoneTransform data, validate input
GenerativeModelLLM generation, directLimitedGenerate copy, summarize text
AgenticAgentAutonomous, multi-stepHighResearch, multi-step workflows
HumanHumanManual, judgment-basedFullApprove invoices, review content

Code Functions

Code functions are deterministic functions executed by ServiceAccounts.

Characteristics

  • Actor: ServiceAccount
  • Execution: Synchronous, deterministic
  • Input: Structured data
  • Output: Structured data
  • Reliability: 100% predictable given the same input

Use Cases

Code functions handle all deterministic logic:

CategoryExamples
Data transformationParse JSON, convert formats, map objects
ValidationCheck email format, validate schemas, enforce rules
ComputationCalculate totals, aggregate metrics, run formulas
IntegrationCall external APIs, sync data, send webhooks
I/O operationsRead files, write databases, send emails

Example: Data Validation

// Code function - deterministic validation
async function validateInvoice(invoice: Invoice): Promise<ValidationResult> {
  const errors: string[] = []

  if (!invoice.amount || invoice.amount <= 0) {
    errors.push('Invoice amount must be positive')
  }

  if (!invoice.customerId) {
    errors.push('Customer ID is required')
  }

  if (!invoice.dueDate || invoice.dueDate < new Date()) {
    errors.push('Due date must be in the future')
  }

  return {
    valid: errors.length === 0,
    errors
  }
}

Example: Data Transformation

// Code function - transform data structure
async function transformInvoiceToPayment(invoice: Invoice): Promise<PaymentIntent> {
  return {
    amount: invoice.amount,
    currency: invoice.currency || 'usd',
    customer: invoice.customerId,
    description: `Payment for Invoice ${invoice.id}`,
    metadata: {
      invoiceId: invoice.id,
      invoiceNumber: invoice.number
    }
  }
}

Example: Integration

// Code function - external API call
async function sendToAccounting(invoice: Invoice): Promise<void> {
  await fetch('https://accounting-api.example.com/invoices', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.ACCOUNTING_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(invoice)
  })
}

When to Use Code Functions

Use Code functions when:

  • The logic is deterministic and rule-based
  • You need predictable, repeatable results
  • Performance and speed are critical
  • The function is pure computation or I/O
  • No creativity or judgment is required

Generative Functions

Generative functions use LLMs to generate content or make predictions through direct generation.

Characteristics

  • Actor: Model
  • Execution: Synchronous, single-turn LLM call
  • Input: Text prompts and structured data
  • Output: Generated text or structured data
  • Reliability: Probabilistic, varies by prompt and model

Use Cases

Generative functions handle tasks requiring language understanding and generation:

CategoryExamples
Content generationWrite copy, create descriptions, draft emails
SummarizationCondense documents, extract key points
ClassificationCategorize content, sentiment analysis, tag generation
ExtractionPull structured data from unstructured text
TranslationConvert between languages, formats, tones
AnalysisAnalyze text, identify patterns, provide insights

Example: Content Generation

// Generative function - create product description
async function generateProductDescription(product: Product): Promise<string> {
  const prompt = `
Generate a compelling product description for:

Name: ${product.name}
Category: ${product.category}
Features: ${product.features.join(', ')}
Target audience: ${product.targetAudience}

Write 2-3 paragraphs that highlight benefits and use cases.
`

  const response = await anthropic.messages.create({
    model: 'claude-sonnet-4-5',
    max_tokens: 500,
    messages: [{ role: 'user', content: prompt }]
  })

  return response.content[0].text
}

Example: Classification

// Generative function - classify support ticket
async function classifyTicket(ticket: SupportTicket): Promise<TicketCategory> {
  const prompt = `
Classify this support ticket into one category:
- billing
- technical
- feature_request
- bug_report
- other

Ticket: ${ticket.description}

Respond with just the category name.
`

  const response = await openai.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: prompt }],
    temperature: 0
  })

  return response.choices[0].message.content as TicketCategory
}

Example: Extraction

// Generative function - extract structured data
async function extractInvoiceData(ocrText: string): Promise<InvoiceData> {
  const prompt = `
Extract invoice data from this OCR text and return as JSON:

${ocrText}

Return JSON with these fields:
- invoiceNumber: string
- amount: number
- currency: string
- dueDate: string (ISO format)
- vendorName: string
`

  const response = await anthropic.messages.create({
    model: 'claude-sonnet-4-5',
    messages: [{ role: 'user', content: prompt }]
  })

  return JSON.parse(response.content[0].text)
}

Code vs Generative Functions

AspectCodeGenerative
ExecutionDeterministicProbabilistic
LogicRule-basedLLM-based
Predictability100%Varies
SpeedFastSlower
CostNegligiblePer token
Best forComputation, I/OLanguage tasks

When to Use Generative Functions

Use Generative functions when:

  • You need natural language understanding or generation
  • The task involves creativity or subjective judgment
  • Rules-based logic is too rigid or complex
  • You need to process unstructured text
  • Classification or extraction is required
  • The function is a single-turn interaction

Agentic Functions

Agentic functions are complex tasks performed autonomously by Agents through multi-step workflows.

Characteristics

  • Actor: Agent (implements Worker interface)
  • Execution: Asynchronous, multi-turn, autonomous
  • Input: Task description and context
  • Output: Task result after multi-step execution
  • Reliability: Varies, depends on task complexity and tools available

Use Cases

Agentic functions handle complex, multi-step tasks requiring planning and tool use:

CategoryExamples
ResearchGather information from multiple sources, competitive analysis
AnalysisAnalyze data, identify trends, provide insights
Problem-solvingDebug code, troubleshoot issues, find solutions
PlanningCreate implementation plans, design systems
Multi-step workflowsComplete tasks requiring multiple steps and decisions

Example: Research Task

// Agentic function - multi-step research
async function researchCompetitor(company: string, agent: Agent): Promise<CompetitorReport> {
  const task: Task = {
    type: 'research',
    description: `Research ${company} and provide a competitive analysis`,
    context: {
      company,
      focusAreas: ['products', 'pricing', 'market_position', 'recent_news']
    }
  }

  // Agent autonomously:
  // 1. Plans the research approach
  // 2. Searches the web for information
  // 3. Visits and analyzes competitor websites
  // 4. Synthesizes findings into a report
  const result = await agent.do(task)

  return result.data as CompetitorReport
}

Example: Code Analysis

// Agentic function - analyze codebase
async function analyzeCodeQuality(repo: Repository, agent: Agent): Promise<QualityReport> {
  const task: Task = {
    type: 'analysis',
    description: 'Analyze code quality and provide recommendations',
    context: {
      repoUrl: repo.url,
      language: repo.primaryLanguage,
      focusAreas: ['architecture', 'testing', 'documentation', 'performance']
    }
  }

  // Agent autonomously:
  // 1. Clones repository
  // 2. Analyzes code structure
  // 3. Runs static analysis tools
  // 4. Reviews test coverage
  // 5. Generates comprehensive report
  const result = await agent.do(task)

  return result.data as QualityReport
}

Example: Multi-Step Workflow

// Agentic function - complete complex workflow
async function createFeatureImplementation(
  feature: FeatureRequest,
  agent: Agent
): Promise<Implementation> {
  const task: Task = {
    type: 'implementation',
    description: `Create implementation plan and code for: ${feature.title}`,
    context: {
      requirements: feature.requirements,
      codebase: feature.codebaseContext,
      constraints: feature.constraints
    }
  }

  // Agent autonomously:
  // 1. Analyzes requirements
  // 2. Reviews existing codebase
  // 3. Designs solution architecture
  // 4. Writes implementation code
  // 5. Creates tests
  // 6. Generates documentation
  const result = await agent.do(task)

  return result.data as Implementation
}

Generative vs Agentic Functions

AspectGenerativeAgentic
TurnsSingleMultiple
PlanningNoneAutonomous
Tool useNoYes
AutonomyLowHigh
ComplexitySimpleComplex
Best forDirect generationMulti-step tasks

When to Use Agentic Functions

Use Agentic functions when:

  • The task requires multiple steps
  • Planning and decision-making are needed
  • You need to use external tools or APIs
  • The workflow is exploratory or research-oriented
  • The task is too complex for a single LLM call
  • You need autonomous execution

Human Functions

Human functions are tasks performed manually by humans, requiring judgment, creativity, or oversight.

Characteristics

  • Actor: Human (implements Worker interface)
  • Execution: Asynchronous, manual
  • Input: Task description and UI
  • Output: Human decision or work product
  • Reliability: Varies by person and task complexity

Use Cases

Human functions handle tasks requiring human judgment, creativity, or compliance:

CategoryExamples
ApprovalApprove invoices, sign contracts, authorize payments
ReviewCode review, content review, quality assurance
Decision-makingStrategic decisions, edge cases, policy exceptions
Creative workDesign, writing, strategy, branding
ComplianceLegal review, regulatory approval, audit

Example: Invoice Approval

// Human function - approve invoice
async function approveInvoice(invoice: Invoice, human: Human): Promise<ApprovalResult> {
  const task: HumanTask = {
    type: 'approval',
    assignee: human,
    description: `Approve invoice ${invoice.number} for ${invoice.amount}`,
    data: invoice,
    ui: {
      type: 'slack',
      template: 'invoice-approval'
    }
  }

  // Creates task, notifies human via Slack
  // Human reviews and clicks approve/reject
  const result = await human.do(task)

  return result.data as ApprovalResult
}

Example: Content Review

// Human function - review blog post
async function reviewBlogPost(post: BlogPost, reviewer: Human): Promise<ReviewResult> {
  const task: HumanTask = {
    type: 'review',
    assignee: reviewer,
    description: `Review blog post: ${post.title}`,
    data: {
      post,
      criteria: ['accuracy', 'tone', 'grammar', 'SEO']
    },
    ui: {
      type: 'web',
      template: 'content-review'
    }
  }

  // Opens web interface for human review
  // Reviewer provides feedback and approval
  const result = await reviewer.do(task)

  return result.data as ReviewResult
}

Example: Strategic Decision

// Human function - make strategic decision
async function decidePricingStrategy(
  analysis: MarketAnalysis,
  executive: Human
): Promise<PricingDecision> {
  const task: HumanTask = {
    type: 'decision',
    assignee: executive,
    description: 'Review market analysis and decide pricing strategy',
    data: {
      analysis,
      options: ['premium', 'competitive', 'penetration'],
      context: 'Q1 2024 product launch'
    },
    ui: {
      type: 'web',
      template: 'strategic-decision'
    }
  }

  // Executive reviews analysis in web interface
  // Makes decision with rationale
  const result = await executive.do(task)

  return result.data as PricingDecision
}

Human Task UI Rendering

Human functions render to different interfaces based on context:

// Same task, different UIs
const approvalTask = createHumanTask({
  type: 'approval',
  data: invoice
})

// Render to Slack
renderSlack(approvalTask) // Slack Block Kit with buttons

// Render to Email
renderEmail(approvalTask) // HTML email with action buttons

// Render to Web
renderHTML(approvalTask) // Rich web interface

Agentic vs Human Functions

AspectAgenticHuman
SpeedFastSlow
CostLowHigh
ScaleUnlimitedLimited
JudgmentGoodExcellent
CreativityGoodExcellent
ComplianceNoYes
Best forAutomationCritical decisions

When to Use Human Functions

Use Human functions when:

  • The task requires subjective judgment or creativity
  • Compliance or governance requires human oversight
  • Legal or ethical considerations apply
  • AI cannot reliably handle edge cases
  • Strategic or high-stakes decisions are involved
  • Customer-facing quality is critical

The Task Interface

Agentic and Human functions both work with Tasks through the Worker interface.

Task Structure

interface Task {
  id: string
  type: string
  description: string
  context: any
  assignee?: Agent | Human
  status: 'pending' | 'in_progress' | 'completed' | 'failed'
  result?: Result
}

interface Result {
  success: boolean
  data: any
  error?: string
}

Worker Interface

interface Worker {
  ask(prompt: string): Promise<Response>
  do(task: Task): Promise<Result>
}

Both Agents and Humans implement this interface, making them interchangeable.

Example: Hybrid Workflow

async function processInvoice(invoice: Invoice): Promise<ProcessedInvoice> {
  // 1. Code function - validate
  const validation = await validateInvoice(invoice)
  if (!validation.valid) throw new Error('Invalid invoice')

  // 2. Generative function - extract data
  const extractedData = await extractInvoiceData(invoice.ocrText)

  // 3. Code function - transform
  const enrichedInvoice = await enrichInvoiceData(invoice, extractedData)

  // 4. Agentic or Human function - approve
  const approver = enrichedInvoice.amount > 10000
    ? humanApprover  // Human for high-value
    : agentApprover  // Agent for low-value

  const approval = await approveInvoice(enrichedInvoice, approver)

  if (!approval.approved) {
    throw new Error('Invoice not approved')
  }

  // 5. Code function - process payment
  const payment = await processPayment(enrichedInvoice)

  return { invoice: enrichedInvoice, payment, approval }
}

Function Composition

Functions can be composed into workflows:

Sequential Composition

// Execute functions in sequence
async function processOrder(order: Order): Promise<ProcessedOrder> {
  const validated = await validateOrder(order)        // Code
  const enriched = await enrichOrderData(validated)   // Code
  const fraud = await checkFraud(enriched)            // Generative
  const approved = await approveOrder(enriched)       // Human
  const processed = await processPayment(approved)    // Code
  return processed
}

Parallel Composition

// Execute functions in parallel
async function analyzeCompetitors(competitors: string[]): Promise<Analysis[]> {
  const tasks = competitors.map(competitor =>
    researchCompetitor(competitor, agent)  // Agentic
  )
  return await Promise.all(tasks)
}

Conditional Composition

// Choose function based on conditions
async function handleSupport(ticket: SupportTicket): Promise<Resolution> {
  const category = await classifyTicket(ticket)  // Generative

  if (category === 'billing') {
    return await resolveBilling(ticket)      // Code
  } else if (category === 'technical') {
    return await debugIssue(ticket, agent)   // Agentic
  } else {
    return await escalateToHuman(ticket)     // Human
  }
}

Function Selection Guide

Choose the right function type for your use case:

Decision Tree

Is the logic deterministic?
├─ Yes → Code function (ServiceAccount)
└─ No → Does it need language understanding/generation?
    ├─ Yes → Is it a single-turn generation?
    │   ├─ Yes → Generative function (Model)
    │   └─ No → Agentic function (Agent)
    └─ No → Does it require human judgment?
        ├─ Yes → Human function (Human)
        └─ No → Agentic function (Agent)

Quick Reference

RequirementFunction Type
Rules-based logicCode
Generate textGenerative
Multi-step researchAgentic
Approval/complianceHuman
Data transformationCode
ClassificationGenerative
Complex problem-solvingAgentic
Strategic decisionsHuman
API integrationCode
Content creationGenerative
Autonomous workflowsAgentic
Creative workHuman or Agentic

Performance Characteristics

Different function types have different performance profiles:

Function TypeLatencyCostScaleReliability
Code~msNegligibleUnlimited100%
Generative~seconds$0.001-0.01/callHigh90-95%
Agentic~minutes$0.10-1.00/taskMedium80-90%
Human~hours/days$10-100/taskLimitedVaries

Cost Optimization

// Optimize by using cheaper functions when possible
async function processDocument(doc: Document): Promise<ProcessedDoc> {
  // Try Code function first (free)
  const parsed = await parseDocument(doc)

  // Use Generative only if needed (cheap)
  const classified = await classifyDocument(parsed)

  // Use Agentic for complex analysis (moderate cost)
  if (classified.needsDeepAnalysis) {
    return await analyzeDocument(parsed, agent)
  }

  // Only escalate to Human for exceptions (expensive)
  if (classified.requiresHumanReview) {
    return await reviewDocument(parsed, human)
  }

  return parsed
}

Next Steps

  • Read Actors to understand who executes Functions
  • See Workflows for orchestrating Functions
  • Explore Verbs for naming actions and events

On this page