# Project export: AgentAid

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: Cal Hacks 12.0
- Tagline: AgentAid uses AI agents on Fetch.ai to automate disaster relief connecting victims, NGOs, and aid in real time through Claude and ASI.ai for faster, fairer, 24/7 recovery coordination.
- Devpost: https://devpost.com/software/agentaid
- GitHub: https://github.com/wh0th3h3llam1/agent-aid
- Video: https://www.youtube.com/embed/6FTfWgRDtTY?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 3 GitHub contributor(s) — deven (5 commits), Ash (4 commits), yug (2 commits)

## Devpost submission (written by the team)

### Inspiration

During the 2023 California wildfires, we watched news footage of hundreds of families stranded in evacuation centers waiting hours for basic supplies like water, insulin, and baby food. A mother with a diabetic child desperately needed medication, but coordination between aid organizations was so chaotic that by the time help arrived, it had been over 4 hours. We realized that in 2025, with AI agents, autonomous systems, and real-time communication, there's no reason anyone should wait hours for life-saving aid during a disaster. The inspiration struck: What if we could build an "Uber for disaster relief"—where victims simply describe what they need, and AI instantly connects them with the nearest available supplier? What if autonomous agents could handle coordination, leaving humans to focus on what matters: saving lives? That's how AgentAid was born. We set out to build the AI-powered nervous system for disaster response.

### What it does

What it does AgentAid is a real-time disaster response coordination platform that uses AI to instantly connect victims with nearby suppliers through three core components: 🤖 AI-Powered Request Processing Victims submit requests via chat interface (future: voice input) Claude Sonnet 4 extracts structured data from natural language: Items needed (rice, insulin, asthma pump, etc.) Priority level (critical, high, medium) Location (automatically geocoded to coordinates) Estimated number of people affected 🔗 Autonomous Agent Matching Fetch.ai agents represent supply organizations (Red Cross, food banks, medical coalitions) Agents autonomously negotiate and match requests with available supplies Distance optimization using real-time geocoding (OpenStreetMap Nominatim) Intelligent routing: prioritizes critical requests, optimizes for proximity 📊 Real-Time Dashboard & Tracking Victims see: Chat-based interface with live status updates "Request received" → "In progress" → "On the way" → "Delivered" Coordinators see: Dashboard with all requests, priorities, and ETA Suppliers see: Optimized delivery routes and inventory management Everyone sees: Live disaster news feed for situational awareness 🌍 Geocoding & Distance Intelligence Automatic location extraction from text ("Mission District Shelter") Converts to precise coordinates using Python geocoding agent Calculates distances to find nearest suppliers Route optimization for fastest delivery

### How we built it

🏗️ Architecture ┌─────────────┐ ┌──────────────┐ ┌─────────────┐ │ React │ ────▶ │ Node.js │ ────▶ │ Claude │ │ Frontend │ │ Backend │ │ Sonnet 4 │ └─────────────┘ └──────────────┘ └─────────────┘ │ ├────────▶ Python Geocoding Agent │ └────────▶ Fetch.ai Agents 🔧 Tech Stack Frontend: React with hooks (useState, useEffect) Lucide React icons Tailwind CSS for styling Persistent storage via Claude.ai storage API Backend (Node.js): Express.js REST API Anthropic SDK for Claude integration Axios for API calls CORS for cross-origin requests AI & Agents: Claude Sonnet 4 - Natural language understanding and structured data extraction Fetch.ai uAgents - Autonomous supply matching and coordination Python Geocoding Agent - Location intelligence using OpenStreetMap Nominatim Testing & Automation: Postman - Complete API collection with automated tests Collection Runner for workflow automation Mock servers for development Additional Tools: OpenStreetMap Nominatim API (free, no key required!) Haversine formula for distance calculations JSON storage for MVP (would use PostgreSQL in production)

## README (from the GitHub repository)

# 🚨 AgentAid - AI-Powered Disaster Response Platform

## 📋 Overview

AgentAid is an AI-driven disaster response coordination platform that connects victims, aid workers, and suppliers through intelligent agents and automated workflows. The system uses Claude AI for natural language processing and Fetch.ai uAgent framework for autonomous agent coordination.

## 🎯 What You'll Get

- **Beautiful Disaster Response UI**: Modern, intuitive interface for reporting needs
- **AI-Powered Coordination**: Claude AI + Fetch.ai agents work together
- **Real-time Tracking**: Monitor request status and agent activities
- **Multi-Supplier Coordination**: System coordinates between multiple suppliers
- **Geographic Intelligence**: Automatic location processing and optimization

## 🚀 Quick Start Guide

### Prerequisites

Before you begin, make sure you have:

