Skip to content

scrtlabs/secret-ai-fetch-agent

Repository files navigation

SecretAI Medical Prediction Agent

A medical prediction agent system built with the uAgents framework that integrates with SecretAI's confidential computing platform for privacy-preserving medical image analysis. The system processes medical images (breast density analysis) and returns PDF diagnostic reports through secure, encrypted execution.

Features

  • Confidential Computing: Privacy-preserving medical analysis using SecretAI's secure platform
  • Event-Driven Architecture: Built on uAgents framework for scalable agent communication
  • Rate Limiting: Built-in quota management (10 requests/hour) to prevent API abuse
  • Comprehensive Error Handling: Custom exception types with detailed logging
  • Multiple Client Interfaces: Both programmatic and CLI interfaces available
  • Async Operations: Full async/await support for non-blocking operations
  • Health Monitoring: Built-in health check endpoints for system monitoring
  • Automatic Cleanup: Secure temporary file management with automatic cleanup
  • Agent Inspector: Integration with AgentVerse for monitoring and debugging

System Architecture

The system consists of three main components:

  1. Medical Agent (medical_agent.py) - Server that processes requests
  2. CLI Client (cli.py) - Command-line interface for individual requests
  3. Batch Client (medical_client.py) - Programmatic client for batch processing

For detailed architecture diagrams, see ARCHITECTURE.md.

Installation

Prerequisites

  • Python 3.13 or higher
  • Access to SecretAI API (API token required)

Setup

  1. Clone the repository:

    git clone <repository-url>
    cd secret-ai-fetch-agent
  2. Install dependencies:

    pip install -r requirements.txt
    # or using poetry
    poetry install
  3. Create required directories:

    mkdir -p /tmp/medical_agent ./reports ./images
  4. Configure environment variables:

    export API_TOKEN="your-secretai-api-token"
    export API_ENDPOINT="https://secretai-fetch.scrtlabs.com:23434/predict/breast-density"
    export TEMP_DIR="/tmp/medical_agent"

Quick Start

1. Start the Medical Agent

python medical_agent.py

Expected Output:

INFO:__main__:Starting Medical Prediction Agent on port 8000
INFO:__main__:Agent address: agent1qwvhn4mmd6vraafm7yr9aqzsy3y96uzpas3w4wmutrr9nwgd0rsg6ncj5zx
INFO:__main__:API endpoint: https://secretai-fetch.scrtlabs.com:23434/predict/breast-density
INFO:__main__:Temp directory: /tmp/medical_agent
INFO:__main__:Initial health check: PASSED
INFO:     [Medical Prediction Agent]: Starting agent with address: agent1qwvhn4mmd6vraafm7yr9aqzsy3y96uzpas3w4wmutrr9nwgd0rsg6ncj5zx
INFO:     [Medical Prediction Agent]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=agent1qwvhn4mmd6vraafm7yr9aqzsy3y96uzpas3w4wmutrr9nwgd0rsg6ncj5zx
INFO:     [Medical Prediction Agent]: Starting server on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     [Medical Prediction Agent]: Manifest published successfully: Medical Prediction Protocol
INFO:     [Medical Prediction Agent]: Manifest published successfully: Health Protocol
INFO:     [uagents.registration]: Registration on Almanac API successful
INFO:     [uagents.registration]: Almanac contract registration is up to date!

2. Process Medical Images

Using CLI Interface (Recommended for single images)

python cli.py images/sample_A1.jpg --agent-address agent1qwvhn4mmd6vraafm7yr9aqzsy3y96uzpas3w4wmutrr9nwgd0rsg6ncj5zx

Expected Output:

