mirror of
https://github.com/mastra-ai/mastra.git
synced 2026-11-17 08:44:46 +00:00
|
History
|
||
|---|---|---|
| .. | ||
| src/mastra | ||
| docker-compose.yaml | ||
| package.json | ||
| pnpm-lock.yaml | ||
| pnpm-workspace.yaml | ||
| README.md | ||
Durable Agents Example
This example demonstrates three patterns for durable agent execution, all with Redis-backed resumable streams.
Agent Patterns
| Agent | Factory | Resumable Streams | Durable Execution |
|---|---|---|---|
durableResearchAgent |
createDurableAgent |
Redis | - |
eventedResearchAgent |
createEventedAgent |
Redis | Workflow engine |
inngestResearchAgent |
createInngestAgent |
Redis | Inngest |
Setup
- Start Redis:
docker run -d -p 6379:6379 redis
- Install dependencies:
pnpm install
- Start the dev server:
pnpm dev
- For Inngest agent, start the Inngest dev server:
npx inngest-cli@latest dev
Usage
Start a stream
curl -X POST http://localhost:4111/api/agents/durable-research-agent/stream \
-H "Content-Type: application/json" \
-d '{"messages": [{"role": "user", "content": "Research quantum computing"}]}'
Reconnect to a stream
If your connection drops, use the runId to reconnect:
curl -X POST http://localhost:4111/api/agents/durable-research-agent/observe \
-H "Content-Type: application/json" \
-d '{"runId": "your-run-id", "offset": 5}'
How It Works
All three agent types inherit cache and pubsub from the Mastra instance:
import { EventEmitterPubSub } from '@mastra/core/events';
import { RedisServerCache } from '@mastra/redis';
import Redis from 'ioredis';
// Redis cache for resumable streams - events persist across reconnections
const cache = new RedisServerCache({ client: new Redis('redis://localhost:6379') });
// EventEmitter pubsub for real-time delivery (process-local)
const pubsub = new EventEmitterPubSub();
export const mastra = new Mastra({
cache,
pubsub,
agents: {
durableResearchAgent, // Inherits cache/pubsub
eventedResearchAgent, // Inherits cache/pubsub
inngestResearchAgent, // Inherits cache/pubsub
},
});
Events are cached with sequential indices. When observe() is called, missed events replay from cache before continuing with live events.