consciousness_sim 1.0.1
consciousness_sim: ^1.0.1 copied to clipboard
An advanced Dart library simulating machine consciousness based on Global Workspace Theory. Provides a sophisticated information-processing model that mimics attention mechanisms, memory systems, conc [...]
π§ consciousness_sim #
A production-ready Dart library with two integrated layers:
- Consciousness engine β machine consciousness simulation based on Global Workspace Theory (Baars, 1988): attention spotlight, tri-level memory, semantic inference, cross-modal binding.
- Autonomous agent framework β a full LLM-driven agent loop wired directly onto the consciousness engine: goal decomposition, execution DAG, tool routing, self-reflection, and memory persistence.
π¦ Installation #
# pubspec.yaml
dependencies:
consciousness_sim: ^1.0.0
dart pub get
ποΈ Table of Contents #
- Consciousness Engine
- Autonomous Agent Framework
- Running Examples
- Running Tests
- Documentation
- Roadmap
- References
π§ Consciousness Engine #
Quick Start #
import 'package:consciousness_sim/consciousness_sim.dart';
Future<void> main() async {
final mind = Consciousness();
await mind.observe('a cat is sitting on the table');
await mind.observe('the cat looks hungry');
await mind.observe('there is fish on the table');
print(mind.think());
// β "The cat will likely try to eat the fish."
}
Core Features #
| Feature | Description |
|---|---|
| π― Selective Attention | Spotlight model with salience-based concept prioritisation |
| π§© Conceptual Binding | Temporal + semantic binding engine with co-activation |
| ποΈ Tri-level Memory | Episodic, semantic, and working memory with consolidation |
| π Semantic Graph | Directed, weighted concept network with BFS/DFS/spreading activation |
| π‘ Inference Engine | Rule-based, causal, associative, and memory-driven reasoning |
| ποΈ Multi-Modal | Cross-modal binding for visual, auditory, tactile, and other inputs |
| π Pattern Discovery | Co-occurrence, sequence, and cluster pattern recognition |
| π Plugin System | Extensible processing hooks (emotion detection, logging, etc.) |
| π Metrics & Viz | Built-in performance metrics and ASCII workspace visualisation |
βοΈ Consciousness Configuration #
final mind = Consciousness(
config: ConsciousnessConfig(
name: 'MyMind',
workspaceCapacity: 7, // Miller's 7Β±2 chunks
attentionThreshold: 0.30, // Min salience to enter workspace
enableLongTermLearning: true, // Encode to episodic/semantic memory
enableContinuousDecay: true, // Background activation decay
decayIntervalSeconds: 5, // Decay timer interval
memoryConsolidationIntervalMinutes: 10, // EpisodicβSemantic promotion
logLevel: LogLevel.info, // Logging verbosity
),
);
π¬ Consciousness Examples #
Attention control
final mind = Consciousness(
config: ConsciousnessConfig(workspaceCapacity: 7, attentionThreshold: 0.3),
);
await mind.observe('weather is nice');
await mind.observe('FIRE ALARM!');
print(mind.think()); // "Fire is detected β this is dangerous!"
// Redirect attention manually
mind.refocusAttention(['weather', 'temperature']);
print(mind.think()); // Now focuses on weather
Custom inference rules
mind.learn(InferenceRule(
id: 'rule_low_battery',
name: 'robot_low_battery',
conditions: ['battery', 'low'],
conclusion: 'Robot should return to charging station.',
weight: 0.95,
));
await mind.observe('battery level is critically low');
print(mind.think()); // "Robot should return to charging station."
Multi-modal perception
await mind.observeVisual('obstacle detected ahead');
await mind.observeAuditory('collision warning beep');
await mind.observeTactile('proximity sensor: 10 cm');
final state = await mind.process();
print(mind.think()); // Synthesised from all three modalities
Memory access
final episodes = mind.recallEpisodes('cat fish'); // episodic
final facts = mind.recallFacts('hunger'); // semantic
final all = mind.recall('hungry animal'); // cross-memory
Plugins
class EmotionLogger extends ConsciousnessPlugin {
@override String get name => 'EmotionLogger';
@override
Future<void> process(ConsciousState state) async {
print('Workspace size: ${state.workspace.length}');
}
}
mind.addPlugin(EmotionLogger());
Visualisation
const viz = ConsciousnessVisualizer();
final state = mind.getCurrentState();
print(viz.renderState(state));
print(viz.renderActivationMap(state.activationMap));
print(viz.renderGraph(mind.conceptGraph));
π€ Autonomous Agent Framework #
The agent framework layers a full LLM-driven autonomous loop onto the consciousness engine. One call β mind.asAgent(...) β wires all subsystems together.
Architecture #
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AgentMind β
β β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββββββββ β
β β LLMCore β βPlanningEngineβ βAgentLoopController β β
β β (reason) ββββΆβ (plan/ ββββΆβ observe β β
β β β β replan) β β retrieveMemory β β
β ββββββββββββββββ ββββββββββββββββ β plan β β
β β β decide β β
β ββββββββββββββββ ββββββββββββββββ β execute β β
β β LLMProvider β β ToolRouter β β updateMemory β β
β β EchoβMockβ β β (6 built-in β β checkComplete β β
β β Http β β + custom) β ββββββββββββββββββββββ β
β ββββββββββββββββ ββββββββββββββββ β β
β βΌ β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββββββββ β
β βAgentMemory β βSelfReflectionβ β ExecutionDAG β β
β βStore β βModule β β (Kahn topo sort) β β
β β(inverted idx)β β(4 detectors) β β pendingβrunning β β
β ββββββββββββββββ ββββββββββββββββ β βsucceeded/failed β β
β ββββββββββββββββββββββ β
β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Consciousness (cognitive substrate) β β
β β workspace Β· attention Β· memory Β· perception Β· reasoning β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Loop cycle (per iteration):
observe β retrieveMemory β plan β decide β execute β updateMemory β checkComplete
LLM decision types (JSON protocol):
| Action | Trigger |
|---|---|
use_tool |
Execute a named tool with structured input |
think |
Record an internal thought without side effects |
complete |
Declare the goal achieved β loop exits successfully |
replan |
Discard remaining tasks and generate a new plan |
error |
Signal an unrecoverable situation |
Agent Quick Start #
import 'package:consciousness_sim/consciousness_sim.dart';
Future<void> main() async {
final mind = Consciousness();
final agent = mind.asAgent(
provider: MockLLMProvider(responses: [
'{"action":"use_tool","tool":"calculate","input":{"expression":"42*2"},'
'"thought":"Computing the result."}',
'{"action":"complete","reason":"Result is 84."}',
]),
);
final result = await agent.pursue(AgentGoal(
id: 'g-001',
description: 'Calculate 42 Γ 2',
successCriteria: ['Result returned'],
));
print(result.success ? result.summary : result.error);
// β "Result is 84."
await agent.dispose();
mind.dispose();
}
Agent Components #
| Component | Class | Responsibility |
|---|---|---|
| Goal model | AgentGoal |
Typed goal with id, description, criteria, priority, maxIterations |
| Task graph | ExecutionDAG |
Kahn's topological sort; tracks pending/running/succeeded/failed/skipped |
| LLM orchestration | LLMCore |
Prompt assembly, context compression, JSON parsing, token tracking |
| Agent memory | AgentMemoryStore |
Inverted word index; composite score = importance Γ exp(βageH/24); LRU eviction |
| Tool system | ToolRegistry / ToolRouter |
Registration, catalogue building, dispatch with typed results |
| Planning | PlanningEngine |
LLM-backed JSON decomposition + rule-based fallback; replan() preserves succeeded tasks |
| Execution loop | AgentLoopController |
Full autonomous cycle; graceful stop(); AgentLoopEvent broadcast stream |
| Self-reflection | SelfReflectionModule |
4 detectors: cascade failures, tool loop, stalled progress, thought spiral; optional LLM deep-reflection |
| Entry point | AgentMind |
Wires all layers; exposes pursue(), events, memory, llm, tools |
LLM Providers #
EchoLLMProvider (debug)
Echoes the last user message back as a complete action. Zero dependencies.
final agent = mind.asAgent(provider: EchoLLMProvider());
MockLLMProvider (testing)
Serves a fixed response queue then cycles. Supports keyword heuristics as fallback.
final provider = MockLLMProvider(
name: 'mock-gpt',
responses: [
'{"action":"use_tool","tool":"calculate","input":{"expression":"2+2"},"thought":"..."}',
'{"action":"complete","reason":"Done."}',
],
);
HttpLLMProvider (production)
OpenAI-compatible HTTP backend. Drop in any endpoint that follows the /v1/chat/completions schema.
final provider = HttpLLMProvider(
endpoint: 'https://api.openai.com/v1/chat/completions',
apiKey: Platform.environment['OPENAI_API_KEY']!,
model: 'gpt-4o',
maxTokens: 1024,
temperature: 0.2,
);
π§ Built-in Tools #
All built-in tools follow the ToolResult.failure() contract β they never throw; errors are returned as structured failures.
| Tool name | Class | Description |
|---|---|---|
search_web |
SearchWebTool |
Mock/DuckDuckGo-style keyword search |
calculate |
CalculateTool |
Recursive-descent math: +βΓΓ·, sqrt, pi, nested parens |
read_file |
ReadFileTool |
Reads a text file from disk (sandbox-restricted) |
write_file |
WriteFileTool |
Writes/appends text to a file (sandbox-restricted) |
call_api |
CallApiTool |
HTTP GET/POST with optional headers and body |
schedule_task |
ScheduleTaskTool |
Schedules a named callback after N seconds |
Register all built-in tools in one call:
final registry = ToolRegistry();
BuiltinToolset.registerAll(registry);
Or let AgentMind do it automatically via AgentMindConfig(registerBuiltinTools: true).
βοΈ Agent Configuration #
final agent = mind.asAgent(
provider: myProvider,
config: AgentMindConfig(
registerBuiltinTools: true, // auto-register 6 built-in tools
extraTools: [MyCustomTool()], // additional tools
enableReflection: true, // self-reflection module
loopConfig: AgentLoopConfig(
maxConsecutiveErrors: 3, // stop if N errors in a row
emitEvents: true, // broadcast AgentLoopEvent stream
iterationDelay: Duration.zero, // optional throttle between iterations
reflectionIntervalIterations: 5,// self-reflection every N iterations
),
),
);
AgentGoal fields:
AgentGoal(
id: 'g-001',
description: 'Your goal description',
successCriteria: ['Criterion 1', 'Criterion 2'],
maxIterations: 20, // hard cap (default 20)
priority: 0.8, // 0.0β1.0
timeoutSeconds: 120, // optional wall-clock limit
context: {'key': 'val'} // extra context injected into prompts
)
π Production OpenAI Setup #
import 'dart:io';
import 'package:consciousness_sim/consciousness_sim.dart';
Future<void> main() async {
final mind = Consciousness(
config: const ConsciousnessConfig(name: 'ProductionAgent'),
);
final agent = mind.asAgent(
provider: HttpLLMProvider(
endpoint: 'https://api.openai.com/v1/chat/completions',
apiKey: Platform.environment['OPENAI_API_KEY']!,
model: 'gpt-4o',
maxTokens: 1024,
temperature: 0.1,
),
config: AgentMindConfig(
registerBuiltinTools: true,
enableReflection: true,
loopConfig: const AgentLoopConfig(
maxConsecutiveErrors: 3,
emitEvents: true,
reflectionIntervalIterations: 5,
),
),
);
final result = await agent.pursue(AgentGoal(
id: 'prod-task-001',
description: 'Research quantum computing and summarise the key concepts.',
successCriteria: ['Summary provided', 'Key concepts listed'],
maxIterations: 15,
));
print(result.success ? result.summary : 'Failed: ${result.error}');
await agent.dispose();
mind.dispose();
}
π‘ Event Stream #
Subscribe to agent.events for real-time observation of the loop:
agent.events.listen((AgentLoopEvent event) {
switch (event.type) {
case AgentLoopEventType.iterationStarted:
print('ββ Iteration ${event.iteration} ββ');
case AgentLoopEventType.toolExecuted:
final r = event.data as ToolResult?;
print('π§ ${r?.toolName}: ${r?.outputText}');
case AgentLoopEventType.completed:
print('π― Done: ${event.data}');
case AgentLoopEventType.reflected:
print('πͺ Reflection: ${event.data}');
default:
break;
}
});
All 14 event types:
| Event | When emitted |
|---|---|
iterationStarted |
Beginning of each iteration |
observed |
Environment observations received |
memoryRetrieved |
Memory lookup completed |
planned |
DAG (re)planned |
decided |
LLM decision received |
toolExecuted |
Tool call returned |
thoughtRecorded |
think action processed |
taskSucceeded |
A DAG task marked succeeded |
taskFailed |
A DAG task marked failed |
memoryUpdated |
Memory store updated |
replanned |
replan action triggered |
reflected |
Self-reflection module ran |
completed |
Loop exited with success |
failed |
Loop exited with failure |
π οΈ Custom Tools #
Extend the agent with any tool by subclassing Tool:
class WeatherTool extends Tool {
const WeatherTool();
@override String get name => 'get_weather';
@override String get description => 'Returns current weather for a city.';
@override
Map<String, String> get inputSchema => {
'city': 'The city name to look up.',
};
@override
Future<ToolResult> run(Map<String, dynamic> input) async {
final city = input['city'] as String? ?? '';
if (city.isEmpty) return ToolResult.failure(name, 'city is required');
// call your weather API here β¦
return ToolResult.success(name, 'Sunny, 22Β°C in $city');
}
}
// Register it
final agent = mind.asAgent(
provider: myProvider,
config: AgentMindConfig(extraTools: const [WeatherTool()]),
);
Custom LLM Provider #
Implement LLMProvider to connect any backend:
class MyProvider implements LLMProvider {
@override String get name => 'my-llm';
@override
Future<LLMResponse> complete(LLMRequest request) async {
// Call your LLM service with request.messages
final text = await myLlmClient.chat(request.messages.last.content);
return LLMResponse(
content: text,
promptTokens: 0,
completionTokens: 0,
model: name,
);
}
}
Custom EnvironmentAdapter #
Inject real-world observations at each iteration:
class SensorAdapter implements EnvironmentAdapter {
@override
Future<List<AgentObservation>> poll() async {
final reading = await sensor.read();
return [
AgentObservation(
content: 'Sensor reading: $reading',
source: 'sensor',
salience: 0.8,
),
];
}
}
// Pass to AgentLoopController directly, or via AgentMindConfig
π Project Layout #
consciousness_sim/
βββ lib/
β βββ consciousness_sim.dart β Public API (single import)
β βββ core/
β β βββ models.dart β Concept, Memory, Inference, ConsciousState
β β βββ workspace.dart β WorkspaceManager (7Β±2 buffer)
β β βββ attention.dart β AttentionSpotlight
β β βββ binding.dart β BindingEngine
β β βββ consciousness.dart β Consciousness + AgentMind extension
β βββ memory/
β β βββ episodic_memory.dart
β β βββ semantic_memory.dart
β β βββ working_memory.dart
β β βββ memory_manager.dart
β βββ perception/
β β βββ sensory_input.dart
β β βββ feature_extraction.dart
β β βββ perception_buffer.dart
β βββ reasoning/
β β βββ inference_engine.dart
β β βββ conceptual_graph.dart
β β βββ causal_inference.dart
β β βββ pattern_recognizer.dart
β βββ integration/
β β βββ cross_modal_binding.dart
β β βββ synchronization.dart
β β βββ coherence_manager.dart
β βββ utils/
β β βββ logger.dart
β β βββ metrics.dart
β β βββ visualization.dart
β βββ agent/ β Autonomous agent framework
β βββ agent_models.dart β AgentGoal, AgentTask, AgentDecision, β¦
β βββ memory/
β β βββ agent_memory_store.dart
β βββ llm/
β β βββ llm_provider.dart β Echo / Mock / Http providers
β β βββ llm_core.dart β LLMCore (reason, compress, parse)
β βββ tools/
β β βββ tool_interface.dart β Tool, ToolResult, ToolRegistry, ToolRouter
β β βββ builtin_tools.dart β 6 built-in tools + _MathParser
β βββ planning/
β β βββ planning_engine.dartβ ExecutionDAG + PlanningEngine
β βββ loop/
β β βββ agent_loop.dart β AgentLoopController + events + adapters
β βββ reflection/
β βββ self_reflection.dartβ SelfReflectionModule (4 detectors)
βββ example/
β βββ basic_consciousness.dart β Consciousness quick-start
β βββ advanced_awareness.dart β Attention, plugins, metrics
β βββ learning_simulation.dart β Rule learning + inference
β βββ multi_modal_integration.dartβ Cross-modal binding
β βββ autonomous_agent.dart β Agent with MockLLMProvider + events
β βββ multi_tool_agent.dart β All 6 tools + custom tool + reflection
βββ test/
β βββ core_test.dart
β βββ memory_test.dart
β βββ perception_test.dart
β βββ reasoning_test.dart
β βββ integration_test.dart
β βββ agent/
β βββ agent_models_test.dart
β βββ llm_core_test.dart
β βββ tool_system_test.dart
β βββ planning_engine_test.dart
β βββ agent_loop_test.dart
βββ doc/
βββ AGENT_ARCHITECTURE.md β Deep-dive agent architecture doc
βββ THEORY.md β Scientific foundations (GWT, binding, β¦)
βββ PERFORMANCE_GUIDE.md β Tuning tips and benchmarks
π§ͺ Running Examples #
# Autonomous agent (MockLLMProvider, no API key needed)
dart run example/autonomous_agent.dart
# All 6 tools + custom tool + self-reflection
dart run example/multi_tool_agent.dart
# Basic consciousness demo
dart run example/basic_consciousness.dart
# Advanced attention & plugins
dart run example/advanced_awareness.dart
β Running Tests #
# All tests
dart test
# Consciousness-only tests
dart test test/core_test.dart test/memory_test.dart \
test/perception_test.dart test/reasoning_test.dart \
test/integration_test.dart
# Agent framework tests
dart test test/agent/
# Single file
dart test test/agent/agent_loop_test.dart
Test coverage:
| Suite | What is tested |
|---|---|
core_test |
Concept, WorkspaceManager, AttentionSpotlight, BindingEngine |
memory_test |
EpisodicMemory, SemanticMemory, WorkingMemory, MemoryManager |
perception_test |
FeatureExtractor, PerceptionBuffer, SensoryInputProcessor |
reasoning_test |
InferenceEngine, ConceptualGraph, CausalInference, PatternRecognizer |
integration_test |
CrossModalBinding, Synchronization, CoherenceManager, end-to-end |
agent_models_test |
AgentGoal, AgentTask, AgentDecision, AgentContext, AgentRunResult |
llm_core_test |
EchoLLMProvider, MockLLMProvider, LLMCore.reason(), compressContext |
tool_system_test |
ToolResult, ToolRegistry, ToolRouter, all 6 built-in tools |
planning_engine_test |
ExecutionDAG, PlanningEngine (rule-based + LLM-backed + lifecycle) |
agent_loop_test |
AgentLoopController, events, adapters, stop(), SelfReflectionModule |
π Documentation #
| Document | Content |
|---|---|
README.md |
This file β getting started, API reference |
doc/AGENT_ARCHITECTURE.md |
Deep-dive agent architecture: layers, data flow, extension guide, config tables |
THEORY.md |
Scientific foundations: GWT, binding theory, memory models, inference |
PERFORMANCE_GUIDE.md |
Tuning tips, benchmarks, memory sizing |
πΊοΈ Roadmap #
v1.0 β (Current) #
- Core workspace + attention spotlight
- Tri-level memory (episodic, semantic, working)
- Rule-based, causal, and associative inference
- Cross-modal binding and coherence
- Pattern recognition over concept streams
- Plugin system
- Full autonomous agent framework (LLM + tools + planning + loop + reflection)
- 6 built-in tools + custom tool API
- MockLLMProvider for zero-config testing
- HttpLLMProvider for OpenAI-compatible backends
v1.5 π§ #
- Reinforcement learning from agent feedback
- Emotion and mood state modelling with valence tracking
- Advanced causal chains (Pearl Level 2)
- Real-time streaming perception pipeline
- Vector-embedding semantic search in
AgentMemoryStore
v2.0 π #
- Self-referential awareness (meta-cognition module)
- Personality and value system encoded as inference rules
- Social reasoning: multi-agent coordination
- Gradual consciousness growth simulation
v3.0+ π― #
- AGI-lite: creative problem solving with hypothesis generation
- Ethical reasoning and value alignment
- Full self-model and autobiographical continuity
- Multi-modal LLM integration (vision, audio)
π License #
MIT Β© 2026 consciousness_sim contributors
π References #
- Baars, B. J. (1988). A cognitive theory of consciousness. Cambridge University Press.
- Dehaene, S. (2014). Consciousness and the Brain. Viking.
- Tulving, E. (1972). Episodic and semantic memory. In Organization of Memory (pp. 381β403).
- Baddeley, A. D. & Hitch, G. (1974). Working memory. Psychology of Learning and Motivation, 8, 47β89.
- Pearl, J. (2000). Causality: Models, Reasoning, and Inference. Cambridge University Press.
- Miller, G. A. (1956). The magical number seven. Psychological Review, 63(2), 81β97.
See THEORY.md for the complete annotated bibliography.