Motia Examples

repository·main·Indexed 19 days ago

https://github.com/motiadev/motia-examples

A collection of 60+ practical examples for the Motia backend framework, demonstrating event-driven, real-time, and AI-powered applications. Featured examples include the Room-Renovate AI Home Renovation Planner (v1.0.0), which uses a multi-agent workflow and Google Gemini for design planning and rendering, and a Competitor Price Scraper implementing a RAG system with OpenAI, Anthropic Claude, and Supabase.

Tokens
143.6K
Snippets
393
Records
623
Agent score
65%

What's inside motia-examples

  1. Overview of Motia Examples

    main
    This repository contains over 60 examples for Motia, a modern backend framework designed for building event-driven applications with built-in observability and state management. The examples are organized by complexity level, ranging from beginner to expert, covering use cases like AI agents, RAG (Retrieval-Augmented Generation), real-time streaming, and third-party integrations.
  2. Overview of Advanced Use Case Examples

    main

    This collection contains expert-level implementations of Motia's event-driven architecture. Key examples include:

    • ai-room-renovate: A full-stack computer vision app for interior design.
    • competitor-price-scrapper: An enterprise-grade scraping system with proxy rotation and anti-bot evasion.
    • ecommerce-shopify-whatsapp: A conversational commerce automation tool integrating Shopify and WhatsApp.
    • meeting-transcription: A multi-stage audio processing pipeline for speech-to-text and insights.
    • public-form-auto-triage: An intelligent routing system for classifying and assigning form submissions.
    • vision-example: A comprehensive suite for object detection, OCR, and scene understanding.
    • wake-surf-club: A full-stack booking system with SMS (Twilio) and calendar integration.
  3. Explore Motia AI Agent Categories

    main

    Motia provides three main categories of AI agent examples to help you progress from simple to complex implementations:

    • Chat Agents: Focused on conversational AI interfaces. These include features like memory (stateful conversations), context management, and real-time streaming via Server-Sent Events (SSE).
    • Specialized Agents: Domain-specific agents designed for single tasks. Examples include code reviewers, research assistants (using the ReAct pattern), content moderators, and financial analysts.
    • Multi-Agent Systems: Complex orchestrations where multiple specialized agents work together to solve high-level problems, such as generating full-stack applications or planning travel itineraries.
  4. Explore Monitoring and Alerting examples

    main

    The repository provides several intermediate-level examples for different monitoring domains:

    • ai-aqi-alert-system: Monitors Air Quality Index (AQI) via API and sends email alerts when levels are unhealthy. Uses Cron Steps and location-based monitoring.
    • ai-morgage-alert-system: Tracks mortgage rates across multiple lenders and alerts users to refinancing opportunities using trend analysis.
    • car-alert: Monitors vehicle health and maintenance schedules, supporting mileage monitoring and service reminders.
  5. Explore Foundational Motia Patterns

    main

    The foundational directory contains intermediate examples for building production-ready applications. These examples are categorized into four main areas:

    • API Patterns: Building robust APIs with file processing, data transformation, and analysis (e.g., todo-app, image-resizer, sentimental-analysis).
    • Workflow Patterns: Mastering essential production workflows like human-in-the-loop processes (e.g., human-in-the-loop).
    • Automation: Content processing, messaging, and scheduled tasks using Cron Steps (e.g., blog-to-tweet, telegram-gmail-automation, currency-rate-monitor).
    • Infrastructure: Containerization, parallel processing, and monitoring (e.g., motia-docker, motia-parallel-execution, motia-uptime-monitor).
  6. Core Motia Concepts covered in examples

    main

    The Motia examples collection is designed to teach the following core architectural concepts:

    • API Steps: Creating and managing API endpoints.
    • Event Steps: Processing background events and building event-driven architectures.
    • Middleware: Implementing authentication (e.g., JWT), validation, and request/response processing.
    • Queues: Managing job queues, asynchronous task processing, and retry mechanisms.
    • Real-time Streaming: Building interactive applications using Server-Sent Events (SSE) and WebSockets (Motia Streams) for features like real-time updates and collaborative cursor sharing.
  7. Explore Motia Examples by Category

    main

    The motia-examples repository is organized into several functional categories to help you find specific implementation patterns. You can browse examples based on your current development goal:

    • Getting Started: Foundational patterns and quickstarts.
    • Foundational: Core API patterns, middleware, and state management.
    • AI Agents: Multi-agent systems and chat agents.
    • RAG and Search: Retrieval-Augmented Generation and search applications.
    • Integrations: Connecting with third-party services like Stripe.
    • Monitoring and Alerts: Observability and notification workflows.
    • Content and Marketing: Automation for email and content.
    • Advanced Use Cases: Complex workflows like web scraping.
  8. Understand the research context for Mem0 and RAG applications

    main

    The research-report.md file provides a curated bibliography of academic papers relevant to building memory-centric AI applications like Mem0. It categorizes research into several key areas:

    1. Retrieval-Augmented Generation (RAG): Foundational techniques for combining parametric memory (LLM weights) with non-parametric memory (retrieved documents).
    2. External Memory Mechanisms: Approaches like Memorizing Transformers that use approximate nearest neighbor (ANN) search over past key-value pairs to extend context.
    3. Architectural Recurrence: Methods like Transformer-XL and Recurrent Memory Transformer (RMT) that use segment-level recurrence or special memory tokens to pass information across long sequences.
    4. Memory Management Systems: Concepts like MemGPT which treat LLMs like operating systems with tiered memory (main context vs. external context) managed via function calls.
    5. Long-Context Limitations: Research such as 'Lost in the Middle' which identifies how LLM performance degrades when relevant information is placed in the middle of a long context window.
  9. Available Content and Marketing Examples

    main

    The Content and Marketing directory contains three primary specialized examples:

    • email-marketing-automation (Advanced): A complete platform for email campaigns, audience segmentation, drip sequences, A/B testing, and analytics.
    • ugc-workflow (Intermediate): A system for managing User-Generated Content (UGC) featuring AI moderation, approval workflows, and multi-channel publishing.
    • conversation-analyzer-with-vision (Advanced): A multi-modal analysis tool that uses Vision AI to extract insights, sentiment, and topics from both text and images.
  10. Research Paper Analysis Report: RAG and Long-Term Memory

    main

    This document is a research report generated by a research assistant application. It analyzes various academic papers related to Retrieval-Augmented Generation (RAG) and long-term memory mechanisms for Large Language Models (LLMs), specifically in the context of the Mem0 framework.

    Key research areas covered include:

    • Retrieval-Augmented Generation (RAG): Combining parametric memory (LLM weights) with non-parametric memory (external document indices).
    • External Memory Augmentation: Using kNN (k-Nearest Neighbor) search to access external key-value stores (e.g., Memorizing Transformers).
    • Architectural Extensions: Using recurrence (e.g., Transformer-XL) or dedicated memory tokens (e.g., Recurrent Memory Transformer) to extend context windows.
    • Long-Term Memory Management: Frameworks for memory writing, reading, and reflection to maintain consistency in long-running dialogues (e.g., MemoryBank).
  11. How to pass context from Middlewares to Handlers in Motia

    main

    In Motia, you can avoid redundant token verification by using the Middleware Context Passing pattern. Instead of verifying a JWT in every handler, follow this workflow:

    1. Middleware: Verifies the JWT once and attaches the decoded claims (e.g., userId, role) directly to the request object.
    2. TypeScript Module Augmentation: Use declare module 'motia' to extend the ApiRequest interface so that your custom properties (like tokenInfo) are type-safe throughout your application.
    3. Handlers: Access the attached claims directly from the req object without re-verifying the token.

    This pattern ensures efficiency, reduces code duplication, and maintains consistency across your API.

    // Example of the pattern in a handler
    export const handler: Handlers['Profile'] = async (req, { logger }) => {
      // Access tokenInfo directly - no re-verification needed!
      const { tokenInfo } = req
      
      logger.info('Fetching profile', {
        userId: tokenInfo!.userId,
        role: tokenInfo!.role
      })
      
      return {
        status: 200,
        body: { userId: tokenInfo!.userId }
      }
    }
  12. How parallel execution works in Motia

    main

    Motia achieves parallel execution through an event-driven pub/sub architecture. Instead of manual thread management, you define steps that subscribe to the same topic.

    1. API Trigger: An ApiRouteConfig step receives input and emits a specific topic (e.g., ['parallel-processing']).
    2. Parallel Processors: Multiple steps define an EventConfig where the subscribes array contains that same topic. Because they all listen to the same broadcast, they execute concurrently.
    3. Aggregation: A final step (the aggregator) listens for results from all processors and uses logic to detect when all expected keys have arrived to merge them into a final state.

    Example API Trigger Configuration:

    export const config: ApiRouteConfig = {
      type: 'api',
      method: 'POST',
      path: '/process-data',
      emits: ['parallel-processing'],
      bodySchema: z.object({
        text: z.string().min(1, 'Text content is required'),
        id: z.string().optional()
      })
    }

    Example Parallel Processor Configuration:

    export const config: EventConfig = {
      type: 'event',
      subscribes: ['parallel-processing'], // Same topic = parallel execution
      emits: ['processing-result'],
      input: z.object({
        text: z.string(),
        processingId: z.string()
      })
    }
    export const config: ApiRouteConfig = {
      type: 'api',
      method: 'POST',
      path: '/process-data',
      emits: ['parallel-processing'],
      bodySchema: z.object({
        text: z.string().min(1, 'Text content is required'),
        id: z.string().optional()
      })
    }
    
    export const config: EventConfig = {
      type: 'event',
      subscribes: ['parallel-processing'],
      emits: ['processing-result'],
      input: z.object({
        text: z.string(),
        processingId: z.string()
      })
    }