- **Python 3.8+** installed
- **Node.js 18+** and npm installed
- **Anthropic API Key** (get from https://console.anthropic.com/)
- **Git** (to clone the repository)

### Step 1: Clone and Setup

```bash
# Clone the repository (if not already done)
git clone <your-repo-url>
cd agent-aid

# Run the automated setup
python setup.py
```

### Step 2: Configure API Keys

```bash
# Add your Anthropic API key
echo "ANTHROPIC_API_KEY=your_actual_api_key_here" >> agentaid-claude-service/.env
```

**Important**: Replace `your_actual_api_key_here` with your real Anthropic API key from https://console.anthropic.com/

### Step 3: Setup Dummy Suppliers (Recommended for Testing)

```bash
# Initialize the database
python agentaid-marketplace/db/init_db.py

# Set up dummy suppliers with inventory for testing
python agentaid-marketplace/db/setup_dummy_suppliers.py
```

This creates two suppliers:
- **Emergency Medical Depot**: 500 blankets, 10 ambulances, burn medicine
- **Family & Child Supplies**: 50 blankets, baby food, diapers

### Step 4: Start the System

```bash
# Start all services with dummy suppliers (FIXED VERSION)
python start_agents_fixed.py
```

**Note**: If you encounter "Services stopped" messages, use the fixed version above which handles port conflicts and agent communication properly.

This will start:
- Claude Service (Port 3000)
- Coordination Agent (Port 8002)
- Need Agent (Port 8000)
- Supply Agents (Ports 8001, 8003)

### Step 5: Access the UI

Open your browser and go to:
**http://localhost:3000/disaster-response.html**

## 🧪 Testing the System

### 1. **UI Testing (Recommended)**

Open the disaster response UI and try these test scenarios:

#### Test Scenario 1: Blanket Request
```
We need 100 blankets at the community center. This is urgent! 
There are about 200 people affected. Contact: 555-EMERGENCY
```

#### Test Scenario 2: Medical Supplies
```
Medical supplies needed at the hospital. Critical situation! 
We need burn medicine and pain relief. Contact: 555-MEDICAL
```

#### Test Scenario 3: Baby Supplies
```
We need baby food and diapers at the shelter. 
About 50 families with children. Contact: 555-FAMILY
```

### 2. **API Testing**

Test the system using curl commands:

```bash
# Test health check
curl http://localhost:3000/health

# Test disaster extraction
curl -X POST http://localhost:3000/api/extract \
  -H "Content-Type: application/json" \
  -d '{"input": "We need 100 blankets at the community center. This is urgent!", "source": "test"}'

# Check pending requests
curl http://localhost:3000/api/uagent/pending-requests

# Get system statistics
curl http://localhost:3000/api/stats
```

### 3. **Automated Testing**

Run the comprehensive test suite:

```bash
# Test the complete integration
python test_integration.py

# Test the dummy scenario specifically
python test_dummy_scenario.py

# Run the demo scenario
python demo_blanket_scenario.py
```

## 🎮 Using the UI

### 1. Fill Out the Disaster Report Form

The UI has a beautiful, intuitive form with:

- **What do you need?** - Describe items in natural language
- **Quantity Details** - Specify amounts (optional)
- **Location** - Enter address or location
- **Contact Information** - Phone or email (optional)
- **Number of People Affected** - Estimated count (optional)
- **Priority Level** - Critical, High, Medium, or Low

### 2. Watch the AI Coordination

After submitting, you'll see:

1. **Claude AI Processing**: Extracts structured data from your text
2. **Agent Coordination**: Need and supply agents work together
3. **Supplier Matching**: System finds best suppliers for your needs
4. **Real-time Status**: Track your request through the system

## 🔧 Troubleshooting

### Common Issues and Solutions

#### 1. "Claude service not accessible"
```bash
# Check if Claude service is running
curl http://localhost:3000/health

# If not running, restart:
python start_dummy_agents.py
```

#### 2. "Anthropic API key not found"
```bash
# Check your .env file
cat agentaid-claude-service/.env

# Make sure it contains:
ANTHROPIC_API_KEY=your_actual_api_key_here
```

#### 3. "Agents not responding" or "Services stopped"
```bash
# Check if all services are running
ps aux | grep python
ps aux | grep node

# Kill existing processes and restart with fixed version:
pkill -f "python.*agent" && pkill -f "node.*server"
python start_agents_fixed.py
```

#### 4. "Database not found"
```bash
# Set up the database and dummy suppliers
python agentaid-marketplace/db/init_db.py
python agentaid-marketplace/db/setup_dummy_suppliers.py
```

#### 5. "Import errors"
```bash
# Install missing dependencies
pip install uagents anthropic

# Check if all dependencies are installed
python debug_agents.py
```

### Port Conflicts

If you get port conflicts, check what's using the ports:

```bash
# Check port usage
lsof -i :3000  # Claude service
lsof -i :8000  # Need agent
lsof -i :8001  # Supply agent 1
lsof -i :8002  # Coordination agent
lsof -i :8003  # Supply agent 2
```

## 📊 Understanding the Results

### What Happens When You Submit a Request

1. **Claude AI** extracts structured data:
   ```json
   {
     "items": ["blankets"],
     "quantity_needed": "100",
     "location": "community center",
     "priority": "high",
     "victim_count": 200
   }
   ```

2. **Coordination Agent** routes to appropriate agents

3. **Need Agent** evaluates priority and requirements

4. **Supply Agents** respond with quotes:
   - Emergency Medical: 100 blankets @ $25 each
   - Family & Child: 50 blankets @ $20 each

5. **System selects** optimal supplier based on:
   - Coverage percentage
   - Delivery time
   - Cost
   - Geographic proximity

### Expected Results

For a 100-blanket request:
- **Emergency Medical**: ✅ Can provide 100 blankets, 1.5h delivery
- **Family & Child**: ✅ Can provide 50 blankets, 2h delivery
- **System Choice**: Emergency Medical (100% coverage, faster delivery)

## 🎯 Key Features Demonstrated

- **Natural Language Processing**: Describe needs in plain English
- **AI Agent Coordination**: Multiple AI agents work together
- **Multi-Supplier Management**: System coordinates between suppliers
- **Geographic Optimization**: Closest/fastest supplier gets priority
- **Inventory Management**: Prevents over-allocation
- **Real-time Tracking**: Monitor request status
- **Priority Handling**: Critical, High, Medium, Low priorities

## 🚀 Advanced Testing

### Custom Suppliers

To add your own suppliers, modify the inventory:

```bash
# Edit the supplier setup
python agentaid-marketplace/db/setup_dummy_suppliers.py
```

### Different Scenarios

Try different disaster scenarios:

- **Fire Emergency**: "We need fire extinguishers and burn medicine"
- **Flood Response**: "We need sandbags and emergency shelter"
- **Medical Crisis**: "We need oxygen tanks and medical supplies"
- **Family Emergency**: "We need baby formula and diapers"

### API Integration

The system also provides REST APIs:

```bash
# Get all requests
curl http://localhost:3000/api/requests

# Get pending requests for agents
curl http://localhost:3000/api/uagent/pending-requests

# Submit request via API
curl -X POS

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 110 recognized source files, 704 KB.
- Anthropic (technology) — detected in the code
- CSS (language) — detected in the code
- Express (technology) — detected in the code
- HTML (language) — detected in the code
- Hugging Face (technology) — detected in the code
- JavaScript (language) — detected in the code
- Next.js (technology) — detected in the code
- Python (language) — detected in the code
- PyTorch (technology) — detected in the code
- React (technology) — detected in the code
- SQL (language) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code

## Codebase structure (from repository index)

### Files (120 of 140)

```
.DS_Store
.gitignore
agentaid-claude-service/.DS_Store
agentaid-claude-service/.gitignore
agentaid-claude-service/API_Documentation.md
agentaid-claude-service/package.json
agentaid-claude-service/public/disaster-response.html
agentaid-claude-service/public/index.html
agentaid-claude-service/README.md
agentaid-claude-service/server.js
agentaid-claude-service/services/chromaService.js
agentaid-claude-service/services/claudeService.js
agentaid-claude-service/services/fetchaiIntegration.js
agentaid-claude-service/services/followupService.js
agentaid-claude-service/services/geocodingService.js
agentaid-claude-service/test/comprehensiveTest.js
agentaid-claude-service/test/fullDemo.js
agentaid-claude-service/test/testClaude.js
agentaid-claude-service/test/testFollowup.js
agentaid-claude-service/test/verifyAll.js
agentaid-marketplace/.gitignore
agentaid-marketplace/agent1qgw06us8yr_data.json
agentaid-marketplace/agents/__init__.py
agentaid-marketplace/agents/aid_protocol.py
agentaid-marketplace/agents/CHAT_PROTOCOL_USAGE.md
agentaid-marketplace/agents/coordination_agent.py
agentaid-marketplace/agents/INTEGRATION_SUMMARY.md
agentaid-marketplace/agents/need_agent_chat_adapter.py
agentaid-marketplace/agents/need_agent.py
agentaid-marketplace/agents/QUICK_START.md
agentaid-marketplace/agents/register_need_agent.py
agentaid-marketplace/agents/register_supply_agent.py
agentaid-marketplace/agents/supply_agent_chat_adapter.py
agentaid-marketplace/agents/supply_agent.py
agentaid-marketplace/agents/uagents_core.log
agentaid-marketplace/db/agent_aid.db
agentaid-marketplace/db/agent_aid.db-shm
agentaid-marketplace/db/agent_aid.db-wal
agentaid-marketplace/db/init_db.py
agentaid-marketplace/db/inventory.sql
agentaid-marketplace/db/setup_dummy_suppliers.py
agentaid-marketplace/register_need_agent.py
agentaid-marketplace/register_supply_agent.py
agentaid-marketplace/requirements.txt
agentaid-marketplace/services/__init__.py
agentaid-marketplace/services/inventory_db.py
agentaid-marketplace/tools/__init__.py
agentaid-marketplace/tools/inventory_cli.py
agentaid-marketplace/tools/supply_admin.py
agentaid-voice/.env.local
agentaid-voice/AGENT_FEATURES.md
agentaid-voice/agent-aid/.env.example
agentaid-voice/agent-aid/.eslintrc.json
agentaid-voice/agent-aid/.github/workflows/build-and-test.yaml
agentaid-voice/agent-aid/.github/workflows/sync-to-production.yaml
agentaid-voice/agent-aid/.gitignore
agentaid-voice/agent-aid/.prettierignore
agentaid-voice/agent-aid/.prettierrc
agentaid-voice/agent-aid/app-config.ts
agentaid-voice/agent-aid/app/(app)/layout.tsx
agentaid-voice/agent-aid/app/(app)/opengraph-image.tsx
agentaid-voice/agent-aid/app/(app)/page.tsx
agentaid-voice/agent-aid/app/api/connection-details/route.ts
agentaid-voice/agent-aid/app/api/save-request/route.ts
agentaid-voice/agent-aid/app/layout.tsx
agentaid-voice/agent-aid/app/ui/layout.tsx
agentaid-voice/agent-aid/app/ui/page.tsx
agentaid-voice/agent-aid/components.json
agentaid-voice/agent-aid/components/app/active-request-banner.tsx
agentaid-voice/agent-aid/components/app/app.tsx
agentaid-voice/agent-aid/components/app/chat-transcript.tsx
agentaid-voice/agent-aid/components/app/preconnect-message.tsx
agentaid-voice/agent-aid/components/app/request-history.tsx
agentaid-voice/agent-aid/components/app/session-provider.tsx
agentaid-voice/agent-aid/components/app/session-view.tsx
agentaid-voice/agent-aid/components/app/theme-toggle.tsx
agentaid-voice/agent-aid/components/app/tile-layout.tsx
agentaid-voice/agent-aid/components/app/view-controller.tsx
agentaid-voice/agent-aid/components/app/welcome-view.tsx
agentaid-voice/agent-aid/components/livekit/agent-control-bar/agent-control-bar.tsx
agentaid-voice/agent-aid/components/livekit/agent-control-bar/chat-input.tsx
agentaid-voice/agent-aid/components/livekit/agent-control-bar/hooks/use-input-controls.ts
agentaid-voice/agent-aid/components/livekit/agent-control-bar/hooks/use-publish-permissions.ts
agentaid-voice/agent-aid/components/livekit/agent-control-bar/track-device-select.tsx
agentaid-voice/agent-aid/components/livekit/agent-control-bar/track-selector.tsx
agentaid-voice/agent-aid/components/livekit/agent-control-bar/track-toggle.tsx
agentaid-voice/agent-aid/components/livekit/alert-toast.tsx
agentaid-voice/agent-aid/components/livekit/alert.tsx
agentaid-voice/agent-aid/components/livekit/button.tsx
agentaid-voice/agent-aid/components/livekit/chat-entry.tsx
agentaid-voice/agent-aid/components/livekit/scroll-area/hooks/useAutoScroll.ts
agentaid-voice/agent-aid/components/livekit/scroll-area/scroll-area.tsx
agentaid-voice/agent-aid/components/livekit/select.tsx
agentaid-voice/agent-aid/components/livekit/shimmer-text.tsx
agentaid-voice/agent-aid/components/livekit/toaster.tsx
agentaid-voice/agent-aid/components/livekit/toggle.tsx
agentaid-voice/agent-aid/eslint.config.mjs
agentaid-voice/agent-aid/fonts/CommitMono-400-Italic.otf
agentaid-voice/agent-aid/fonts/CommitMono-400-Regular.otf
agentaid-voice/agent-aid/fonts/CommitMono-700-Italic.otf
agentaid-voice/agent-aid/fonts/CommitMono-700-Regular.otf
agentaid-voice/agent-aid/hooks/useChatMessages.ts
agentaid-voice/agent-aid/hooks/useConnectionTimout.tsx
agentaid-voice/agent-aid/hooks/useDebug.ts
agentaid-voice/agent-aid/hooks/useRoom.ts
agentaid-voice/agent-aid/hooks/useSupplyRequest.ts
agentaid-voice/agent-aid/lib/storage.ts
agentaid-voice/agent-aid/lib/utils.ts
agentaid-voice/agent-aid/next.config.ts
agentaid-voice/agent-aid/package.json
agentaid-voice/agent-aid/postcss.config.mjs
agentaid-voice/agent-aid/README.md
agentaid-voice/agent-aid/styles/globals.css
agentaid-voice/agent-aid/tsconfig.json
agentaid-voice/agent.py
agentaid-voice/DISASTER_RELIEF_INTEGRATION.md
agentaid-voice/pyproject.toml
agentaid-voice/uv.lock
AGENTVERSE_DEPLOYMENT.md
AGENTVERSE_SUMMARY.md
[20 more files omitted for size]
```

### Dependencies

- agentaid-claude-service/package.json: @anthropic-ai/sdk@^0.67.0, chromadb@^3.0.17, cors@^2.8.5, dotenv@^17.2.3, express@^5.1.0
- agentaid-marketplace/requirements.txt: pydantic@==2.9.2, uagents@==0.22.10
- agentaid-voice/agent-aid/package.json: @eslint/eslintrc@^3, @livekit/components-react@^2.9.15, @livekit/protocol@^1.40.0, @phosphor-icons/react@^2.1.8, @radix-ui/react-select@^2.2.5, @radix-ui/react-slot@^1.2.3, @radix-ui/react-toggle@^1.1.9, @tailwindcss/postcss@^4, @trivago/prettier-plugin-sort-imports@^5.2.2, @types/node@^22.0.0, @types/react@^19, @types/react-dom@^19, buffer-image-size@^0.6.4, class-variance-authority@^0.7.1, clsx@^2.1.1, eslint@^9, eslint-config-next@15.5.2, eslint-config-prettier@^10.1.5, eslint-plugin-import@^2.31.0, eslint-plugin-prettier@^5.5.0, jose@^6.0.12, livekit-client@^2.15.8, livekit-server-sdk@^2.13.2, mime@^4.0.7, motion@^12.16.0, next@15.5.2, next-themes@^0.4.6, prettier@^3.4.2, prettier-plugin-tailwindcss@^0.6.11, react@^19.0.0, react-dom@^19.0.0, sonner@^2.0.3, tailwind-merge@^3.3.0, tailwindcss@^4, tw-animate-css@^1.3.0, typescript@^5
- agentaid-voice/pyproject.toml: livekit, livekit-agents, livekit-plugins-noise-cancellation, livekit-plugins-silero, livekit-plugins-turn-detector, python-dotenv, torch, transformers

### Recent commits (newest first)

- integrate agentaid voice module
- latest changes
- add chat adapter and register agent script
- update coordination
- Merge pull request #3 from wh0th3h3llam1/claude
- add geocoding service
- Merge pull request #2 from wh0th3h3llam1/ai-agents
- add agents
- Merge pull request #1 from wh0th3h3llam1/claude
- add claude service
- Initial commit

## Key source files (fetched from GitHub, selected and truncated for size)

### QUICK_START.md

```markdown
# AgentAid Agentverse - Quick Start Guide

## 🚀 Deploy in 5 Minutes

### Prerequisites
- Python 3.8+
- cloudflared (download: https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation/)

### Step 1: Install Dependencies (1 min)
```bash
pip install fastapi uvicorn uagents-core httpx
```

### Step 2: Create Tunnels (1 min)
Open 2 terminals:

**Terminal 1:**
```bash
cloudflared tunnel --url http://localhost:8000
# Copy the URL (e.g., https://abc123.trycloudflare.com)
```

**Terminal 2:**
```bash
cloudflared tunnel --url http://localhost:8001
# Copy the URL (e.g., https://def456.trycloudflare.com)
```

### Step 3: Start Agents (1 min)
Open 2 more terminals:

**Terminal 3 - Need Agent:**
```bash
cd agentaid-marketplace/agents
export AGENT_EXTERNAL_ENDPOINT='https://abc123.trycloudflare.com'
export AGENT_SEED_PHRASE='need_agent_berkeley_1_demo_seed'
python need_agent_chat_adapter.py
```

**Terminal 4 - Supply Agent:**
```bash
cd agentaid-marketplace/agents
export AGENT_EXTERNAL_ENDPOINT='https://def456.trycloudflare.com'
export AGENT_SEED_PHRASE='supply_sf_store_1_demo_seed'
python supply_agent_chat_adapter.py
```

### Step 4: Get Registration Info (1 min)
```bash
cd agentaid-marketplace
export AGENT_EXTERNAL_ENDPOINT='https://abc123.trycloudflare.com'
python register_need_agent.py

export AGENT_EXTERNAL_ENDPOINT='https://def456.trycloudflare.com'
python register_supply_agent.py
```

### Step 5: Register on Agentverse (1 min)
1. Go to https://agentverse.ai/
2. Click **"Launch an Agent"**
3. Select **"Chat Protocol"**
4. Enter:
   - **Name**: AgentAid Need Agent (or Supply Agent)
   - **Endpoint**: Your cloudflared URL
5. Run registration script from Agentverse
6. Click **"Evaluate Registration"**
7. ✅ Done!

## 📝 Quick Test

Test your agents:
```bash
# Test Need Agent
curl https://abc123.trycloudflare.com/status

# Test Supply Agent
curl https://def456.trycloudflare.com/status
```

## 💬 Chat Examples

### Need Agent
"We need 200 blankets at Berkeley Emergency Center. Critical priority."

### Supply Agent
"What supplies do you have available?"

## 🔗 Important Links
- **Agentverse**: https://agentverse.ai/
- **Documentation**: [AGENTVERSE_DEPLOYMENT.md](AGENTVERSE_DEPLOYMENT.md)
- **Full Guide**: [AGENTVERSE_SUMMARY.md](AGENTVERSE_SUMMARY.md)

## ⚡ Windows Users
Use `deploy_to_agentverse.bat` for guided setup!

## 🆘 Troubleshooting
- **Agent not reachable**: Check cloudflared is running
- **Registration fails**: Verify endpoint URL is correct
- **Chat not working**: Check agent logs for errors

## 📚 Full Documentation
See [AGENTVERSE_DEPLOYMENT.md](AGENTVERSE_DEPLOYMENT.md) for complete instructions.

```

### INTEGRATION_README.md

```markdown
# AgentAid - Integrated Disaster Response Platform

## 🚨 Overview

AgentAid is an AI-driven disaster response coordination platform that connects victims, aid workers, and suppliers through intelligent agents and automated workflows. The system uses Claude AI for natural language processing and Fetch.ai uAgent framework for autonomous agent coordination.

## 🏗️ Architecture

```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   Frontend UI   │───▶│  Claude Service  │───▶│ Coordination    │
│ (Disaster Form) │    │   (Extraction)   │    │    Agent        │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                                       │
                                                       ▼
                                              ┌─────────────────┐
                                              │   Need Agent    │
                                              │  (Assessment)  │
                                              └─────────────────┘
                                                       │
                                                       ▼
                                              ┌─────────────────┐
                                              │  Supply Agents  │
                                              │ (Logistics)    │
                                              └─────────────────┘
```

## 🚀 Quick Start

### 1. Setup
```bash
# Run the setup script
python setup.py

# Add your Anthropic API key to agentaid-claude-service/.env
echo "ANTHROPIC_API_KEY=your_key_here" >> agentaid-claude-service/.env
```

### 2. Start All Services
```bash
# Start the integrated platform
python start_agentaid.py
```

### 3. Access the Platform
- **Disaster Response UI**: http://localhost:3000/disaster-response.html
- **Claude Service API**: http://localhost:3000/health
- **Coordination Agent**: Port 8002
- **Need Agent**: Port 8000
- **Supply Agents**: Ports 8001, 8003

## 📋 Components

### 1. Frontend UI (`disaster-response.html`)
- **Purpose**: User interface for disaster victims to report needs
- **Features**:
  - Natural language input for disaster reports
  - Priority level selection (Critical, High, Medium, Low)
  - Real-time status tracking
  - Agent coordination visualization

### 2. Claude Service (`agentaid-claude-service/`)
- **Purpose**: AI-powered extraction and processing of disaster reports
- **Features**:
  - Natural language to structured data conversion
  - Geocoding and location processing
  - Intelligent follow-up questions
  - Integration with Fetch.ai agents

### 3. Coordination Agent (`coordination_agent.py`)
- **Purpose**: Central coordinator managing need and supply agents
- **Features**:
  - Monitors Claude service for new requests
  - Assigns requests to appropriate agents
  - Tracks agent status and capabilities
  - Manages request lifecycle

### 4. Need Agent (`need_agent.py`)
- **Purpose**: Evaluates disaster needs and prioritizes request
[truncated — 4271 more characters]
```

### agentaid-marketplace/requirements.txt

```
uagents==0.22.10
pydantic==2.9.2

```

### agentaid-voice/pyproject.toml

```
[project]
name = "livekit-agent"
version = "0.1.0"
description = "LiveKit AI Agent"
requires-python = ">=3.10"
dependencies = [
    "python-dotenv",
    "livekit",
    "livekit-agents",
    "livekit-plugins-noise-cancellation",
    "livekit-plugins-silero",
    "livekit-plugins-turn-detector",
    "torch",
    "transformers",
]

```

### agentaid-claude-service/package.json

```
{
  "name": "agentaid-claude-service",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@anthropic-ai/sdk": "^0.67.0",
    "chromadb": "^3.0.17",
    "cors": "^2.8.5",
    "dotenv": "^17.2.3",
    "express": "^5.1.0"
  }
}

