Cognitive Agents
Cognitive agents implement a BDI (Belief-Desire-Intention) architecture with episodic memory, HTN planning, intrinsic motivation, and inter-agent messaging. The agents run on the server; the SDK provides CRUD and control operations.
Creating an agent
import { ReasoningLayerClient } from '@kortexya/reasoninglayer';
const client = new ReasoningLayerClient({ baseUrl: 'https://platform.ovh.reasoninglayer.ai', tenantId: 'my-tenant-uuid', auth: { mode: 'cookie' },});
const agent = await client.cognitive.createAgent({ name: 'research-agent', config: { beliefConfidenceThreshold: 0.6, enableLearning: true, maxBeliefHistory: 200, maxGoalsPerCycle: 5, },});
console.log(agent.agentId); // UUIDconsole.log(agent.name); // "research-agent"Running a BDI cycle
The runCycle method executes a single Belief-Desire-Intention cycle for the agent. During a cycle, the agent perceives changes, updates beliefs, selects goals, forms intentions, and executes actions.
const result = await client.cognitive.runCycle({ agentId: agent.agentId,});
console.log(result.message);console.log(`Goals pursued: ${result.outcome.goalsPursued.length}`);console.log(`Goals achieved: ${result.outcome.goalsAchieved.length}`);console.log(`Goals failed: ${result.outcome.goalsFailed.length}`);console.log(`Actions executed: ${result.outcome.actionsExecuted.length}`);console.log(`New beliefs: ${result.outcome.newBeliefs.length}`);console.log(`Success rate: ${result.outcome.successRate}`);Managing beliefs
Beliefs represent what the agent knows about the world, each with a confidence score and source.
// Add a beliefconst belief = await client.cognitive.addBelief({ agentId: agent.agentId, belief: { sort: 'temperature_reading', features: { location: 'server-room', value: 42, }, }, confidence: 0.95, source: 'sensor-api',});
console.log(belief.beliefId); // UUID of the belief termManaging goals
Goals represent what the agent wants to achieve. Each goal has a priority and status.
// Add a goalconst goal = await client.cognitive.addGoal({ agentId: agent.agentId, goal: { sort: 'reduce_temperature', features: { target_location: 'server-room', target_value: 22, }, }, priority: 8, status: 'pending',});
console.log(goal.goalId); // UUID of the goal termAgent state
Retrieve the agent’s current state at two detail levels.
Basic state
const state = await client.cognitive.getAgent(agent.agentId);
console.log(`Agent: ${state.name}`);console.log(`Beliefs: ${state.beliefs.length}`);console.log(`Goals: ${state.goals.length}`);console.log(`Has pending goals: ${state.hasPendingGoals}`);
for (const belief of state.beliefs) { console.log(` [${belief.sortName}] confidence=${belief.confidence} source=${belief.source}`);}
for (const goal of state.goals) { console.log(` [${goal.goalSort}] priority=${goal.priority} status=${goal.status}`);}Extended state (BDI + motivation)
const extended = await client.cognitive.getExtendedAgentState({ agentId: agent.agentId,});
// Intentions (committed plans)for (const intention of extended.intentions) { console.log(`Intention ${intention.id}:`); console.log(` Goal: ${intention.goalSort}`); console.log(` Step: ${intention.currentStep}/${intention.plan.length}`); console.log(` Commitment: ${intention.commitmentStrength}`);}
// Motivation (intrinsic drives)if (extended.motivation) { for (const drive of extended.motivation.drives) { console.log(`Drive: ${drive.driveType} activation=${drive.activation}`); } for (const deficit of extended.motivation.deficits) { console.log(`Deficit: ${deficit.driveType} urgency=${deficit.urgency}`); } if (extended.motivation.dominantDrive) { console.log(`Dominant drive: ${extended.motivation.dominantDrive}`); }}
// Activation levels (ACT-R spreading activation)for (const act of extended.activations) { console.log(`${act.label ?? act.termId}: total=${act.total}`);}
// Rule utilitiesfor (const rule of extended.ruleUtilities) { console.log(`Rule ${rule.ruleId}: utility=${rule.utility} uses=${rule.uses}`);}Episodic memory
Agents maintain episodic memory of past experiences. You can recall similar episodes and view statistics.
// Recall episodes similar to a goalconst episodes = await client.cognitive.recallEpisodes({ agentId: agent.agentId, goalId: goalId, context: ['high-temperature', 'server-room'], maxResults: 5,});
for (const ep of episodes.episodes) { console.log(`Episode ${ep.episodeId}:`); console.log(` Outcome: ${ep.outcome}, Reward: ${ep.reward}`); console.log(` Actions: ${ep.actions.join(', ')}`); if (ep.similarity !== null && ep.similarity !== undefined) { console.log(` Similarity: ${ep.similarity}`); }}
// Episode statisticsconst stats = await client.cognitive.getEpisodeStats({ agentId: agent.agentId });console.log(`Total: ${stats.totalEpisodes}`);console.log(`Success rate: ${stats.successRate}`);console.log(`Average reward: ${stats.averageReward}`);Inter-agent messaging
Agents can send messages to each other or broadcast to all agents.
// Send a direct messageconst msg = await client.cognitive.sendMessage({ fromAgentId: agent1Id, toAgentId: agent2Id, content: { alert: 'temperature-critical', location: 'server-room' }, priority: 9,});
// Broadcast to all agentsconst broadcast = await client.cognitive.broadcastMessage({ fromAgentId: agent1Id, content: { type: 'status-update', status: 'operational' },});
console.log(`Sent to ${broadcast.recipientsCount} agents`);
// Mark messages as readawait client.cognitive.markMessagesRead({ agentId: agent2Id, messageIds: [msg.messageId],});HTN planning
Add Hierarchical Task Network methods that define how complex tasks decompose into subtasks.
const method = await client.cognitive.addHtnMethod({ agentId: agent.agentId, taskPattern: taskPatternTermId, subtasks: [subtask1Id, subtask2Id, subtask3Id], preconditions: ['has_tools', 'has_access'],});
console.log(method.methodId);Feedback
Provide human feedback on agent results to improve learning.
const feedback = await client.cognitive.provideFeedback({ agentId: agent.agentId, resultId: goalId, rating: 1, // +1 correct, 0 neutral, -1 wrong correction: 'The target temperature should be 20, not 22', preference: 'Prefer gradual cooling over sudden changes',});
console.log(feedback.feedbackId);if (feedback.learnedRuleId) { console.log(`Learned new rule: ${feedback.learnedRuleId}`);}console.log(`Updated rules: ${feedback.updatedRules.length}`);WebSocket event subscription
Subscribe to real-time events from a cognitive agent. Events are pushed as the agent processes BDI cycles.
const subscription = client.cognitive.subscribeToEvents(agent.agentId, { onEvent(event) { switch (event.type) { case 'connected': console.log(`Connected to agent ${event.agentId} at ${event.timestamp}`); break;
case 'cycle_complete': console.log(`Cycle complete: ${event.actionsExecuted} actions`); console.log(`Beliefs updated: ${event.beliefsUpdated}`); break;
case 'goal_completed': console.log(`Goal ${event.goalId}: ${event.success ? 'success' : 'failed'}`); break;
case 'kb_change': console.log(`KB change: ${event.changeType} on ${event.sort}/${event.termId}`); break;
case 'attention_shift': console.log(`Attention shifted to ${event.to} (priority: ${event.priority})`); break;
case 'hitl_request': console.log(`Human review requested: ${event.actionSort}`); console.log(`Confidence: ${event.confidence}`); break;
case 'impasse_detected': console.log(`Impasse on goal ${event.blockedGoal}: ${event.impasseType}`); console.log(`Suggestions: ${event.recoverySuggestions.join(', ')}`); break;
case 'heartbeat': // Server keepalive break;
case 'error': console.error(`Agent error [${event.code}]: ${event.message}`); break; } },
onConnect() { console.log('WebSocket connected'); },
onReconnect() { console.log('WebSocket reconnected'); },
onError(error) { console.error('WebSocket error:', error.message); },
onClose() { console.log('WebSocket closed'); },});
// Check connection statusconsole.log(`Connected: ${subscription.connected}`);
// Close when donesubscription.close();The 9 event types:
| Event Type | Description |
|---|---|
connected | Initial connection confirmation |
heartbeat | Server keepalive ping |
cycle_complete | A BDI cycle finished |
goal_completed | A goal succeeded or failed |
kb_change | Knowledge base was modified |
attention_shift | Agent’s focus changed |
hitl_request | Human-in-the-loop review requested |
impasse_detected | Agent is blocked and needs help |
error | Server-side error |
Deleting an agent
await client.cognitive.deleteAgent(agent.agentId);