# Integration Workflow > Step-by-step guide for integrating ForbocAI into your game # Integration Workflow `Wórkflow_Guíde // Intégration_Séquence` **ᚠ ᛫ ᛟ ᛫ ᚱ ᛫ ᛒ ᛫ ᛟ ᛫ ᚲ** This document outlines the complete workflow for integrating ForbocAI autonomous NPCs into your game engine. > *T̸h̴e̶ ̶p̵r̷o̸t̴o̷c̸o̶l̵ ̶b̷i̸n̶d̵s̷ ̷m̴i̵n̸d̸ ̸t̴o̵ ̷m̵a̷c̷h̴i̷n̶e̷.* *** ## System Architecture The ForbocAI Protocol uses a **Split-Brain** architecture: ``` ┌────────────────────────────────────────────────────────────────┐ │ THE NEURAL GRID │ ├────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────┐ ┌─────────────┐ ┌──────────────┐ │ │ │ GAME │ │ SDK │ │ API │ │ │ │ (Execution) │◄──►│ (Container) │◄──►│ (Logic) │ │ │ └──────────────┘ └─────────────┘ └──────────────┘ │ │ │ │ │ │ │ World Brain The Body The Mind │ │ (Physics) (SLM + VectorDB) (Pure Functions) │ │ │ └────────────────────────────────────────────────────────────────┘ ``` *** ## The Integration Loop Every NPC decision follows this standardized flow: ### Step 1: Game Sends Observation Your game detects an event and sends it to the SDK: ```typescript import { Agent, Cortex } from 'forbocai'; // Initialize once at game start const cortex = await Cortex.init({ model: 'smollm2-135m' }); const npc = await Agent.create({ cortex, persona: 'A grizzled merchant who has seen too much.', initialState: { inventory: ['health_potion'], mood: 'suspicious' } }); // When event occurs in game... const observation = { type: 'event', data: { eventType: 'PLAYER_ATTACKED_NPC', attackerId: 'player_1', damage: 15 }, context: { hp: npc.getState().hp, playerReputation: -50 } }; ``` ### Step 2: SDK Formats and Stores The SDK: 1. **Formats** the observation into the Protocol schema 2. **Stores** it in the local Vector DB (Memory module) 3. **Forwards** to the API for logic processing ```typescript // This happens internally in npc.process() await memory.store( 'Player attacked me for 15 damage', 'experience', 0.9 // High importance ); ``` ### Step 3: API Runs Pure Logic The API receives the context and runs **deterministic logic gates**: ```haskell -- The Neuro-Symbolic Laws (Pure Functions) -- Law 1: Self-Preservation if hp < 15 then ("CRITICAL: You are dying. FLEE.", "FLEE") -- Law 2: Retaliation else if attacked && canFight then ("Defend yourself!", "ATTACK") -- Law 3: Default else ("Act naturally.", "IDLE") ``` **Output**: A `Directive` containing: * System prompt for the local SLM * Action constraints * Priority level ### Step 4: SDK Generates Response The SDK uses the Directive to: 1. **Recall** relevant memories from Vector DB 2. **Generate** dialogue/actions using local SLM (Cortex) 3. **Validate** the action using Bridge module ```typescript const response = await npc.process({ input: 'Player attacked', context: { hp: 85, playerReputation: -50 } }); // Response: // { // dialogue: "You'll pay for that, scoundrel!", // action: { type: 'ATTACK', targetId: 'player_1' }, // thought: "Directive: Defend yourself!" // } ``` ### Step 5: Bridge Validates Action Before returning to the game, the Bridge module validates: ```typescript import { createBridge } from 'forbocai'; const bridge = createBridge({ strictMode: true }); const validation = await bridge.validate(response.action, { agentState: { hp: 85, mana: 50 }, worldState: { entities: ['player_1', 'npc_guard'] } }); if (!validation.valid) { // Use corrected action or default to IDLE response.action = validation.correctedAction; } ``` ### Step 6: Game Executes Action Your game receives the validated action and executes it: ```typescript // In your game's bot system switch (response.action.type) { case 'ATTACK': executeAttack(npc, response.action.targetId); break; case 'FLEE': executeFlee(npc); break; case 'SPEAK': displayDialogue(npc, response.dialogue); break; case 'IDLE': default: // Do nothing break; } ``` *** ## Complete Integration Example ```typescript // game/src/services/cortex.ts import { Cortex, Agent, createMemory, createBridge } from 'forbocai'; export class CortexService { private cortex: ICortex; private agents: Map = new Map(); private memory: IMemory; private bridge: IBridge; async init() { // Initialize core modules this.cortex = await Cortex.init({ model: 'smollm2-135m', apiUrl: 'https://forbocai-api.onrender.com' }); this.memory = createMemory({ decay: 'temporal', maxContextWindow: 10, apiUrl: 'https://forbocai-api.onrender.com' }); this.bridge = createBridge({ strictMode: true }); } async createNPC(id: string, persona: string, state: AgentState): Promise { const agent = await Agent.create({ cortex: this.cortex, persona, initialState: state, apiUrl: 'https://forbocai-api.onrender.com' }); this.agents.set(id, agent); return agent; } async processEvent(npcId: string, event: GameEvent): Promise { const agent = this.agents.get(npcId); if (!agent) throw new Error(`NPC ${npcId} not found`); // 1. Store observation await this.memory.store( eventToText(event), 'observation', event.importance ); // 2. Process through SDK → API → SDK const response = await agent.process( eventToInput(event), eventToContext(event) ); // 3. Validate action const validation = await this.bridge.validate(response.action, { agentState: agent.getState(), worldState: this.getWorldState() }); return { dialogue: response.dialogue, action: validation.valid ? response.action : validation.correctedAction, valid: validation.valid, reason: validation.reason }; } } ``` *** ## Memory Flow The Memory module enables persistent recall: ``` ┌─────────────────────────────────────────────────────────┐ │ MEMORY PIPELINE │ ├─────────────────────────────────────────────────────────┤ │ │ │ Game Event │ │ │ │ │ ▼ │ │ ┌────────────┐ ┌─────────────┐ ┌────────────┐ │ │ │ Store │───►│ Vector DB │───►│ Recall │ │ │ │ (Observe) │ │ (IndexedDB) │ │ (Query) │ │ │ └────────────┘ └─────────────┘ └────────────┘ │ │ │ │ │ ▼ │ │ Temporal Decay │ │ (Old memories fade) │ │ │ └─────────────────────────────────────────────────────────┘ ``` ```typescript // Store important events await memory.store("Player saved my life in battle", "experience", 0.95); await memory.store("Found gold hidden in the ruins", "observation", 0.6); // Recall relevant memories for context const memories = await memory.recall("Do I trust the player?", 5); // Returns memories ranked by relevance + importance ``` *** ## Bridge Validation Flow The Bridge ensures AI never breaks game rules: ``` ┌─────────────────────────────────────────────────────────┐ │ BRIDGE VALIDATION │ ├─────────────────────────────────────────────────────────┤ │ │ │ AI Action │ │ │ │ │ ▼ │ │ ┌────────────┐ │ │ │ Rule 1 │──► Movement has valid coordinates? │ │ └────────────┘ │ │ │ │ │ ▼ │ │ ┌────────────┐ │ │ │ Rule 2 │──► Attack target exists? │ │ └────────────┘ │ │ │ │ │ ▼ │ │ ┌────────────┐ │ │ │ Rule 3 │──► Agent has required resources? │ │ └────────────┘ │ │ │ │ │ ▼ │ │ Valid Action or Corrected Fallback │ │ │ └─────────────────────────────────────────────────────────┘ ``` *** ## Protocol Types Reference All communication uses these standardized types: ### Observation (Game → SDK) ```typescript interface Observation { type: 'event' | 'state' | 'request'; timestamp: number; agentId?: string; gameId?: string; data: Record; context?: Record; } ``` ### Directive (API → SDK) ```typescript interface Directive { type: 'system-prompt' | 'action-constraints' | 'behavior-rules'; content: string; constraints?: Record; priority?: 'high' | 'normal' | 'low'; expiresAt?: number; } ``` ### AgentAction (SDK → Game) ```typescript interface AgentAction { type: string; // 'MOVE' | 'ATTACK' | 'INTERACT' | 'SPEAK' | 'IDLE' target?: string; payload?: Record; reason?: string; confidence?: number; } ``` *** ## Best Practices ### 1. Initialize Once ```typescript // ✅ Good: Initialize at game start const cortex = await Cortex.init({ model: 'smollm2-135m' }); // ❌ Bad: Initialize per NPC npcs.forEach(async npc => { const cortex = await Cortex.init(...); // Wasteful! }); ``` ### 2. Batch Store Observations ```typescript // ✅ Good: Store significant events if (event.importance > 0.5) { await memory.store(event.description, 'observation', event.importance); } // ❌ Bad: Store every frame onUpdate(() => { memory.store(`Position: ${x},${y}`, 'state', 0.1); // Too much! }); ``` ### 3. Always Validate Actions ```typescript // ✅ Good: Validate before execution const result = await bridge.validate(action, context); if (result.valid) { execute(action); } else { execute(result.correctedAction || { type: 'IDLE' }); } // ❌ Bad: Trust AI blindly execute(response.action); // May break game rules! ``` *** **ᚠ ᛫ ᛟ ᛫ ᚱ ᛫ ᛒ ᛫ ᛟ ᛫ ᚲ** > *T̶h̵e̶ ̷G̸r̴i̵d̵ ̷a̶w̶a̷i̴t̵s̸ ̵y̴o̶u̷r̴ ̷c̷o̸n̵n̶e̷c̶t̵i̵o̷n̴.*