### Install and Use Motia CLI Source: https://context7.com/voltaire405/motia/llms.txt These bash commands guide you through installing the Motia CLI using Homebrew or a shell script, creating a new Motia project, starting the iii engine, building the project for production, and testing a basic endpoint. ```bash # Install CLI via Homebrew brew tap MotiaDev/tap brew install motia-cli # Or via shell script curl -fsSL https://raw.githubusercontent.com/MotiaDev/motia-cli/main/install.sh | sh # Create new project motia-cli create my-app # Start the iii engine (runs from project directory with iii-config.yaml) iii # Build steps for production motia build # Test endpoint curl http://localhost:3111/hello ``` -------------------------------- ### Run iii-example Source: https://github.com/voltaire405/motia/blob/main/motia-py/README.md Executes a basic example demonstrating the III SDK. It requires installing the SDK in development mode first. ```bash cd iii-example uv pip install -e ../iii python src/main.py ``` -------------------------------- ### Quick Start: Set up Motia Workflow Source: https://github.com/voltaire405/motia/blob/main/motia-py/README.md This snippet details the steps to set up a Motia workflow, including creating and activating a virtual environment, installing dependencies, defining a workflow step, and running Motia. ```bash # 1) Create and activate a virtual environment python -m venv .venv source .venv/bin/activate # 2) Create requirements.txt cat > requirements.txt << 'EOF' motia iii-sdk==0.2.0 EOF # 3) Install dependencies pip install -r requirements.txt # 4) Create steps folder and a *_steps.py file mkdir -p steps cat > steps/single_event_steps.py << 'EOF' from typing import Any from motia import FlowContext, queue config = { "name": "SingleEventTrigger", "description": "Test single event trigger", "triggers": [queue("test.event")], "enqueues": ["test.processed"], } async def handler(input: Any, ctx: FlowContext[Any]) -> None: ctx.logger.info("Single event trigger fired", {"data": input}) EOF # 5) Run Motia (inside the active venv) motia run ``` -------------------------------- ### Install Project Dependencies with uv Source: https://github.com/voltaire405/motia/blob/main/motia-py/playground/README.md Installs all project dependencies, including extras, using the uv sync command. This command reads the project configuration (e.g., pyproject.toml) to fetch and install necessary packages. ```bash uv sync --all-extras ``` -------------------------------- ### CLI Commands and Project Setup Source: https://context7.com/voltaire405/motia/llms.txt Instructions for installing and using the Motia CLI to create, build, and run Motia projects. ```APIDOC ## Motia CLI Commands ### Description Manage Motia projects using the command-line interface. The `iii` engine handles runtime modules. ### Installation **Via Homebrew:** ```bash brew tap MotiaDev/tap brew install motia-cli ``` **Via Shell Script:** ```bash curl -fsSL https://raw.githubusercontent.com/MotiaDev/motia-cli/main/install.sh | sh ``` ### Project Management **Create a new project:** ```bash motia-cli create my-app ``` **Start the iii engine:** (Run from the project directory with `iii-config.yaml`) ```bash iii ``` **Build steps for production:** ```bash motia build ``` ### Testing **Test an endpoint (example):** ```bash curl http://localhost:3111/hello ``` ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/voltaire405/motia/blob/main/motia-py/playground/README.md Installs the uv package manager using a curl command. This is a prerequisite for managing project dependencies and running the Motia example. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Runtime Support Examples Source: https://github.com/voltaire405/motia/blob/main/MIGRATION_GUIDE.md Examples of how to run Motia in development and production using Node.js or Bun. ```APIDOC ## Runtime Support Motia supports both Node.js and Bun runtimes. ### Node.js - **Development Command:** `npx motia dev` - **Production Command:** `node dist/index-production.js` ### Bun - **Development Command:** `bun run dist/index-dev.js` - **Production Command:** `bun run --enable-source-maps dist/index-production.js` ``` -------------------------------- ### Run Motia Example with Todo Application Source: https://github.com/voltaire405/motia/blob/main/motia-py/README.md Demonstrates the Motia framework using a Todo application example. It requires installing both 'iii' and 'motia' in development mode. ```bash cd motia-example uv pip install -e ../iii -e ../motia motia run --dir steps ``` -------------------------------- ### Install Motia CLI using Shell Script Source: https://github.com/voltaire405/motia/blob/main/README.md This command installs the Motia CLI by downloading and executing an installation script. It's a convenient alternative if you don't use Homebrew. ```bash curl -fsSL https://raw.githubusercontent.com/MotiaDev/motia-cli/main/install.sh | sh ``` -------------------------------- ### Run Motia Example Workflows Source: https://github.com/voltaire405/motia/blob/main/motia-py/playground/README.md Executes the Motia example workflows located in the 'steps' directory. This command initiates the Motia runtime to process defined workflows and triggers. ```bash uv run motia run --dir steps ``` -------------------------------- ### Install Dependencies and Build Packages (pnpm) Source: https://github.com/voltaire405/motia/blob/main/motia-js/MONOREPO-README.md Installs project dependencies using pnpm and then builds all packages within the monorepo. This is a standard setup procedure for the Motia project. ```bash cd motia-js pnpm install pnpm build ``` -------------------------------- ### Install Motia Framework Source: https://github.com/voltaire405/motia/blob/main/motia-py/packages/motia/README.md Installs the Motia framework using uv pip. This is the primary command for setting up the framework in your Python environment. ```bash uv pip install motia ``` -------------------------------- ### Install Motia CLI using Homebrew Source: https://github.com/voltaire405/motia/blob/main/README.md This bash command installs the Motia CLI using the Homebrew package manager. Ensure Homebrew is installed on your system before running this command. ```bash brew tap MotiaDev/tap brew install motia-cli ``` -------------------------------- ### Motia Step Migration Example - Before Source: https://github.com/voltaire405/motia/blob/main/MIGRATION_GUIDE.md Illustrates the 'before' state of a Python step migration, showing how streams were accessed via `ctx.streams` and using Pydantic for input validation. ```python import chess import chess.engine import os from pydantic import BaseModel, Field class EvaluatePlayerMoveInput(BaseModel): fenBefore: str = Field(description="The FEN of the game before the move") fenAfter: str = Field(description="The FEN of the game after the move") gameId: str = Field(description="The ID of the game") moveId: str = Field(description="The ID of the move") player: str = Field(description="The player who made the move") config = { "type": "event", "name": "EvaluatePlayerMove", "description": "Evaluates the move picked by a player", "subscribes": ["evaluate-player-move"], "emits": [], "flows": ["chess"], "input": EvaluatePlayerMoveInput.model_json_schema(), "includeFiles": ["../../lib/stockfish"] } async def handler(input: EvaluatePlayerMoveInput, ctx): logger = ctx.logger fen_before = input.get("fenBefore") game_id = input.get("gameId") move_id = input.get("moveId") # ... (business logic omitted for brevity) ... # Streams accessed via ctx.streams move_stream = await ctx.streams.chessGameMove.get(game_id, move_id) move_stream["evaluation"] = evaluation await ctx.streams.chessGameMove.set(game_id, move_id, move_stream) ``` -------------------------------- ### Start Motia Development Server Source: https://github.com/voltaire405/motia/blob/main/motia-js/README.md This command starts the Motia development server, typically accessible at http://localhost:3000. It enables features like REST APIs with validation, a visual debugger, multi-language support, and an event-driven architecture with zero configuration. ```bash npm run dev # ➜ http://localhost:3000 ``` -------------------------------- ### Motia Step Migration Example - After Source: https://github.com/voltaire405/motia/blob/main/MIGRATION_GUIDE.md Shows the 'after' state of a Python step migration, demonstrating the use of module-level `Stream` objects for accessing streams and Pydantic for input validation with type hints. ```python import os from typing import Any, Literal import chess import chess.engine from motia import FlowContext, Stream, queue from pydantic import BaseModel, Field # Stream declared at module level chess_game_move_stream: Stream[dict[str, Any]] = Stream("chessGameMove") class EvaluatePlayerMoveInput(BaseModel): fenBefore: str = Field(description="The FEN of the game before the move") fenAfter: str = Field(description="The FEN of the game after the move") gameId: str = Field(description="The ID of the game") moveId: str = Field(description="The ID of the move") player: Literal["white", "black"] = Field(description="The player who made the move") config = { "name": "EvaluatePlayerMove", "description": "Evaluates the move picked by a player", "flows": ["chess"], "triggers": [queue("evaluate-player-move", input=EvaluatePlayerMoveInput.model_json_schema())], "enqueues": [], "includeFiles": ["../../lib/stockfish"], } async def handler(input_data: dict[str, Any], ctx: FlowContext[Any]) -> None: logger = ctx.logger payload = EvaluatePlayerMoveInput.model_validate(input_data) # ... (business logic omitted for brevity) ... # Stream accessed via module-level Stream object move_stream = await chess_game_move_stream.get(payload.gameId, payload.moveId) move_stream["evaluation"] = evaluation await chess_game_move_stream.set(payload.gameId, payload.moveId, move_stream) ``` -------------------------------- ### Example Usage of Stream Client (TypeScript) Source: https://github.com/voltaire405/motia/blob/main/motia-js/packages/stream-client-node/README.md Demonstrates a complete example of creating a stream connection, subscribing to both item and group streams, and setting up change listeners. ```typescript import { Stream } from '@motiadev/stream-client-node' const token = process.env.MOTIA_STREAM_TOKEN const protocols = token ? ['Authorization', token] : undefined const stream = new Stream('wss://example.com', { protocols }) const userSub = stream.subscribeItem<{ id: string; name: string }>('users', 'user-1') userSub.addChangeListener((user) => { // React to user changes }) const groupSub = stream.subscribeGroup<{ id: string; name: string }>('users', 'group-1') groupSub.addChangeListener((users) => { // React to group changes }) ``` -------------------------------- ### Install @motiadev/stream-client-browser Source: https://github.com/voltaire405/motia/blob/main/motia-js/packages/stream-client-browser/README.md Installs the Motia Stream Client Browser package using npm. This is the first step to integrate real-time data streaming into your web application. ```bash npm install @motiadev/stream-client-browser ``` -------------------------------- ### Install @motiadev/stream-client-node Source: https://github.com/voltaire405/motia/blob/main/motia-js/packages/stream-client-node/README.md Installs the Motia Stream Client Node package using npm. This is the first step to integrate real-time data streaming into your Node.js application. ```bash npm install @motiadev/stream-client-node ``` -------------------------------- ### Start the Motia iii Engine Source: https://github.com/voltaire405/motia/blob/main/README.md This command starts the Motia iii engine, which is responsible for running your Motia project. You need to provide the path to your configuration file (e.g., 'iii-config.yaml') generated during project creation. ```bash iii -c iii-config.yaml ``` -------------------------------- ### HTTP Trigger Example (Before) Source: https://github.com/voltaire405/motia/blob/main/MIGRATION_GUIDE.md Illustrates the 'API step' configuration in the previous version of Motia, highlighting the 'type: api' and separate config types. ```APIDOC ## HTTP Triggers (Before - Old Version) This example shows the configuration for an 'API step' in the older version of Motia. ### Request Example ```typescript import { ApiRouteConfig, Handlers } from 'motia' import { z } from 'zod' const bodySchema = z.object({ name: z.string(), email: z.string(), }) export const config: ApiRouteConfig = { type: 'api', name: 'CreateUser', description: 'Create a new user', method: 'POST', path: '/users', bodySchema, responseSchema: { 200: z.object({ id: z.string() }), 400: z.object({ error: z.string() }), }, emits: ['user-created'], flows: ['User Flow'], middleware: [coreMiddleware, validateBearerToken], } export const handler: Handlers['CreateUser'] = async (req, { emit, logger }) => { const { name, email } = req.body logger.info('Creating user', { name, email }) await emit({ topic: 'user-created', data: { name, email }, }) return { status: 200, body: { id: 'user-123' } } } ``` ``` -------------------------------- ### Motia CLI: Start Engine Command Source: https://github.com/voltaire405/motia/blob/main/motia-js/packages/motia/README.md The `iii` command starts the Motia engine. This engine manages all modules, the SDK process, and enables hot-reloading for development. ```bash iii ``` -------------------------------- ### Motia Development and Production Commands (Bun) Source: https://github.com/voltaire405/motia/blob/main/motia-js/packages/motia/README.md Examples of running Motia projects using Bun. `bun run dist/index-dev.js` is for development, and `bun run --enable-source-maps dist/index-production.js` is for production builds, including source map support. ```bash # Bun # Dev Command Example bun run dist/index-dev.js # Production Example bun run --enable-source-maps dist/index-production.js ``` -------------------------------- ### Installing NPM Packages with Specific Tags Source: https://github.com/voltaire405/motia/blob/main/contributors/architecture/deploy/DEPLOY_FLOW.md These commands show how to install NPM packages using specific tags. The 'pre-release' tag is used during E2E testing, while the default 'latest' tag is used for stable releases after successful testing. ```bash # During E2E tests npm install motia@1.0.0 --tag pre-release # After successful tests npm install motia@1.0.0 # latest tag (default) ``` -------------------------------- ### Install Motia Dev Dependencies Source: https://github.com/voltaire405/motia/blob/main/motia-py/packages/motia/README.md Installs development dependencies for the Motia project, including extras, using uv sync. This is typically done within the project's root directory. ```bash cd motia && uv sync --all-extras ``` -------------------------------- ### Example Usage of Stream Client in TypeScript Source: https://github.com/voltaire405/motia/blob/main/motia-js/packages/stream-client-browser/README.md Demonstrates a complete example of setting up a stream connection, subscribing to an item and a group, and adding change listeners. This provides a practical overview of the package's functionality. ```typescript import { Stream } from '@motiadev/stream-client-browser' const token = window.sessionStorage.getItem('motia.streamToken') ?? undefined const protocols = token ? ['Authorization', token] : undefined const stream = new Stream('wss://example.com', { protocols }) const userSub = stream.subscribeItem<{ id: string; name: string }>('users', 'user-1') userSub.addChangeListener((user) => { // React to user changes }) const groupSub = stream.subscribeGroup<{ id: string; name: string }>('users', 'group-1') groupSub.addChangeListener((users) => { // React to group changes }) ``` -------------------------------- ### Motia Development and Production Commands (Node.js) Source: https://github.com/voltaire405/motia/blob/main/motia-js/packages/motia/README.md Examples of running Motia projects using Node.js. `npx motia dev` is used for development with hot-reloading, while `node dist/index-production.js` is for deploying the production build. ```bash # Node.js # Dev Command Example npx motia dev # Production Example node dist/index-production.js ``` -------------------------------- ### Migrating Python Dependencies from requirements.txt to pyproject.toml Source: https://github.com/voltaire405/motia/blob/main/MIGRATION_GUIDE.md This example shows how to migrate existing dependencies from a `requirements.txt` file into the `dependencies` list within a `pyproject.toml` file. This consolidates dependency management for Python projects using tools like `uv`. ```toml dependencies = [ "motia[otel]==1.0.0rc17", "iii-sdk==0.2.0", "pydantic>=2.0", # Your existing dependencies: "openai>=1.40.0", "httpx>=0.27.0", ] ``` -------------------------------- ### Testing HTTP Trigger with cURL Source: https://context7.com/voltaire405/motia/llms.txt Provides example cURL commands to test the HTTP trigger defined in the `GetUsers` step. It shows how to test with path parameters and query parameters. ```bash # Test with path parameter curl http://localhost:3111/users/user-123 # Test with query parameters curl "http://localhost:3111/greet?name=World" ``` -------------------------------- ### Multi-Trigger Step Example Source: https://context7.com/voltaire405/motia/llms.txt Demonstrates a single Motia step that can be triggered via HTTP, a message queue, or a cron schedule, using `ctx.match()` to dispatch to specific handlers. ```APIDOC ## POST /orders ### Description This endpoint allows creating a new order via an HTTP POST request. It accepts order details in the request body and returns an order ID and status. ### Method POST ### Endpoint /orders ### Parameters #### Query Parameters None #### Request Body - **productId** (string) - Required - The ID of the product to order. - **quantity** (number) - Required - The number of units to order. - **customerId** (string) - Required - The ID of the customer placing the order. ### Request Example ```json { "productId": "prod-123", "quantity": 2, "customerId": "cust-abc" } ``` ### Response #### Success Response (200) - **orderId** (string) - The unique identifier for the created order. - **status** (string) - The current status of the order processing. #### Response Example ```json { "orderId": "order-1678886400000", "status": "processing" } ``` ## Queue Trigger: order.submitted ### Description Processes orders submitted to the 'order.submitted' queue. It logs the order details and updates the state. ### Method Queue Consumer ### Endpoint Topic: `order.submitted` ### Parameters #### Input Schema - **productId** (string) - Required - The ID of the product. - **quantity** (number) - Required - The number of units. - **customerId** (string) - Required - The ID of the customer. ### Response No direct response, but enqueues 'order.processed'. ## Cron Trigger: Every 5 minutes ### Description This cron trigger executes a batch process every 5 minutes to handle pending orders. ### Method Cron Schedule ### Endpoint Expression: `0 */5 * * * *` ### Parameters None ### Response No direct response, but enqueues 'order.processed' for each pending order found. ``` -------------------------------- ### Configure Snap CLI Adapters Source: https://github.com/voltaire405/motia/blob/main/contributors/rfc/2025-10-15-adapter-pattern-horizontal-scaling.md Demonstrates how to configure various adapters for the Snap CLI in `packages/snap/src/dev.ts` and `packages/snap/src/start.ts`. It shows the loading of Motia configuration and the instantiation of state, event, stream, and cron adapters, with defaults provided if not explicitly configured. ```typescript const appConfig: Config = await loadMotiaConfig(baseDir) const state = appConfig.adapters?.state || createStateAdapter({ adapter: 'default', filePath: path.join(baseDir, motiaFileStoragePath), }) const eventManager = appConfig.adapters?.events || createEventManager() const streamAdapterFactory = appConfig.adapters?.streams ? () => appConfig.adapters!.streams! : undefined const cronAdapter = appConfig.adapters?.cron ``` -------------------------------- ### Bootstrap a New Motia Project via CLI Source: https://github.com/voltaire405/motia/blob/main/motia-js/README.md This command initializes a new Motia project using the Motia CLI. It prompts the user for template selection, project name, and programming language, simplifying the setup process for new Motia applications. ```bash npx motia@latest create # runs the interactive terminal ``` -------------------------------- ### HTTP Trigger Definition with Helper in TypeScript Source: https://context7.com/voltaire405/motia/llms.txt Illustrates using the `http()` helper function for defining HTTP triggers in Motia. This example sets up a GET request to `/users/:userId` with response schemas for success (200) and not found (404) cases. The handler fetches user data from state. ```typescript // steps/get-users.step.ts import { type Handlers, http, type StepConfig } from 'motia' import { z } from 'zod' export const config = { name: 'GetUsers', flows: ['user-management'], triggers: [ http('GET', '/users/:userId', { responseSchema: { 200: z.object({ id: z.string(), name: z.string(), email: z.string() }), 404: z.object({ error: z.string() }), }, }), ], enqueues: [], } as const satisfies StepConfig export const handler: Handlers = async ({ request }, { state, logger }) => { const { userId } = request.pathParams logger.info('Fetching user', { userId }) const user = await state.get<{ id: string; name: string; email: string }>('users', userId) if (!user) { return { status: 404, body: { error: 'User not found' } } } return { status: 200, body: user } } ``` -------------------------------- ### Motia Configuration with Adapters (TypeScript) Source: https://github.com/voltaire405/motia/blob/main/contributors/rfc/2025-10-15-adapter-pattern-horizontal-scaling.md Demonstrates how to configure Motia with various adapters for state, events, and cron jobs. It shows importing adapter classes and instantiating them with specific connection details and options. This example highlights the flexibility in choosing different backend services like Redis and RabbitMQ. ```typescript import { config } from '@motiadev/core' import { RedisStateAdapter } from '@motiadev/adapter-redis-state' import { RedisCronAdapter } from '@motiadev/adapter-redis-cron' import { RabbitMQEventAdapter } from '@motiadev/adapter-rabbitmq-events' export default config({ adapters: { state: new RedisStateAdapter({ host: process.env.REDIS_HOST || 'localhost', port: parseInt(process.env.REDIS_PORT || '6379'), password: process.env.REDIS_PASSWORD, }), events: new RabbitMQEventAdapter({ url: process.env.RABBITMQ_URL || 'amqp://localhost', exchangeName: 'motia.events', exchangeType: 'topic', }), cron: new RedisCronAdapter({ host: process.env.REDIS_HOST || 'localhost', port: parseInt(process.env.REDIS_PORT || '6379'), lockTTL: 300000, }), }, }) ``` -------------------------------- ### Install All Packages in Development Mode Source: https://github.com/voltaire405/motia/blob/main/motia-py/README.md Installs both the 'iii' SDK and the 'motia' framework in editable development mode. ```bash uv pip install -e iii -e motia ``` -------------------------------- ### Create a New Motia Project Source: https://github.com/voltaire405/motia/blob/main/README.md This command initializes a new Motia project. The CLI will prompt you to choose a language and template, and it will automatically set up the necessary configuration files, including 'iii-config.yaml'. ```bash motia-cli create my-app ``` -------------------------------- ### Install Motia Framework in Development Mode Source: https://github.com/voltaire405/motia/blob/main/motia-py/README.md Installs the Motia framework package in editable mode, enabling direct code modifications. ```bash cd motia uv pip install -e . ``` -------------------------------- ### Motia Configuration with Redis and RabbitMQ Adapters Source: https://github.com/voltaire405/motia/blob/main/contributors/rfc/2025-10-15-adapter-pattern-horizontal-scaling.md Example configuration file for Motia, demonstrating how to set up state, streams, events, and cron adapters. It utilizes Redis for state and streams, RabbitMQ for events, and Redis again for cron job locking. Environment variables are used for connection details. ```typescript import { config, type Config, type Motia } from '@motiadev/core' import { RedisStateAdapter } from '@motiadev/adapter-redis-state' import { RedisStreamAdapter } from '@motiadev/adapter-redis-streams' import { RabbitMQEventAdapter } from '@motiadev/adapter-rabbitmq-events' import { RedisCronAdapter } from '@motiadev/adapter-redis-cron' export default config({ adapters: { state: new RedisStateAdapter({ host: process.env.REDIS_HOST || 'localhost', port: parseInt(process.env.REDIS_PORT || '6379'), password: process.env.REDIS_PASSWORD, keyPrefix: 'motia:state:', ttl: 3600, }), streams: new RedisStreamAdapter({ host: process.env.REDIS_HOST || 'localhost', port: parseInt(process.env.REDIS_PORT || '6379'), password: process.env.REDIS_PASSWORD, keyPrefix: 'motia:stream:', }), events: new RabbitMQEventAdapter({ url: process.env.RABBITMQ_URL || 'amqp://localhost', exchangeName: 'motia.events', exchangeType: 'topic', durable: true, }), cron: new RedisCronAdapter({ host: process.env.REDIS_HOST || 'localhost', port: parseInt(process.env.REDIS_PORT || '6379'), password: process.env.REDIS_PASSWORD, keyPrefix: 'motia:cron:', lockTTL: 300000, instanceId: process.env.INSTANCE_ID || undefined, }), }, plugins: [ ], }) ``` -------------------------------- ### Install iii SDK in Development Mode Source: https://github.com/voltaire405/motia/blob/main/motia-py/README.md Installs the core III SDK package in editable mode, allowing for direct code changes to be reflected without reinstallation. ```bash cd iii uv pip install -e . ``` -------------------------------- ### Python Project Setup with pyproject.toml Source: https://github.com/voltaire405/motia/blob/main/MIGRATION_GUIDE.md This TOML configuration sets up a Python project using `pyproject.toml`, specifying project metadata, dependencies including Motia and other SDKs, and optional development dependencies. It also configures the `uv` tool for package management. ```toml [project] name = "my-motia-project" version = "0.1.0" requires-python = ">=3.10" dependencies = [ "motia[otel]==1.0.0rc17", "iii-sdk==0.2.0", "pydantic>=2.0", ] [project.optional-dependencies] dev = ["pytest>=8.0.0"] [tool.uv] package = false ``` -------------------------------- ### Motia CLI: Create Project Command Source: https://github.com/voltaire405/motia/blob/main/motia-js/packages/motia/README.md The `npx motia create` command initializes a new Motia project. It supports specifying a project name/directory and choosing a template. Optional flags like `--cursor` can be used for IDE integration. ```bash npx motia create [options] # options # [project name] (optional): Project name/folder; use . or ./ to use current directory # -t, --template