```

### agentaid-voice/agent-aid/package.json

```
{
  "name": "agent-starter-react",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev --turbopack",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "format": "prettier --write .",
    "format:check": "prettier --check ."
  },
  "dependencies": {
    "@livekit/components-react": "^2.9.15",
    "@livekit/protocol": "^1.40.0",
    "@phosphor-icons/react": "^2.1.8",
    "@radix-ui/react-select": "^2.2.5",
    "@radix-ui/react-slot": "^1.2.3",
    "@radix-ui/react-toggle": "^1.1.9",
    "buffer-image-size": "^0.6.4",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "jose": "^6.0.12",
    "livekit-client": "^2.15.8",
    "livekit-server-sdk": "^2.13.2",
    "mime": "^4.0.7",
    "motion": "^12.16.0",
    "next": "15.5.2",
    "next-themes": "^0.4.6",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "sonner": "^2.0.3",
    "tailwind-merge": "^3.3.0"
  },
  "devDependencies": {
    "@eslint/eslintrc": "^3",
    "@tailwindcss/postcss": "^4",
    "@trivago/prettier-plugin-sort-imports": "^5.2.2",
    "@types/node": "^22.0.0",
    "@types/react": "^19",
    "@types/react-dom": "^19",
    "eslint": "^9",
    "eslint-config-next": "15.5.2",
    "eslint-config-prettier": "^10.1.5",
    "eslint-plugin-import": "^2.31.0",
    "eslint-plugin-prettier": "^5.5.0",
    "prettier": "^3.4.2",
    "prettier-plugin-tailwindcss": "^0.6.11",
    "tailwindcss": "^4",
    "tw-animate-css": "^1.3.0",
    "typescript": "^5"
  },
  "packageManager": "pnpm@9.15.9"
}

