Motia Icon

Dynamic Workflows: Building a Sentiment Analyzer with Motia

motia workbench for sentiment analysis

In modern application development, workflows are rarely linear. Whether you're building a simple "prompt => response" system or a complex, multi-stage data processing pipeline, you often need your application to make decisions and route data dynamically. This is where the power of event-driven architecture shines, and where the Motia framework provides a clear path forward.

This guide explores how to build a dynamic sentiment analysis application that uses an LLM to determine how to proceed. We'll cover:

  1. The Motia Philosophy: How steps as a core primitive simplify complex architectures.
  2. Building the Workflow: A step-by-step guide to creating the four key components of our application.
  3. Visualizing the Flow: How events chain together to create a cohesive, dynamic system.
  4. Hands-On with the API: How to run and test your new sentiment analyzer.

Let's dive in.


A Step at a Time

motia workbench for sentiment analysis

At the heart of the Motia framework is a simple but powerful idea: the step. A step is a self-contained, independent unit of logic that listens for an event, performs a task, and, optionally, emits a new event. This concept is the core primitive that allows you to break down even the most complex architectures into a series of simple, manageable components.

Instead of a monolithic application where business logic is tightly coupled, Motia encourages a decoupled, event-driven approach. This has several key advantages:

  • Clarity: Each step has a single responsibility, making the application easier to understand and reason about.
  • Scalability: Steps can be scaled independently, so you can allocate resources where they're needed most.
  • Extensibility: Adding new functionality is as simple as creating a new step and subscribing it to an existing event.
  • Resilience: The decoupled nature of steps means that a failure in one part of the system doesn't necessarily bring down the entire application.

In this project, we'll see this philosophy in action as we build a sentiment analyzer with four distinct steps, each with its own clear purpose.


The Anatomy of Our Sentiment Analyzer

Our application will be composed of four steps. Let's explore each one.

analyzeSentimentApi.step.ts
openAiAnalyzeSentiment.step.ts
handlePositive.step.ts
handleNegative.step.ts

This is the entry point to our workflow. It's an API step that listens for POST requests, validates the incoming data, and emits an openai.analyzeSentimentRequest event.

// Receives user text, emits "openai.analyzeSentimentRequest".
import { Handlers } from 'motia'
import { z } from 'zod'
 
export const config = {
  type: 'api',
  name: 'analyzeSentimentApi',
  description: 'Receives user text and emits an event to trigger sentiment analysis.',
  path: '/api/analyze-sentiment',
  method: 'POST',
  emits: ['openai.analyzeSentimentRequest'],
  bodySchema: z.object({
    text: z.string().min(1, 'text is required'),
  }),
  flows: ['sentiment-demo'],
} as const
 
export const handler: Handlers['analyzeSentimentApi'] = async (req, { emit, logger }) => {
  const { text } = req.body
 
  logger.info('[AnalyzeSentimentAPI] Received text', { text })
 
  // Emit an event to call OpenAI
  await emit({
    topic: 'openai.analyzeSentimentRequest',
    data: { text },
  })
 
  // Return right away
  return {
    status: 200,
    body: { status: 'Accepted', message: 'Your text is being analyzed' },
  }
}

Explore the Workbench

You can explore the workflow in the Workbench.

Flow

You can also read your files and watch logs, traces, debug your architecture directly in the Workbench.

Workbench

Trying It Out

Ready to see it in action? Let's get the project running.

Install Dependencies

First, install the necessary npm packages.

npm install

Set Your Environment Variables

You'll need an OpenAI API key for this project. Export it as an environment variable.

export OPENAI_API_KEY="sk-..."

Run the Project

Start the Motia development server.

npm run dev

Test the API

Now you can send requests to your API and see the workflow in action.

Positive Sentiment

curl -X POST http://localhost:3000/api/analyze-sentiment \
  -H "Content-Type: application/json" \
  -d '{"text":"I absolutely love this new device! It is amazing and works perfectly."}'

Check your logs, and you should see the [Positive Responder] has been triggered.

Negative Sentiment

curl -X POST http://localhost:3000/api/analyze-sentiment \
  -H "Content-Type: application/json" \
  -d '{"text":"This is the worst product I have ever used. It broke after one day."}'

This time, the [Negative Responder] will fire.


💻 Dive into the Code

Want to explore the complete implementation? Check out the full source code and additional examples in our GitHub repository:

Explore More Examples

Get hands-on with the complete source code, configuration files, and additional examples to accelerate your learning.


Conclusion: The Power of a Simple Primitive

This sentiment analysis application is a powerful demonstration of the Motia philosophy. By embracing the step as a core primitive, we've turned a potentially complex, branching workflow into a series of simple, understandable, and scalable components.

This is just the beginning. From here, you can extend the application by adding new steps to handle neutral sentiment, send notifications, or store results in a database. The event-driven architecture of Motia makes it easy to add new functionality without disrupting the existing flow.

We encourage you to explore, experiment, and see for yourself how Motia can simplify your most complex backend challenges. Happy coding!

Need help? See our Community Resources for questions, examples, and discussions.

On this page