Daydreams: Building Stateful AI Agents with Lightweight TypeScript Framework
The complex neural connections that power modern AI systems (Source: Unsplash)
In artificial intelligence development, we face a fundamental challenge: How can we create AI agents that remember past interactions, switch between multiple tasks, and maintain consistent behavior logic? Traditional frameworks often leave developers struggling with state management complexities. The Daydreams framework emerges as an elegant solution to these challenges.
What is the Daydreams Framework?
Daydreams is a lightweight TypeScript framework designed for building stateful, multi-context AI agents. Compatible with both Node.js and browser environments, it solves critical AI development pain points:
-
Memory gaps: Standard AI models “forget” after conversations end -
Task fragmentation: Difficulty managing multiple independent conversations -
Capability limitations: Lack of standardized methods for custom operations
Core Capabilities Explained
graph TD
A[User Input] --> B[Daydreams Engine]
B --> C[Context Manager]
C --> D[Memory Storage]
B --> E[Action Execution]
E --> F[External API Calls]
B --> G[LLM Processing]
G --> H[Structured Output]
Daydreams addresses these through three foundational pillars:
-
🔄 Multi-Context System
Manages multiple independent conversation streams simultaneously, with each context maintaining isolated state. Imagine a customer service agent handling dozens of inquiries, each with separate memory and progress tracking. -
💾 Persistent State Management
Conversation states automatically save and resume after restarts. Even after server reboots, your AI agent continues where it left off. -
🔌 Framework-Agnostic Design
Seamlessly integrates with LangChain, Vercel AI SDK, and other popular tools without forcing developers to abandon existing tech stacks.
Why Choose Daydreams?
Developer Experience Advantages
-
TypeScript Native Support: Full type safety and intelligent code completion -
Minimalist API: Master just two core concepts – contexts and actions -
Modular Architecture: Use only needed components (minimum bundle size: 5KB) -
Real-Time Streaming: Built-in support for progressive response delivery
// Streaming response example
await agent.send({
handlers: {
onLogStream: (log) => {
if (log.ref === "output") {
console.log(log.content); // Outputs response chunks in real-time
}
}
}
});
Practical Application Scenarios
-
Cross-Platform Chatbots: Maintain consistent user profiles across Discord, Telegram, etc. -
Complex Task Agents: Execute multi-step workflows like research or data analysis -
Personalized Recommendation Systems: Deliver precise suggestions based on interaction history -
Automated Workflows: Connect APIs to execute predefined operation sequences
5-Minute Quickstart
Environment Setup
Ensure you have:
-
Node.js 18+ environment -
TypeScript 4.5+ (recommended) -
LLM service API key (OpenAI/Anthropic/etc.)
Installation Commands
# Choose your preferred package manager
npm install @daydreamsai/core
# OR
yarn add @daydreamsai/core
# OR
pnpm add @daydreamsai/core
Build Your First AI Agent
import { createDreams, context } from "@daydreamsai/core";
import { anthropic } from "@ai-sdk/anthropic";
import { z } from "zod";
// Define chat context structure
const chatContext = context({
type: "chat",
schema: z.object({ userId: z.string() }),
create() {
return {
messages: [],
preferences: {} // Stores user preferences
};
},
});
// Create agent instance
const agent = await createDreams({
model: anthropic("claude-3-5-sonnet-latest"),
context: chatContext
}).start({ userId: "user-123" });
// Send message - state persists automatically
await agent.send({
context: chatContext,
args: { userId: "user-123" },
input: {
type: "text",
data: "Remember I use Python for data analysis"
}
});
Developer workspace for building AI agents (Source: Pexels)
Deep Dive: Core Concepts
Context: The Memory Container
Context is Daydreams’ core abstraction, representing an independent task or conversational environment. Each context contains:
-
Conversation history -
Custom state objects -
Metadata information
const projectContext = context({
type: "project",
schema: z.object({ projectId: z.string() }),
create() {
return {
tasks: [],
progress: 0,
lastUpdated: new Date()
};
}
});
// Isolated states for different projects
const projectA = agent.getContext({
context: projectContext,
args: { projectId: "A" }
});
Actions: Extending Agent Capabilities
Actions are custom functions agents can execute, defined through type-safe interfaces:
const sendEmailAction = {
name: "send_email",
description: "Send email to specified contact",
schema: z.object({
to: z.string().email(),
subject: z.string(),
body: z.string()
}),
handler: async ({ to, subject, body }) => {
// Actual email sending logic
return { success: true };
}
};
// Register with agent
const agent = createDreams({
actions: [sendEmailAction]
});
Memory: Knowledge Persistence
Daydreams employs a dual-layer storage architecture:
graph LR
A[Working Memory] --> B[Key-Value Store]
A --> C[Vector Store]
A --> D[Episodic Memory]
-
Key-Value Store: Preserves structured data -
Vector Store: Enables semantic search -
Episodic Memory: Records event sequences
// Save user preferences
await agent.memory.store.set("user:prefs", {
language: "en-US",
timezone: "America/New_York"
});
// Vector store for knowledge fragments
await agent.memory.vectors.upsert("fact-001", {
text: "User prefers Python for data analysis",
embedding: await generateEmbedding(text)
});
Architectural Insights
Daydreams features a modular event-driven architecture:
graph TB
Input[Input Sources] --> Engine[Core Engine]
Engine --> Context[Context Manager]
Engine --> Memory[Memory System]
Engine --> Actions[Action System]
Engine --> Task[Task Runner]
Task --> LLM[Large Language Model]
Context --> State[Context State]
Memory --> Vector[Vector Store]
Memory --> KV[Key-Value Store]
Actions --> Custom[Custom Actions]
Execution Workflow Explained
sequenceDiagram
participant User
participant Agent
participant Engine
participant Context
participant Action
participant Memory
User->>Agent: Send Request
Agent->>Engine: Process Request
Engine->>Context: Load State
Context->>Memory: Retrieve Data
Engine->>Action: Execute Operation
Action-->>Engine: Return Results
Engine->>Memory: Save State
Engine-->>User: Return Response
Practical Implementation Scenarios
Scenario 1: Cross-Platform Assistant
import { discordAdapter } from "@daydreamsai/discord";
const discordAgent = createDreams({
extensions: [discordAdapter],
context: userContext
});
// Shared state across platforms
discordAgent.onMessage((msg) => {
const state = agent.getContext({ userId: msg.author.id });
// Respond using conversation history
});
Scenario 2: Research Agent Collaboration
const researchAgent = createDreams({
model: anthropic("claude-3-opus"),
description: "Specialized research agent"
});
const writerAgent = createDreams({
model: openai("gpt-4-turbo"),
description: "Content creation agent"
});
// Shared context between agents
const sharedCtx = context({ type: "project" });
const researchData = await researchAgent.run({
context: sharedCtx,
input: "Latest advancements in quantum computing"
});
const report = await writerAgent.run({
context: sharedCtx,
input: researchData
});
Scenario 3: Blockchain Interactions
import { ethereumAction } from "@daydreamsai/chains";
const cryptoAgent = createDreams({
actions: [ethereumAction],
context: walletContext
});
// Execute on-chain operation
await agent.send({
action: "ethereum_transaction",
params: {
to: "0x...",
value: "1ETH"
}
});
Blockchain technology enabling decentralized applications (Source: Pexels)
Advanced Techniques & Best Practices
Hybrid Model Strategy
Select different models for specialized tasks:
createDreams({
model: openai("gpt-4"), // Default model
reasoningModel: anthropic("claude-3-opus"), // Complex reasoning
analysisContext: {
model: groq("mixtral-8x7b") // High-speed analysis
}
});
Debugging & Monitoring
Robust built-in diagnostics:
createDreams({
logLevel: LogLevel.DEBUG,
debugger: (ctxId, keys, data) => {
console.log(`[${ctxId}] ${keys.join(".")}`, data);
}
});
Performance Optimization
-
Tree Shaking: Include only used modules -
Stream Processing: Reduce memory footprint -
Caching Strategies: Reuse frequent query results
Ecosystem & Extensions
Platform Adapters
-
Discord: @daydreamsai/discord
-
Twitter: @daydreamsai/twitter
-
Telegram: @daydreamsai/telegram
-
CLI: @daydreamsai/cli
Storage Backends
-
Supabase: @daydreamsai/supabase
-
ChromaDB: @daydreamsai/chroma
-
MongoDB: @daydreamsai/mongo
Blockchain Support
Frequently Asked Questions
When should I use Daydreams?
Ideal use cases:
-
Chatbots requiring cross-session memory -
Multi-step workflow automation -
Personalized recommendation systems -
Unified assistants across platforms
Other solutions may be better for:
-
Single request-response interactions -
Projects deeply integrated with specific frameworks -
Simple front-end conversational applications
How does state persistence work?
Daydreams implements a dual-layer storage strategy:
// Working memory (volatile)
agent.context.state = { session: "active" };
// Persistent storage (auto-saved)
await agent.memory.store.set("user:123", preferences);
// Restore after restart
const agent = createDreams(/* config */).start();
console.log(await agent.memory.store.get("user:123"));
Which language models are supported?
Compatible with major providers via adapters:
Provider | Example Models | Adapter |
---|---|---|
OpenAI | GPT-4 | @ai-sdk/openai |
Anthropic | Claude 3.5 | @ai-sdk/anthropic |
Gemini Pro | @ai-sdk/google |
|
Groq | Mixtral | @ai-sdk/groq |
Local Models | Llama 3 | @ai-sdk/ollama |
Join the Daydreams Community
Daydreams is MIT-licensed open source. We welcome contributions:
# Clone repository
git clone https://github.com/daydreamsai/daydreams.git
cd daydreams
# Install dependencies
pnpm install
# Build in development mode
pnpm build:packages --watch
# Run tests
pnpm test
Community Resources:
Collaborative development drives innovation (Source: Unsplash)
Conclusion: Building Truly Intelligent Agents
The Daydreams framework redefines how we build AI agents by enabling developers to:
-
Create genuinely memorable AI systems -
Manage complex multi-task environments -
Seamlessly extend agent capabilities -
Deploy across diverse environments
Whether building customer service bots, research assistants, or personalized recommendation systems, Daydreams provides powerful yet simple abstractions that let you focus on business logic rather than infrastructure.
journey
title Evolution of AI Agents
section Basic Agents
Single Interactions --> Stateless: 1: Early Systems
section Daydreams
Persistent Memory --> Multi-Context: 2: Breakthrough
Task Management --> Action Execution: 3: Capability Expansion
section Future Vision
Autonomous Collaboration --> Goal-Driven: 4: Development Path
Currently in Alpha stage, Daydreams is evolving rapidly. Join our community today and help shape the future of AI agent development!