Processing image: images/sample_A1.jpg
INFO:     [secretai-fetch-agent-cli]: Starting agent with address: agent1qf4h7lq9sn3ycmz7m4ednwctsv8gl4pv02zmkgzchwy87eft6uhjxrz549n
WARNING:  [secretai-fetch-agent-cli]: No endpoints provided. Skipping registration: Agent won't be reachable.
INFO:     [secretai-fetch-agent-cli]: Sending prediction request for: images/sample_A1.jpg
INFO:     [secretai-fetch-agent-cli]: Agent inspector available at https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8008&address=agent1qf4h7lq9sn3ycmz7m4ednwctsv8gl4pv02zmkgzchwy87eft6uhjxrz549n
INFO:     [secretai-fetch-agent-cli]: Starting server on http://0.0.0.0:8008 (Press CTRL+C to quit)

Using Batch Client (For multiple images)

python medical_client.py

Usage Examples

CLI Client Commands

Basic Usage

python cli.py path/to/medical_image.jpg --agent-address <agent_address>

With Patient ID

python cli.py chest_xray.jpg --agent-address agent1qwvhn4mmd6vraafm7yr9aqzsy3y96uzpas3w4wmutrr9nwgd0rsg6ncj5zx --patient-id "PATIENT_001"

Custom Output Directory

python cli.py mammogram.png --agent-address agent1qwvhn4mmd6vraafm7yr9aqzsy3y96uzpas3w4wmutrr9nwgd0rsg6ncj5zx --output-dir ./medical_reports

Health Check Only

python cli.py --health-check --agent-address agent1qwvhn4mmd6vraafm7yr9aqzsy3y96uzpas3w4wmutrr9nwgd0rsg6ncj5zx

With Custom Timeout

python cli.py large_image.jpg --agent-address agent1qwvhn4mmd6vraafm7yr9aqzsy3y96uzpas3w4wmutrr9nwgd0rsg6ncj5zx --timeout 600

CLI Help

python cli.py --help

Configuration

Environment Variables

Variable Description Default
AGENT_SEED Unique seed for agent identity medical-prediction-agent-2025
AGENT_NAME Display name for the agent Medical Prediction Agent
API_ENDPOINT SecretAI API endpoint https://secretai-fetch.scrtlabs.com:23434/predict/breast-density
API_TOKEN Bearer token for API authentication Required
PORT Agent listening port 8000
TEMP_DIR Temporary file storage directory /tmp/medical_agent
OUTPUT_DIR Directory for saving PDF reports ./reports

Supported File Formats

  • Images: .jpg, .jpeg, .png
  • Output: PDF reports with medical analysis

Rate Limits

  • Medical Prediction Protocol: 10 requests per hour per client
  • Health Check Protocol: Unlimited

Sample Agent Logs

Successful Request Processing

INFO:     [Medical Prediction Agent]: Received medical prediction request from agent1qf4h7lq9sn3ycmz7m4ednwctsv8gl4pv02zmkgzchwy87eft6uhjxrz549n
INFO:     [Medical Prediction Agent]: Prediction ID: 844a437a-ed11-4e73-81fc-0fe4b2f81ef3
INFO:     [Medical Prediction Agent]: Filename: sample_A1.jpg
INFO:     [Medical Prediction Agent]: Patient ID: None
INFO:     [Medical Prediction Agent]: Processing prediction request 844a437a-ed11-4e73-81fc-0fe4b2f81ef3
INFO:__main__:Calling prediction API for file: sample_A1.jpg
INFO:__main__:Successfully received PDF report (2048576 bytes)
INFO:     [Medical Prediction Agent]: Successfully processed prediction 844a437a-ed11-4e73-81fc-0fe4b2f81ef3

Network Error Example

ERROR:    [Medical Prediction Agent]: API error for prediction 844a437a-ed11-4e73-81fc-0fe4b2f81ef3: Network error: Cannot connect to host secretai-fetch.scrtlabs.com:23434 ssl:default [Connect call failed ('67.215.13.123', 23434)]
ERROR:    [Medical Prediction Agent]: Unable to resolve destination endpoint for agent: agent1qf4h7lq9sn3ycmz7m4ednwctsv8gl4pv02zmkgzchwy87eft6uhjxrz549n