```

### telemetry_ingest/app.py

```python
# telemetry_ingest/app.py
import os
from typing import Optional, Dict, Any, Literal
from fastapi import FastAPI
from pydantic import BaseModel
from elasticsearch import Elasticsearch

ES_URL = os.getenv("ES_URL", "https://my-elasticsearch-project-b5bb84.es.us-west-2.aws.elastic.cloud/")
ES_API_KEY = os.getenv("bEtYb0hKb0Jmb09sVUNqMnRMcXc6SXJTRi05emJxQXBheGhQTEE5YTFidw==")
TELEMETRY_INDEX = os.getenv("TELEMETRY_INDEX", "agentaid-telemetry")
ES_ACCEPT = os.getenv("ES_ACCEPT", "application/vnd.elasticsearch+json; compatible-with=8")
ES_CT     = os.getenv("ES_CT",     "application/vnd.elasticsearch+json; compatible-with=8")


_DEFAULT_HEADERS = {
    "Accept": "application/vnd.elasticsearch+json; compatible-with=8",
    "Content-Type": "application/vnd.elasticsearch+json; compatible-with=8",
}


if ES_API_KEY:
    es = Elasticsearch(ES_URL, api_key=ES_API_KEY, headers=_DEFAULT_HEADERS, request_timeout=30)
