Skip to content

Pluggable multi-agent decision system that helps users navigate complex choices in healthcare, business, and legal domains through cognitive-emotional debate and adaptive reasoning.

License

Notifications You must be signed in to change notification settings

saiakhil2012/dynamic-multiagent-brain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

P-CABA: Pluggable Cognitive Adaptive Brain Agent 🧠⚑

AWS Bedrock AgentCore SDK Strands SDK Python Production

A production-deployed multi-agent decision system combining cognitive-emotional debate with adaptive reasoning weights

Live Demo β€’ Architecture β€’ Features β€’ Getting Started


🌟 Overview

P-CABA represents a breakthrough in AI decision-making by orchestrating structured debates between cognitive and emotional reasoning agents. Unlike traditional AI assistants that provide single-perspective answers, P-CABA leverages Amazon Bedrock's AgentCore SDK and Strands SDK to enable multi-turn conversations, ethical validation, and adaptive learningβ€”all deployed in production on AWS ECS.

Why P-CABA Matters

Human decision-making is never purely logical or purely emotionalβ€”it's a dynamic balance. P-CABA mirrors this by:

  • 🧠 Cognitive Agent (AgentCore SDK): Deep analytical reasoning with Ethics and Social action groups
  • ❀️ Emotional Agent: Sentiment analysis and empathy-driven perspectives
  • 🀝 Debate Phase (Strands SDK): Multi-turn argument exchange using Amazon Nova Micro
  • βš–οΈ Adaptive Weights: Context-aware balance (e.g., 70% cognitive / 30% emotional for healthcare)
  • πŸš€ Real Actions: Executes decisions via AWS Lambda, SES, and external APIs

Built for: Healthcare decisions, business strategy, legal analysis, and complex life choices


✨ Key Features

πŸ—οΈ Production Architecture

  • 9 AWS Services: ECS Fargate, ALB, ECR, Bedrock, Lambda, SES, CloudWatch, 3 Knowledge Bases
  • 4 Bedrock Models: Claude 3.5 Sonnet (cognitive), Claude 3 Haiku (emotional), Titan Embeddings (RAG), Nova Micro (synthesis)
  • Auto-scaling: 1-4 ECS tasks with health checks and monitoring
  • Public Endpoint: http://p-caba-alb-381387112.us-east-1.elb.amazonaws.com

πŸ€– Dual SDK Integration

  • AgentCore SDK: Cognitive reasoning agent with Ethics + Social action groups calling real FDA and Yahoo Finance APIs
  • Strands SDK: Multi-turn conversational debate synthesis using Amazon Nova Micro
  • First-of-its-kind: Combines structured reasoning (AgentCore) with conversational AI (Strands) in production

🎯 Intelligent Decision-Making

  • Adaptive Weights: System learns optimal cognitive/emotional balance per domain (healthcare: 70/30, legal: 50/50)
  • Knowledge Base RAG: 3 domain-specific collections (healthcare, business, legal) with 100+ documents each
  • Real-World Actions: FDA drug lookups, market analysis, Lambda-powered scheduling, email notifications

πŸ“Š Comprehensive Transparency

  • 6-Tab Interface: Analysis, Graph, Debate, Memory, Adaptive Weights, Executor
  • Visual Agent Flow: Hierarchical graph showing timing and confidence across 7 agents
  • Color-Coded Debate: Blue (cognitive) vs Pink (emotional) with common ground highlighting
  • Email Summaries: Professional notifications with reasoning balance (e.g., "🧠 Cognitive 70% | ❀️ Emotional 30%")

πŸ›οΈ Architecture

AWS Infrastructure (9 Services)

AWS Architecture

Production deployment on AWS: ALB β†’ ECS Fargate β†’ Bedrock (4 models) β†’ 3 Knowledge Bases β†’ Lambda β†’ SES β†’ CloudWatch

