Quick Start (5 min): Killing the Runaway Agent Loop
A rogue while loop spins unchecked at 2:14 AM. Before anyone notices, an autonomous agent script burns through $380 in OpenAI credits while hallucinating invalid tool parameters. Most engineers deploying LLM chains encounter this failure mode sooner or later. Sequential scripts break down when production traffic throws unpredictable edge cases at them. The solution is ditching fragile script loops for deterministic, event-driven state machines.
LlamaIndex Workflows replace rigid chains with discrete, typed events emitted across asynchronous steps. You get explicit state boundaries, isolated retries, and total observability over execution flow.
Start by installing the core packages:
pip install llama-index-core llama-index-llms-openai
Export your API credentials:
export OPENAI_API_KEY="sk-proj-your-api-key-here"
Next, assemble a minimal two-step workflow. Step one accepts raw user input and fires a validated event. Step two captures that specific event and completes the run:
import asyncio
from llama_index.core.workflow import (
Workflow,
Event,
StartEvent,
StopEvent,
step,
)
# Define explicit event boundaries
class QueryProcessedEvent(Event):
payload: str
class FastAgentWorkflow(Workflow):
@step
async def process_input(self, ev: StartEvent) -> QueryProcessedEvent:
raw_query = ev.get("query", "")
sanitized = raw_query.strip().lower()
# Dispatch to the next discrete handler
return QueryProcessedEvent(payload=sanitized)
@step
async def generate_response(self, ev: QueryProcessedEvent) -> StopEvent:
result = f"Processed safely: {ev.payload}"
return StopEvent(result=result)
async def main():
wf = FastAgentWorkflow(timeout=10, verbose=False)
result = await wf.run(query=" Production Outage Ticket #404 ")
print(result)
if __name__ == "__main__":
asyncio.run(main())
Run the script. You will notice that process_input never directly calls generate_response. Instead, the runtime inspects the Python type annotations, identifies that generate_response consumes QueryProcessedEvent, and triggers it the moment that event fires.
Deep Dive: Architecture of Event-Driven AI Agents
Traditional DAG runtimes like LangChain chains force execution down fixed paths. That works well for simple retrieval pipelines. It fails during complex workflows like multi-table schema migrations or Tier-2 support triage. In those scenarios, user inputs are noisy and external APIs throw 504 gateway timeouts at random.
Production agents require state recovery. If step four crashes, you should not re-run steps one through three and double-bill your tokens.
Core Components: Events, Steps, and Context
LlamaIndex Workflows operate on three building blocks:
- Events: Subclasses of
Eventcarrying Pydantic-validated payloads. Every piece of data passed between steps is strictly typed. That eliminates schema drift across your pipeline. - Step Handlers: Async functions decorated with
@step. A step executes only when its subscribed event types arrive in the queue. - Workflow Context: An isolated state container passed into steps via
ctx: Context. It stores intermediate results without leaking variables into global scope.
Controlling Complex State Machines
Standard loop-based agents store state in transient local variables. If an HTTP request hangs, that state vanishes into thin air. Event-driven architectures replace volatile local variables with explicit transitions. Each step returns a specific event type that directs traffic down the right execution path.
Here is an automated triage workflow routing customer issues based on severity:
from llama_index.core.workflow import Workflow, Event, StartEvent, StopEvent, step
from llama_index.llms.openai import OpenAI
class CriticalAlertEvent(Event):
summary: str
class StandardTicketEvent(Event):
summary: str
class TriageWorkflow(Workflow):
llm = OpenAI(model="gpt-4o-mini")
@step
async def classify_ticket(self, ev: StartEvent) -> CriticalAlertEvent | StandardTicketEvent:
text = ev.get("ticket_text", "")
prompt = f"Classify as CRITICAL or STANDARD. Return only the label: {text}"
response = await self.llm.acomplete(prompt)
if "CRITICAL" in response.text.upper():
return CriticalAlertEvent(summary=text)
return StandardTicketEvent(summary=text)
@step
async def handle_critical(self, ev: CriticalAlertEvent) -> StopEvent:
# Instant on-call paging via PagerDuty or Opsgenie webhook
return StopEvent(result=f"[PAGED ON-CALL] Severity-1: {ev.summary}")
@step
async def handle_standard(self, ev: StandardTicketEvent) -> StopEvent:
# Route to Jira backlog with standard 24h SLA
return StopEvent(result=f"[LOGGED TO JIRA] Backlog item: {ev.summary}")
Routing happens deterministically. If the classifier returns invalid tokens or the model hallucinates an unknown label, the workflow catches it right at step one. You never trigger downstream side effects with bad input.
Advanced Usage: Dynamic Fan-Out and Multi-Event Joins
Allowing an LLM to trigger payment refunds or modify database tables without guardrails invites disaster. Robust agent pipelines require parallel specialized analysis followed by synchronized barrier checks.
Aggregating Fan-Out Workflows
Consider an automated security triage system. When an alert arrives, the system spins up two parallel tasks: one auditing IAM access logs and another scanning VPC flow records. Both analyses must finish before creating a remediation ticket.
Use ctx.send_event() to fire multiple parallel events, and use ctx.collect_events() to synchronize their completion:
from llama_index.core.workflow import Workflow, Event, StartEvent, StopEvent, Context, step
class SecurityAnalysisDone(Event):
report: str
class InfraAnalysisDone(Event):
report: str
class IncidentWorkflow(Workflow):
@step
async def fan_out(self, ctx: Context, ev: StartEvent) -> None:
ticket_id = ev.get("ticket_id", "INC-8091")
# Emit multiple events into the workflow loop concurrently
ctx.send_event(SecurityAnalysisDone(report=f"IAM audit clear for {ticket_id}"))
ctx.send_event(InfraAnalysisDone(report=f"VPC egress spike detected for {ticket_id}"))
@step
async def aggregate_findings(
self,
ctx: Context,
ev: SecurityAnalysisDone | InfraAnalysisDone
) -> StopEvent | None:
# Wait until both required event types arrive in context
events = ctx.collect_events(ev, [SecurityAnalysisDone, InfraAnalysisDone])
if events is None:
# One check is still pending; yield until it arrives
return None
sec_report, infra_report = events
summary = f"Synthesis: {sec_report.report} & {infra_report.report}"
return StopEvent(result=summary)
The ctx.collect_events call acts as a thread-safe barrier. It pauses aggregate_findings until both events land in the event loop. No manual locks. No flaky asyncio.gather error handling.
Production Hardening: 3 Operational Rules
Running agents at scale (50,000+ invocations daily) requires defensive engineering. These three production patterns will keep your pipelines stable and your latency predictable.
1. Enforce Per-Workflow and Per-Step Timeouts
Default timeouts are a liability. Model provider endpoints frequently experience silent socket hangs that tie up worker processes. Always declare explicit timeouts when initializing the workflow and making external calls:
# Terminate stalled workflows after 25 seconds to reclaim worker memory
wf = TriageWorkflow(timeout=25.0)
2. Stream and Intercept Events for Observability
Skip standard print() statements. Intercept event streams in real time through the workflow handler. This lets you stream status updates directly to users over WebSockets or forward trace data into tools like Datadog:
# Run the workflow and attach an event listener to the handler
handler = wf.run(ticket_text="Database connection pool saturated")
async for event in handler.stream_events():
# Ship structured telemetry directly to your logging platform
print(f"[TRACE] Step event dispatched: {type(event).__name__}")
result = await handler
3. Handle Malformed Model Outputs with Dead-Letter Events
When an LLM produces malformed output, do not crash the entire process. Wrap your parsing logic in a try/except block inside the step handler. If JSON parsing fails, increment a retry counter in ctx.data and re-emit a RetryStepEvent. Once retries hit your threshold—typically 3 attempts—emit a DeadLetterEvent to divert the payload to an engineering queue for human review.