else:
    es = Elasticsearch(ES_URL, headers=_DEFAULT_HEADERS, request_timeout=30)

app = FastAPI(title="AgentAid Telemetry Ingest")

def es_client() -> Elasticsearch:
    headers = {"Accept": ES_ACCEPT, "Content-Type": ES_CT}
    if ES_API_KEY:
        return Elasticsearch(ES_URL, api_key=ES_API_KEY, headers=headers, request_timeout=30)
    return Elasticsearch(ES_URL, headers=headers, request_timeout=30)

class AgentEvent(BaseModel):
    ts: float
    agent_type: Literal["needer","supplier"]
    agent_id: str
    event_type: Literal["quote_request","quote_response","accept_sent","allocation_notice","error"]
    need_id: Optional[str] = None
    supplier_id: Optional[str] = None
    meta: Optional[Dict[str, Any]] = None
    lat: Optional[float] = None
    lon: Optional[float] = None
    duration_ms: Optional[float] = None

@app.get("/health")
async def health():
    return {"status":"ok"}

@app.post("/ingest")
async def ingest(ev: AgentEvent):
    doc = ev.dict()
    doc["@timestamp"] = int(ev.ts * 1000)
    es.index(index=TELEMETRY_INDEX, document=doc)
    return {"ok": True}