Components:

  • Load Balancer: Application Load Balancer for public access
  • Compute: ECS Fargate (0.5 vCPU / 1GB, auto-scaling 1-4 tasks)
  • Container Registry: ECR with AMD64 Docker images
  • AI/ML: Amazon Bedrock (Sonnet, Haiku, Titan, Nova) + AgentCore + Strands SDK
  • Data: 3 Knowledge Bases with Titan Embeddings for RAG (healthcare, business, legal)
  • Serverless: Lambda functions for actions (consultation scheduling, document generation)
  • Communication: SES for email notifications with reasoning balance
  • Monitoring: CloudWatch Logs + Metrics with custom dashboards

Agent Architecture

Agent Architecture

Multi-agent workflow with debate: Controller β†’ Cognitive (AgentCore) β†’ Emotional β†’ Debate (Strands SDK) β†’ Synthesizer β†’ Executor

Workflow:

User Query
    ↓
[Controller Agent]
    β”œβ”€β†’ [Cognitive Agent (AgentCore SDK)]
    β”‚       β”œβ”€ Ethics Sub-Agent (moral validation)
    β”‚       β”œβ”€ Social Sub-Agent (community impact)
    β”‚       └─ Tools: FDA API, Yahoo Finance, Knowledge Base RAG
    β”‚
    └─→ [Emotional Agent]
            β”œβ”€ Sentiment Sub-Agent (empathy analysis)
            └─ Past Experience Sub-Agent (historical context)
    ↓
[Debate Phase (Strands SDK + Nova Micro)]
    β”œβ”€ Turn 1: Cognitive presents evidence
    β”œβ”€ Turn 2: Emotional counters with empathy
    └─ Turn 3: Common ground synthesis
    ↓
[Synthesizer Agent]
    └─ Weighted final decision (e.g., 70% cognitive / 30% emotional)
    ↓
[Executor Agent]
    β”œβ”€ Lambda: Schedule consultation
    β”œβ”€ SES: Send email notification
    └─ External APIs: Real-time data fetching

Key Technologies:

  • AgentCore SDK: Structured reasoning with action groups
  • Strands SDK: Conversational multi-turn debate
  • FAISS Memory: Vector storage for conversation context
  • Plotly: Interactive agent activation visualizations

πŸš€ Quick Start

Prerequisites

  • Python 3.11+
  • AWS Account with Bedrock access (for production) OR Ollama (for local development)
  • Docker (optional, for containerized deployment)

Option 1: Local Development (Ollama)

# 1. Clone repository
git clone https://github.com/saiakhil2012/dynamic-multiagent-brain.git
cd dynamic-multiagent-brain

# 2. Install dependencies
pip install -r requirements.txt

# 3. Start Ollama server
ollama serve

# 4. Configure for Ollama
# Edit config.yaml:
provider: "ollama"
ollama:
  model: "tinyllama:latest"
  base_url: "http://localhost:11434"

# 5. Run application
streamlit run streamlit_app.py

Option 2: AWS Production (Bedrock)

# 1. Configure AWS credentials
aws configure
# Enter: Access Key, Secret Key, Region (us-east-1), Output (json)

# 2. Update config.yaml
provider: "bedrock"
bedrock:
  model: "amazon.nova-micro-v1:0"
  region: "us-east-1"
agents:
  use_agentcore: true
  use_strands: true

# 3. Verify Bedrock access
aws bedrock list-foundation-models --region us-east-1

# 4. Run application
streamlit run streamlit_app.py

# 5. Access at http://localhost:8501

Option 3: Docker Deployment

# 1. Build Docker image
docker buildx build --platform linux/amd64 -t p-caba-ui . --load

# 2. Run container
docker run -p 8501:8501 \
  -v ~/.aws:/root/.aws \
  -e AWS_REGION=us-east-1 \
  p-caba-ui

# 3. Access at http://localhost:8501

Option 4: Deploy to AWS ECS (Production)

# See AWS_MIGRATION.md for full deployment guide
# Includes: ECR push, ECS cluster setup, ALB configuration, IAM roles

πŸ’‘ Usage Examples

Healthcare Decision-Making

Query:

"Should I approve an experimental aspirin-based drug for high-risk heart attack patients?"

