# Agent (Entity) > Create autonomous AI entities with persona, state, and memory # 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: ```typescript interface AgentState { // Core attributes inventory: string[]; skills: Record; relationships: Record; // -100 to 100 // Emotional state mood: 'hostile' | 'suspicious' | 'neutral' | 'friendly' | 'loyal'; // Custom attributes (application-specific) [key: string]: unknown; } ``` ### Agent Response When processing input, agents return structured responses: ```typescript interface AgentResponse { dialogue: string; // What the agent says action?: AgentAction; // What the agent does thought?: string; // Internal reasoning (debug) } ``` *** ## Usage ### Creating an Agent Use the `createAgent` factory function (never use `new`): ```typescript import { createAgent, createCortex } from 'forbocai'; // Initialize Cortex first const cortex = createCortex({ model: 'smollm2-135m' }); await cortex.init(); // Create agent with persona and initial state const merchant = createAgent({ id: 'npc_merchant_001', cortex, persona: `You are Kira, a cautious merchant in a dystopian market. You distrust strangers but can be won over with fair trades. You speak in short, clipped sentences.`, initialState: { inventory: ['rusty_key', 'healing_potion', 'ancient_map'], mood: 'suspicious', skills: { bargaining: 0.8, appraisal: 0.9 }, relationships: {} } }); ``` ### Processing Input Agents process player input and generate contextual responses: ```typescript const response = await merchant.process( "I'd like to buy that key from you.", { playerGold: 50, playerReputation: 30 } ); console.log(response.dialogue); // "That key? It's... special. 50 gold and we have a deal." console.log(response.action); // { type: 'OFFER_TRADE', item: 'rusty_key', price: 50 } ``` ### State Management Access and update agent state (immutably): ```typescript // Get current state (returns a copy) const state = merchant.getState(); console.log(state.mood); // 'suspicious' // Update state (replaces entire state) merchant.setState({ ...state, mood: 'friendly', relationships: { player_1: 25 } }); ``` ### Exporting to Soul Export the agent's complete being for persistence or portability: ```typescript const soul = merchant.export(); // Returns: { id, version, name, persona, memories, state } ``` *** ## Importing from Soul Reconstruct an agent from a previously exported Soul: ```typescript import { fromSoul, createCortex } from 'forbocai'; // Assume `soulData` was loaded from IPFS or storage const cortex = createCortex({ model: 'smollm2-135m' }); await cortex.init(); const 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: ```typescript // ✅ Good: Rich personality persona: `You are Marcus, a grizzled blacksmith who lost his family in the war. You channel your grief into your craft. You speak softly but carry immense strength.` // ❌ Bad: Generic persona: `You are a blacksmith NPC.` ``` ### 2. Initialize Cortex Once Share a single Cortex instance across multiple agents: ```typescript // ✅ Good: One Cortex, many agents const cortex = createCortex({ model: 'smollm2-135m' }); await cortex.init(); const npc1 = createAgent({ cortex, persona: '...' }); const npc2 = createAgent({ cortex, persona: '...' }); // ❌ Bad: Multiple Cortex instances const npc1 = createAgent({ cortex: createCortex({...}), // Wasteful! persona: '...' }); ``` ### 3. Track Relationships Use the relationships map to enable dynamic NPC behavior: ```typescript const state = agent.getState(); const playerRelation = state.relationships['player_1'] || 0; if (playerRelation > 50) { // Offer special dialogue options } else if (playerRelation < -50) { // Refuse to trade } ``` *** ## Type Reference ```typescript // Agent Configuration interface AgentConfig { id: string; cortex: ICortex; memory?: IMemory; persona: string; initialState?: Partial; apiUrl?: string; } // Agent Interface interface IAgent { process(input: string, context?: Record): Promise; getState(): AgentState; setState(newState: AgentState): void; export(): Soul; } ``` *** **ᚠ ᛫ ᛟ ᛫ ᚱ ᛫ ᛒ ᛫ ᛟ ᛫ ᚲ** > *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̵.̸*