daydreamsai/core
@daydreamsai/core
@daydreamsai/core
The core framework for building stateful AI agents with type-safe contexts, persistent memory, and extensible actions.
Installation
npm install @daydreamsai/core
Quick Start
import { createDreams, context, action } from '@daydreamsai/core';
import { openai } from '@ai-sdk/openai';
import * as z from 'zod';
// Define a context
const chatContext = context({
type: 'chat',
schema: z.object({
userId: z.string()
})
});
// Define an action
const searchAction = action({
name: 'search',
description: 'Search the web',
schema: z.object({
query: z.string()
}),
handler: async ({ call }) => {
// Implement search logic
return { results: ['result1', 'result2'] };
}
});
// Create agent
const agent = createDreams({
model: openai('gpt-4'),
contexts: [chatContext],
actions: [searchAction]
});
// Start the agent
await agent.start();
// Send a message
const response = await agent.send({
context: chatContext,
args: { userId: 'user123' },
input: { type: 'text', data: 'Search for AI news' }
});
Core Concepts
Contexts
Isolated stateful environments for managing conversations or tasks. Each context maintains its own memory and state.
const context = context({
type: 'support',
schema: z.object({ ticketId: z.string() }),
create: async ({ args }) => ({
status: 'open',
messages: []
})
});
Memory System
Two-tier architecture for managing agent memory:
- Working Memory: Temporary execution state (inputs, outputs, actions)
- Persistent Storage: Long-term memory via pluggable providers (KV, Vector, Graph)
// Access episodes from memory
const episodes = await agent.memory.episodes.getByContext('context:123');
// Export episodes
const result = await agent.exports.export({
episodes,
exporter: 'json'
});
Actions
Type-safe functions that agents can execute:
const action = action({
name: 'sendEmail',
schema: z.object({
to: z.string().email(),
subject: z.string(),
body: z.string()
}),
handler: async ({ call, memory }) => {
// Implementation
return { sent: true };
}
});
Extensions
Plugin system for adding capabilities:
const extension = createExtension({
name: 'weather',
actions: [getWeatherAction],
contexts: [weatherContext]
});
Key Features
- 🧠 Stateful Contexts: Manage isolated conversation states
- 💾 Persistent Memory: Built-in storage with episodes and context management
- 🔧 Type-Safe Actions: Zod-validated action schemas
- 🔌 Extensible: Plugin architecture for custom functionality
- 📊 Memory Export: Export conversations to JSON, Markdown, etc.
- 🔄 Async Task Management: Built-in task runner with concurrency control
- 📝 Structured Logging: Comprehensive execution tracking
Architecture
Agent (dreams.ts)
├── Context System (context.ts)
│ ├── Context State Management
│ ├── Lifecycle Hooks
│ └── Memory Persistence
├── Memory System (memory/)
│ ├── Working Memory
│ ├── Episode Storage
│ └── Providers (KV, Vector, Graph)
├── Engine (engine.ts)
│ ├── Execution Router
│ ├── Action Handler
│ └── Output Processing
└── Task Runner (task.ts)
├── Queue Management
└── Concurrency Control
API Reference
createDreams(config)
Creates a new agent instance.
context(definition)
Defines a context type with schema and lifecycle hooks.
action(definition)
Creates a type-safe action with validation.
Agent Methods
agent.start()
- Initialize the agentagent.run()
- Execute with contextagent.send()
- Send input and get responseagent.getContext()
- Retrieve context stateagent.exports.export()
- Export episodes
Configuration
const agent = createDreams({
// Required
model: languageModel,
// Optional
memory: memorySystem,
contexts: [...],
actions: [...],
extensions: [...],
modelSettings: {
temperature: 0.7,
maxTokens: 2000
},
debugLevel: 'info'
});
Examples
- Basic Chat - Simple conversation agent
- Multi-Context - Managing multiple contexts
- Custom Actions - Building custom actions
- Memory Export - Exporting conversations
- Discord Bot - Integration with Discord
Advanced Topics
Sub-Modules
memory/
- Memory system implementationmemory/exporters/
- Episode export system
Contributing
See CONTRIBUTING.md for development setup and guidelines.
License
MIT
Enumerations
Classes
- ContextLockManager
- EpisodicMemoryImpl
- ExportManager
- GraphMemoryImpl
- InMemoryGraphProvider
- InMemoryKeyValueProvider
- InMemoryVectorProvider
- JSONExporter
- KeyValueMemoryImpl
- KnowledgeExtractor
- KnowledgeService
- MarkdownExporter
- MemorySystem
- VectorMemoryImpl
- WorkingMemoryImpl
Interfaces
- Action
- ActionCallContext
- ActionContext
- Agent
- AgentContext
- Context
- ContextStateApi
- Entity
- EntityExtractionConfig
- EntityTypeDefinition
- Episode
- EpisodeHooks
- EpisodicMemory
- ExtractedEntity
- ExtractedRelationship
- ExtractionResult
- ForgetCriteria
- GraphEdge
- GraphFilter
- GraphMemory
- GraphNode
- GraphPath
- GraphProvider
- GraphTraversal
- Handlers
- HealthStatus
- IChain
- IWorkingMemory
- KeyValueMemory
- KeyValueProvider
- KnowledgeSchema
- KnowledgeServiceConfig
- Memory
- MemoryConfig
- MemoryManager
- MemoryProvider
- MemoryResult
- PushOptions
- RecallOptions
- Relationship
- RelationshipExtractionConfig
- RelationshipSemantics
- RelationshipTypeDefinition
- RememberOptions
- SearchOptions
- SemanticRelationship
- SetOptions
- Thought
- ThoughtRef
- VectorDocument
- VectorMemory
- VectorProvider
- VectorQuery
- VectorResult
- WorkingMemory
- WorkingMemoryData
Type Aliases
- ActionCall
- ActionCtxRef
- ActionHandler
- ActionResult
- ActionSchema
- ActionState
- AnyAction
- AnyActionWithContext
- AnyAgent
- AnyContext
- AnyOutput
- AnyRef
- Config
- ContextConfig
- ContextRef
- ContextRefArray
- ContextSettings
- ContextsEventsRecord
- ContextsRefRecord
- ContextState
- Debugger
- EventDef
- EventRef
- Expert
- Extension
- ExtractTemplateVariables
- InferActionArguments
- InferActionState
- InferAgentContext
- InferAgentMemory
- InferContextMemory
- InferContextOptions
- InferSchema
- InferSchemaArguments
- Input
- InputConfig
- InputRef
- Instruction
- Log
- LogChunk
- MaybePromise
- Optional
- Output
- OutputConfig
- OutputCtxRef
- OutputRef
- OutputRefResponse
- OutputResponse
- OutputSchema
- Pretty
- Registry
- Resolver
- RunRef
- StepRef
- Subscription
- TaskConfiguration
- TemplateResolver
- TemplateVariables
- XMLElement