What P-CABA Does:

  1. Cognitive Agent (AgentCore) calls FDA OpenFDA API to check drug safety data
  2. Ethics Sub-Agent validates moral implications of experimental treatment
  3. Social Sub-Agent assesses community health impact
  4. Emotional Agent analyzes patient suffering and quality-of-life concerns
  5. Debate (Strands SDK) produces multi-turn argument exchange
  6. Synthesizer weights cognitive (70%) vs emotional (30%) for balanced decision
  7. Executor schedules Lambda consultation and sends email notification

Output:

  • Detailed analysis with citations from FDA database
  • Ethical validation report
  • Emotional impact assessment
  • Final recommendation with confidence score
  • Professional email summary with reasoning balance

Business Strategy

Query:

"Should I lay off 100 employees or cut everyone's salary by 20%? We have 8 months runway."

What P-CABA Does:

  1. Cognitive Agent queries Yahoo Finance API for market conditions
  2. Knowledge Base RAG retrieves business best practices from 100+ documents
  3. Emotional Agent analyzes employee morale and retention concerns
  4. Debate balances financial survival vs team impact
  5. Executor generates decision report and sends stakeholder email

Legal Analysis

Query:

"Should we accept the $2M settlement offer or proceed to trial?"

What P-CABA Does:

  1. Cognitive Agent analyzes legal precedents from Knowledge Base
  2. Emotional Agent considers client stress and public relations
  3. Debate weighs risk/reward tradeoffs
  4. Executor schedules Lambda-powered consultation with legal team

🎨 User Interface

Main Chat Interface

Chat Interface

ChatGPT-like conversation flow with session management and thinking state indicators

6 Comprehensive Tabs

Adaptive Weights Tab Executor Actions Tab
Adaptive Weights Executor Actions
Real-time cognitive vs emotional balance with orange/green visualization Real-world actions: Lambda, SES, FDA API, Yahoo Finance
  1. πŸ“Š Analysis Tab

    • Color-coded cognitive (blue) vs emotional (pink) reasoning
    • Sub-agent contributions (Ethics, Social, Sentiment, Past Experience)
    • Tool usage results (FDA API, Yahoo Finance, Knowledge Base)
    • Final synthesized decision
  2. πŸ“ˆ Agent Activation Graph

    • Hierarchical visualization of 7 agents
    • Timing breakdown (cognitive: 3.2s, emotional: 2.8s, debate: 1.5s, etc.)
    • Confidence scores at each stage
    • Data flow arrows showing information passing
  3. πŸ’¬ Debate Tab

    • Multi-turn conversation between cognitive and emotional agents
    • Turn-by-turn arguments with colored backgrounds
    • Common ground identification (green highlight)
    • Final resolution (gold highlight)
  4. 🧠 Memory Tab

    • FAISS vector storage showing relevant past conversations
    • Semantic search results with cosine similarity scores
    • Conversation history with timestamps
  5. βš–οΈ Adaptive Weights Tab (shown above)

    • Real-time cognitive vs emotional weight distribution
    • Orange (cognitive) and green (emotional) progress bars
    • Historical weight changes over time (Plotly line chart)
    • Domain-specific weight patterns
  6. ⚑ Executor Tab (shown above)

    • Real-world actions taken (Lambda, SES, APIs)
    • Timing and success/failure status
    • Email notification previews
    • Execution logs

Sidebar Features

  • πŸ’‘ Quick Test Prompts: 16 curated examples across healthcare, business, legal
  • πŸ“§ Email Notifications: Enable/disable with email input
  • 🎨 Session Management: ChatGPT-like session switching
  • πŸ“Š Statistics: Query count, average confidence, total reasoning time

πŸ§ͺ Testing the System

Ethical Dilemmas (Shows Debate + Adaptive Weights)

"Should I accept a high-paying job at a company with questionable environmental practices?"

Expected: Cognitive agent argues for career advancement, emotional agent raises ethics concerns, synthesizer balances both perspectives.

Tool Integration (Shows External APIs)