Monitoring & Debugging

Agent Inspector

Each agent provides an inspector URL for real-time monitoring:

https://agentverse.ai/inspect/?uri=http%3A//127.0.0.1%3A8000&address=<agent_address>

Health Checks

Check agent health programmatically:

import asyncio
from cli import health_check

async def check_agent():
    is_healthy = await health_check("agent1qwvhn4mmd6vraafm7yr9aqzsy3y96uzpas3w4wmutrr9nwgd0rsg6ncj5zx")
    print(f"Agent healthy: {is_healthy}")

asyncio.run(check_agent())

Log Levels

Set different log levels for debugging:

export PYTHONPATH=.
python -c "
import logging
logging.basicConfig(level=logging.DEBUG)
exec(open('medical_agent.py').read())
"

Error Handling

Common Error Scenarios

  1. File Not Found

    ❌ Error: Image file not found: path/to/image.jpg
    
  2. Invalid File Format

    ❌ Error: Unsupported file type: .gif. Allowed types: .jpg, .jpeg, .png
    
  3. Network Connection Issues

    ❌ Error: Network error: Cannot connect to host secretai-fetch.scrtlabs.com:23434
    
  4. Rate Limit Exceeded

    ❌ Error: Rate limit exceeded. Please wait before sending more requests.
    
  5. API Authentication Error

    ❌ Error: API request failed with status 401: Unauthorized
    

Troubleshooting

  1. Agent Not Starting

    • Check if port 8000 is available
    • Verify environment variables are set
    • Ensure temp directory is writable
  2. Connection Refused

    • Verify agent address is correct
    • Check firewall settings
    • Ensure agent is running and healthy
  3. API Timeouts

    • Increase timeout with --timeout parameter
    • Check network connectivity to SecretAI endpoint
    • Verify image file size (large images take longer)

Security Considerations

Authentication

  • API tokens are passed as Bearer tokens in HTTP headers
  • Tokens should be stored securely in environment variables
  • Never commit API tokens to version control

Data Privacy

  • All medical analysis is performed within SecretAI's confidential computing environment
  • Temporary files are automatically cleaned up after processing
  • No medical data is permanently stored by the agent

Network Security

  • All communications use HTTPS/TLS encryption
  • Rate limiting prevents abuse and DoS attacks
  • Input validation prevents malicious file uploads

Testing

Unit Tests

pytest tests/

Integration Tests

# Test with real API (requires valid token)
python tests/test_integration.py

Load Testing

# Send multiple concurrent requests
for i in {1..5}; do
    python cli.py test_images/sample_$i.jpg --agent-address <agent_address> &
done
wait

Project Structure

secret-ai-fetch-agent/
├── medical_agent.py          # Main agent server
├── cli.py                    # CLI client interface
├── medical_client.py         # Batch processing client
├── models/
│   ├── __init__.py
│   └── medical_models.py     # Data models
├── pyproject.toml           # Project configuration
├── requirements.txt         # Python dependencies
├── README.md               # This file
├── ARCHITECTURE.md         # Architecture diagrams
├── images/                 # Sample medical images
│   ├── sample_A1.jpg
│   ├── sample_B2.png
│   └── chest_xray.jpg
└── reports/               # Generated PDF reports

Contributing

  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 Setup

  1. Install development dependencies:

    pip install -r requirements-dev.txt
  2. Run pre-commit hooks:

    pre-commit install
  3. Run tests before committing:

    pytest tests/ --cov=./ --cov-report=html

License

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

🆘 Support

  • Issues: Report bugs and feature requests on GitHub Issues
  • Documentation: See ARCHITECTURE.md for technical details
  • API Documentation: SecretAI API documentation (contact SecretAI team)

Related Links


Note: This agent requires access to SecretAI's confidential computing platform. Contact the SecretAI team for API key, access and authentication tokens.

About

SecretAI fetch.ai agent for medical diagnostics

Resources

Stars

Watchers

Forks

Packages