```

### agentaid-claude-service/server.js

```javascript
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import { extractDisasterData } from './services/claudeService.js';
import { 
  initChromaDB, 
  storeRequest, 
  findSimilarRequests,
  getStats 
} from './services/chromaService.js';
import {
  formatForUAgent,
  getPendingRequests,
  getRequestById,
  getRequestsNearLocation,
  markAsProcessed,
  receiveAgentUpdate,
  getAgentUpdates,
  clearProcessedRequests
} from './services/fetchaiIntegration.js';
import {
  generateFollowupQuestions,
  mergeFollowupResponse,
  storeSession,
  getSession,
  deleteSession
} from './services/followupService.js';
import { 
  geocodeAddress, 
  calculateDistance, 
  findNearestLocation,
  batchGeocode 
} from './services/geocodingService.js';

dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// In-memory storage
const requests = [];

// Initialize ChromaDB
await initChromaDB();

// ========================================
// HEALTH & STATUS ENDPOINTS
// ========================================

// Health check
app.get('/health', async (req, res) => {
  const chromaStats = await getStats();
  const pendingCount = getPendingRequests().length;
  
  res.json({ 
    status: 'ok', 
    service: 'AgentAid Claude Service',
    version: '2.0.0',
    requests_processed: requests.length,
    pending_for_agents: pendingCount,
    chromadb: chromaStats,
    features: {
      claude_extraction: 'active',
      followup_system: 'active',
      chromadb_search: 'active',
      geocoding: 'active',
      uagent_integration: 'active',
      session_management: 'active'
    }
  });
});