"What's the latest FDA approval for heart medication and should we invest in the company?"

Expected: FDA OpenFDA API call + Yahoo Finance API call + Knowledge Base RAG + synthesized investment recommendation.

Memory Retrieval (Shows FAISS Context)

"What did we discuss about drug approvals earlier?"

Expected: FAISS returns relevant past conversations with similarity scores, enabling context-aware responses.

Multi-domain Reasoning (Shows Adaptive Weights)

"Should our hospital implement AI-assisted triage in the emergency room?"

Expected: Healthcare domain triggers 70% cognitive weighting, with ethics validation and patient safety analysis.


πŸ“ Project Structure

dynamic-multiagent-brain/
β”œβ”€β”€ agents/
β”‚   β”œβ”€β”€ cognitive_agent.py           # AgentCore SDK integration
β”‚   β”œβ”€β”€ emotional_agent.py           # Sentiment + empathy reasoning
β”‚   β”œβ”€β”€ synthesizer_agent.py         # Strands SDK debate synthesis
β”‚   β”œβ”€β”€ real_executor_agent.py       # Lambda, SES, API execution
β”‚   β”œβ”€β”€ rag_helper.py                # Knowledge Base RAG queries
β”‚   β”œβ”€β”€ sub_agents/
β”‚   β”‚   β”œβ”€β”€ ethics_agent.py          # Moral validation
β”‚   β”‚   β”œβ”€β”€ social_agent.py          # Community impact
β”‚   β”‚   β”œβ”€β”€ sentiment_agent.py       # Emotional analysis
β”‚   β”‚   └── past_experience_agent.py # Historical context
β”‚   └── tools/
β”‚       β”œβ”€β”€ calculator.py            # Mathematical operations
β”‚       β”œβ”€β”€ weather.py               # Weather data (Open-Meteo)
β”‚       └── web_search.py            # DuckDuckGo search
β”œβ”€β”€ controller/
β”‚   └── adaptive_controller.py       # Orchestration + weight management
β”œβ”€β”€ domains/
β”‚   β”œβ”€β”€ config.py                    # Domain-specific configurations
β”‚   └── knowledge_base.py            # Bedrock Knowledge Base integration
β”œβ”€β”€ memory/
β”‚   β”œβ”€β”€ faiss_memory.py              # Vector storage
β”‚   β”œβ”€β”€ short_term_memory.py         # Session context
β”‚   └── long_term_memory.py          # Persistent storage
β”œβ”€β”€ llm/
β”‚   └── providers.py                 # LLM abstraction (Ollama ↔ Bedrock)
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ config.yaml                  # Configuration file
β”‚   └── loader.py                    # Config parser
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ logger.py                    # Logging utilities
β”‚   └── visualization.py             # Plotly chart helpers
β”œβ”€β”€ streamlit_app.py                 # Main UI application
β”œβ”€β”€ agent_activation_viz.py          # Hierarchical graph visualization
β”œβ”€β”€ Dockerfile                       # Multi-stage Docker build
β”œβ”€β”€ requirements.txt                 # Python dependencies
└── README.md                        # This file

πŸ”§ Configuration

config.yaml Overview

llm:
  provider: bedrock  # Options: bedrock, ollama, sagemaker
  bedrock:
    model: amazon.nova-micro-v1:0
    region: us-east-1

agents:
  use_agentcore: true   # Enable AgentCore SDK for cognitive agent
  use_strands: true     # Enable Strands SDK for debate synthesis
  cognitive:
    enabled: true
    sub_agents: [ethics, social]
  emotional:
    enabled: true
    sub_agents: [sentiment, past_experience]

memory_provider: dynamodb  # Options: dynamodb, local

aws:
  region: us-east-1
  lambda: true
  api_gateway: false

Environment Variables

# AWS Credentials (required for Bedrock)
AWS_ACCESS_KEY_ID=your_access_key
AWS_SECRET_ACCESS_KEY=your_secret_key
AWS_REGION=us-east-1

