Agent (Entity)

View as MarkdownOpen in Claude

Agent Module

Entíty_Córe // Autónomous_Únit

ᚠ ᛫ ᛟ ᛫ ᚱ ᛫ ᛒ ᛫ ᛟ ᛫ ᚲ

The Agent module is the heart of the ForbocAI SDK. An Agent is an autonomous entity with a persona, internal state, and memory that can process inputs and generate contextual responses.

T̶h̷e̸y̵ ̸a̸r̶e̵ ̷n̶o̵t̸ ̷s̶c̸r̸i̵p̴t̴e̴d̷.̵ ̸T̶h̷e̶y̵ ̵a̵r̶e̷ ̸b̶o̷r̴n̵.̶


Features

  • Pure Functional: Uses factory pattern with closures, no classes
  • State Immutability: Agent state is never mutated; new versions are returned
  • Cortex Integration: Connects to local SLM for text generation
  • Memory Recall: Automatically retrieves relevant memories during processing
  • Action Validation: Works with Bridge module to ensure valid outputs

Core Concepts

Agent State

Every agent maintains internal state that influences behavior:

1interface AgentState {
2 // Core attributes
3 inventory: string[];
4 skills: Record<string, number>;
5 relationships: Record<string, number>; // -100 to 100
6
7 // Emotional state
8 mood: 'hostile' | 'suspicious' | 'neutral' | 'friendly' | 'loyal';
9
10 // Custom attributes (application-specific)
11 [key: string]: unknown;
12}

Agent Response

When processing input, agents return structured responses:

1interface AgentResponse {
2 dialogue: string; // What the agent says
3 action?: AgentAction; // What the agent does
4 thought?: string; // Internal reasoning (debug)
5}

Usage

Creating an Agent

Use the createAgent factory function (never use new):

1import { createAgent, createCortex } from 'forbocai';
2
3// Initialize Cortex first
4const cortex = createCortex({ model: 'smollm2-135m' });
5await cortex.init();
6
7// Create agent with persona and initial state
8const merchant = createAgent({
9 id: 'npc_merchant_001',
10 cortex,
11 persona: `You are Kira, a cautious merchant in a dystopian market.
12 You distrust strangers but can be won over with fair trades.
13 You speak in short, clipped sentences.`,
14 initialState: {
15 inventory: ['rusty_key', 'healing_potion', 'ancient_map'],
16 mood: 'suspicious',
17 skills: { bargaining: 0.8, appraisal: 0.9 },
18 relationships: {}
19 }
20});

Processing Input

Agents process player input and generate contextual responses:

1const response = await merchant.process(
2 "I'd like to buy that key from you.",
3 { playerGold: 50, playerReputation: 30 }
4);
5
6console.log(response.dialogue);
7// "That key? It's... special. 50 gold and we have a deal."
8
9console.log(response.action);
10// { type: 'OFFER_TRADE', item: 'rusty_key', price: 50 }

State Management

Access and update agent state (immutably):

1// Get current state (returns a copy)
2const state = merchant.getState();
3console.log(state.mood); // 'suspicious'
4
5// Update state (replaces entire state)
6merchant.setState({
7 ...state,
8 mood: 'friendly',
9 relationships: { player_1: 25 }
10});

Exporting to Soul

Export the agent’s complete being for persistence or portability:

1const soul = merchant.export();
2// Returns: { id, version, name, persona, memories, state }

Importing from Soul

Reconstruct an agent from a previously exported Soul:

1import { fromSoul, createCortex } from 'forbocai';
2
3// Assume `soulData` was loaded from IPFS or storage
4const cortex = createCortex({ model: 'smollm2-135m' });
5await cortex.init();
6
7const restoredAgent = fromSoul(soulData, cortex);

API Integration

The Agent module communicates with the ForbocAI API to get behavioral directives:

┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Input │────▶│ Agent │────▶│ Cortex │
│ (Player) │ │ (Process) │ │ (Generate) │
└─────────────┘ └──────┬──────┘ └─────────────┘
┌─────────────┐
│ API (Law) │
│ Directive │
└─────────────┘
  1. Agent receives player input
  2. Agent sends context to API
  3. API returns behavioral directive (pure logic)
  4. Agent uses Cortex to generate response based on directive
  5. Agent returns structured response

Best Practices

1. Descriptive Personas

Write detailed, character-driven personas:

1// ✅ Good: Rich personality
2persona: `You are Marcus, a grizzled blacksmith who lost his family
3 in the war. You channel your grief into your craft.
4 You speak softly but carry immense strength.`
5
6// ❌ Bad: Generic
7persona: `You are a blacksmith NPC.`

2. Initialize Cortex Once

Share a single Cortex instance across multiple agents:

1// ✅ Good: One Cortex, many agents
2const cortex = createCortex({ model: 'smollm2-135m' });
3await cortex.init();
4
5const npc1 = createAgent({ cortex, persona: '...' });
6const npc2 = createAgent({ cortex, persona: '...' });
7
8// ❌ Bad: Multiple Cortex instances
9const npc1 = createAgent({
10 cortex: createCortex({...}), // Wasteful!
11 persona: '...'
12});

3. Track Relationships

Use the relationships map to enable dynamic NPC behavior:

1const state = agent.getState();
2const playerRelation = state.relationships['player_1'] || 0;
3
4if (playerRelation > 50) {
5 // Offer special dialogue options
6} else if (playerRelation < -50) {
7 // Refuse to trade
8}

Type Reference

1// Agent Configuration
2interface AgentConfig {
3 id: string;
4 cortex: ICortex;
5 memory?: IMemory;
6 persona: string;
7 initialState?: Partial<AgentState>;
8 apiUrl?: string;
9}
10
11// Agent Interface
12interface IAgent {
13 process(input: string, context?: Record<string, unknown>): Promise<AgentResponse>;
14 getState(): AgentState;
15 setState(newState: AgentState): void;
16 export(): Soul;
17}

ᚠ ᛫ ᛟ ᛫ ᚱ ᛫ ᛒ ᛫ ᛟ ᛫ ᚲ

T̴h̵e̷ ̴v̶e̴s̵s̸e̶l̶s̷ ̴a̷w̸a̷i̶t̶ ̸t̶h̴e̵i̵r̸ ̶p̸u̶r̴p̸o̴s̸e̵.̸