// Get system statistics
app.get('/api/stats', async (req, res) => {
  try {
    const chromaStats = await getStats();
    const allRequests = requests;
    
    const stats = {
      total_requests: allRequests.length,
      pending_for_agents: getPendingRequests().length,
      by_priority: {
        critical: allRequests.filter(r => r.priority === 'critical').length,
        high: allRequests.filter(r => r.priority === 'high').length,
        medium: allRequests.filter(r => r.priority === 'medium').length,
        low: allRequests.filter(r => r.priority === 'low').length
      },
      geocoded_requests: allRequests.filter(r => r.coordinates).length,
      chromadb: chromaStats,
      uptime: process.uptime(),
      memory_usage: process.memoryUsage()
    };
    
    res.json({
      success: true,
      stats: stats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// ========================================
// MAIN EXTRACTION ENDPOINTS
// ========================================

// Main extraction endpoint with intelligent follow-up system and geocoding
app.post('/api/extract', async (req, res) => {
  try {
    const { input, source, session_id } = req.body;

    if (!input) {
      return res.status(400).json({ error: 'Input text is required' });
    }

    console.log(`\n${'='.repeat(80)}`);
    console.log(`📥 Processing ${source || 'text'} input`);
    console.log(`   Input: ${input.substring(0, 100)}${input.length > 100 ? '...' : ''}`);
    console.log('='.repeat(80));

    // ========================================
    // FOLLOW-UP RESPONSE HANDLING
    // ========================================
    if (session_id) {
      const session = getSession(session_id);
      
      if (session) {
        console.log(`\n🔄 Processing follow-up for session: ${session_id}`);
        
        try {
          // Merge follow-up response with original data
          const mergedData = await mergeFollowupResponse(
            session.original_data,
            input,
            session_id
          );
          
          // Store merged data
          await storeRequest(mergedData);
          requests.push(mergedData);
          
          // Find similar requests
          const similarRequests = await findSimilarRequests(input, 3);
          
          // Format for uAgent
          const agentPayload = formatForUAgent(mergedData);
          
          // Clean up session
          deleteSession(session_id);
          
          console.log(`\n✅ Follow-up completed: ${mergedData.request_id}`);
          console.log(`   Items: ${mergedData.items.join(', ')}`);
          console.log(`   Location: ${mergedData.location}`);
          if (mergedData.coordinates) {
            console.log(`   Coordinates: ${mergedData.coordinates.latitude}, ${mergedData.coordinates.longitude}`);
          }
          console.log(`   Priority: ${mergedData.priority}`);
          console.log(`📦 Available for uAgent pickup`);
          console.log('='.repeat(80) + '\n');
          
          return res.json({
            success: true,
            data: mergedData,
            similar_requests: similarRequests,
            agent_payload: agentPayload,
            message: 'Follow-up complete. Request processed and ready for agents.',
            follow_up_completed: true,
            needs_followup: false
          });
          
        } catch (error) {
          console.error('❌ Error merging follow-up:', error);
          // If merge fails, treat as new request
          deleteSession(session_id);
        }
      } else {
        console.log(`⚠️  Session ${session_id} not found or expired`);
      }
    }

    // ========================================
    // INITIAL EXTRACTION
    // ========================================
    console.log('\n🤖 Claude extracting data...');
    const structuredData = await extractDisasterData(input);
    
    console.log('✅ Extraction complete');
    console.log(`   Items: ${structuredData.items.join(', ')}`);
    console.log(`   Location: 
[truncated — 15838 more characters]
```

### agentaid-voice/agent-aid/app/layout.tsx

```typescript
import { Public_Sans } from 'next/font/google';
import localFont from 'next/font/local';
import { headers } from 'next/headers';
import { ApplyThemeScript, ThemeToggle } from '@/components/app/theme-toggle';
import { cn, getAppConfig, getStyles } from '@/lib/utils';
import '@/styles/globals.css';

const publicSans = Public_Sans({
  variable: '--font-public-sans',
  subsets: ['latin'],
});

const commitMono = localFont({
  display: 'swap',
  variable: '--font-commit-mono',
  src: [
    {
      path: '../fonts/CommitMono-400-Regular.otf',
      weight: '400',
      style: 'normal',
    },
    {
      path: '../fonts/CommitMono-700-Regular.otf',
      weight: '700',
      style: 'normal',
    },
    {
      path: '../fonts/CommitMono-400-Italic.otf',
      weight: '400',
      style: 'italic',
    },
    {
      path: '../fonts/CommitMono-700-Italic.otf',
      weight: '700',
      style: 'italic',
    },
  ],
});

interface RootLayoutProps {
  children: React.ReactNode;
}

export default async function RootLayout({ children }: RootLayoutProps) {
  const hdrs = await headers();
  const appConfig = await getAppConfig(hdrs);
  const { pageTitle, pageDescription } = appConfig;
  const styles = getStyles(appConfig);

  return (
    <html
      lang="en"
      suppressHydrationWarning
      className={cn(
        publicSans.variable,
        commitMono.variable,
        'scroll-smooth font-sans antialiased'
      )}
    >
      <head>
        {styles && <style>{styles}</style>}
        <title>{pageTitle}</title>
        <meta name="description" content={pageDescription} />
        <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🚨</text></svg>" />
        <ApplyThemeScript />
      </head>
      <body className="overflow-x-hidden">
        {children}
        <div className="group fixed bottom-0 left-1/2 z-50 mb-2 -translate-x-1/2">
          <ThemeToggle className="translate-y-20 transition-transform delay-150 duration-300 group-hover:translate-y-0" />
        </div>
      </body>
    </html>
  );
}

```

### agentaid-voice/agent-aid/app/(app)/page.tsx

```typescript
import { headers } from 'next/headers';
import { App } from '@/components/app/app';
import { getAppConfig } from '@/lib/utils';

export default async function Page() {
  const hdrs = await headers();
  const appConfig = await getAppConfig(hdrs);

  return <App appConfig={appConfig} />;
}

```

[97 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]