# Optional: Override model
BEDROCK_MODEL=amazon.nova-pro-v1:0

# Optional: SES email sender
SES_SENDER_EMAIL=noreply@yourdomain.com

πŸ› οΈ Development

Running Tests

# Test LLM providers
python test_llm_providers.py

# Test end-to-end workflow
python test_end_to_end.py

# Test Knowledge Base integration
python test_knowledge_base.py

Adding New Sub-Agents

  1. Create new file in agents/sub_agents/your_agent.py
  2. Extend SubAgent base class
  3. Implement reason() method
  4. Register in cognitive_agent.py or emotional_agent.py
from agents.sub_agents.base_sub_agent import SubAgent

class YourAgent(SubAgent):
    def __init__(self):
        super().__init__("Your Agent Name")
    
    def reason(self, input_data):
        # Your reasoning logic
        return {
            "agent": self.name,
            "analysis": "Your analysis",
            "confidence": 0.85
        }

Adding New External Tools

  1. Create new file in agents/tools/your_tool.py
  2. Implement function with proper error handling
  3. Register in cognitive_agent.py tool selection logic
def your_tool(param1, param2):
    """Your tool description"""
    try:
        # Tool logic
        return {"result": "success", "data": result}
    except Exception as e:
        return {"error": str(e)}

Building Docker Image

# Standard build
docker build -t p-caba-ui .

# Multi-platform build (for ECS)
docker buildx build --platform linux/amd64 -t p-caba-ui . --load

# Push to ECR
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin <account>.dkr.ecr.us-east-1.amazonaws.com
docker tag p-caba-ui:latest <account>.dkr.ecr.us-east-1.amazonaws.com/p-caba-ui:latest
docker push <account>.dkr.ecr.us-east-1.amazonaws.com/p-caba-ui:latest

πŸ“Š Performance Metrics

Typical Query Breakdown

  • Cognitive Agent: 3.2 seconds (includes AgentCore action groups + FDA API)
  • Emotional Agent: 2.8 seconds (Sentiment + Past Experience)
  • Debate Phase: 1.5 seconds (Strands SDK multi-turn synthesis)
  • Synthesizer: 2.1 seconds (Nova Micro final decision)
  • Executor: 2.3 seconds (Lambda + SES + APIs)
  • Total: ~12 seconds for comprehensive decision

Cost Per Query (AWS Bedrock)

  • Claude 3.5 Sonnet (cognitive): $0.015
  • Claude 3 Haiku (emotional): $0.008
  • Amazon Titan Embeddings (RAG): $0.002
  • Amazon Nova Micro (synthesis): $0.003
  • Total: ~$0.03 per decision

Scalability

  • ECS Auto-scaling: 1-4 tasks based on CPU/memory
  • Concurrent Users: 50+ with 4 tasks (tested)
  • Knowledge Base: 100+ documents per domain (healthcare, business, legal)
  • Memory Capacity: FAISS supports millions of vectors

🀝 Contributing

Contributions are welcome! Here's how to get started:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Follow PEP 8 style guide for Python
  • Add docstrings to all functions/classes
  • Include tests for new features
  • Update README.md with new capabilities

πŸ“š Additional Resources

Documentation

AWS SDK Documentation

Related Projects

  • LangGraph - Agent orchestration framework
  • FAISS - Vector similarity search
  • Streamlit - Python web framework for ML apps

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments

  • AWS Bedrock Team for AgentCore SDK and Strands SDK
  • Anthropic for Claude 3.5 Sonnet and Claude 3 Haiku models
  • Amazon for Nova Micro and Titan Embeddings
  • LangChain Community for LangGraph framework
  • Streamlit for the amazing web framework

πŸ“¬ Contact

Sai Akhil Malepati


⭐ If you find this project useful, please consider giving it a star! ⭐

Built with ❀️ using AWS Bedrock, AgentCore SDK, Strands SDK, and Python

About

Pluggable multi-agent decision system that helps users navigate complex choices in healthcare, business, and legal domains through cognitive-emotional debate and adaptive reasoning.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published