# Getting Started

A2A (Agent-to-Agent) agents are intelligent, autonomous applications that can process messages, handle document operations, and communicate with other agents in the Health Universe platform. They're perfect for building AI-powered healthcare workflows, document processing pipelines, and clinical decision support tools.

This guide will walk you through creating, testing, and deploying your first A2A agent.

## Prerequisites

Before you begin, make sure you have:

* Python 3.10+ installed
* A [GitHub account](https://docs.healthuniverse.com/overview/building-apps-in-health-universe/getting-started-with-health-universe/create-a-github-account)
* A [Health Universe account](https://docs.healthuniverse.com/overview/building-apps-in-health-universe/getting-started-with-health-universe/create-a-health-universe-account) with [GitHub linked](https://docs.healthuniverse.com/overview/building-apps-in-health-universe/getting-started-with-health-universe/link-your-github-account-to-your-health-universe-account)
* Basic familiarity with Python and async programming

## Installation

### 1. Create a New Repository

Create a new GitHub repository for your agent:

```bash
git clone https://github.com/<your_username>/<your_repo_name>.git
cd <your_repo_name>
```

### 2. Set Up Your Environment

Create and activate a virtual environment:

```bash
python -m venv .env
source .env/bin/activate  # On Windows: .env\Scripts\activate
```

### 3. Install the SDK

Install the Health Universe A2A SDK:

```bash
pip install health-universe-a2a
```

## Creating Your First Agent

### Basic Agent Structure

Create a file called `main.py` with your first agent:

```python
from health_universe_a2a import Agent, AgentContext
import json

class MedicalDataAnalyzer(Agent):
    def get_agent_name(self) -> str:
        return "Medical Data Analyzer"

    def get_agent_description(self) -> str:
        return "Analyzes medical datasets and generates clinical insights"

    async def process_message(self, message: str, context: AgentContext) -> str:
        # Update progress for the user
        await context.update_progress("Starting analysis...", 0.1)

        # List documents in the thread
        docs = await context.documents.list_documents()
        
        if not docs:
            return "No documents found to analyze. Please upload medical data files."

        # Process each document
        results = []
        for i, doc in enumerate(docs):
            await context.update_progress(
                f"Analyzing {doc.name}...", 
                (i + 1) / len(docs) * 0.8
            )
            
            # Read document content
            try:
                content = await context.documents.download_text(doc.id)
                # Simple analysis example
                word_count = len(content.split())
                results.append({
                    "document": doc.name,
                    "word_count": word_count,
                    "size_bytes": len(content.encode('utf-8'))
                })
            except Exception as e:
                results.append({
                    "document": doc.name,
                    "error": f"Could not process: {str(e)}"
                })

        # Write results as a new document
        await context.documents.write(
            "Analysis Results",
            json.dumps(results, indent=2),
            filename="analysis_results.json"
        )

        await context.update_progress("Analysis complete!", 1.0)
        
        return f"Successfully analyzed {len(docs)} documents. Results saved to analysis_results.json"

if __name__ == "__main__":
    agent = MedicalDataAnalyzer()
    agent.serve()
```

### Understanding the Agent Structure

Every A2A agent must implement three core methods:

* **`get_agent_name()`**: Returns the display name for your agent
* **`get_agent_description()`**: Describes what your agent does
* **`process_message()`**: The main logic that processes user requests

The `AgentContext` provides access to:

* **Document operations**: `context.documents` for reading/writing files
* **Progress updates**: `context.update_progress()` for user feedback
* **Inter-agent communication**: `context.call_agent()` for calling other agents

## Testing Locally

### 1. Create Test Data

Create a local test environment:

```bash
mkdir test_data
mkdir test_data/source
echo "Patient ID: 12345, Age: 45, Diagnosis: Hypertension" > test_data/source/patient_data.txt
```

### 2. Local Testing Script

Create `test_local.py`:

```python
import asyncio
from health_universe_a2a.local import create_local_context
from main import MedicalDataAnalyzer

async def test_agent():
    # Create local context
    context = create_local_context("./test_data")
    
    # Create agent instance
    agent = MedicalDataAnalyzer()
    
    # Test the agent
    result = await agent.process_message(
        "Please analyze the medical data", 
        context
    )
    
    print("Agent result:", result)

if __name__ == "__main__":
    asyncio.run(test_agent())
```

Run the test:

```bash
python test_local.py
```

### 3. Test the Server

You can also test the full HTTP server locally:

```bash
python main.py
```

Then visit:

* <http://localhost:8000> - Main endpoint
* <http://localhost:8000/.well-known/agent-card.json> - Agent metadata
* <http://localhost:8000/health> - Health check

## Creating Requirements File

Generate your dependencies:

```bash
pip freeze > requirements.txt
```

Your `requirements.txt` should include at minimum:

```txt
health-universe-a2a>=0.2.0
```

## Deploying to Health Universe

### 1. Prepare Your Repository

Ensure your repository contains:

* `main.py` - Your agent code
* `requirements.txt` - Dependencies
* `README.md` - Documentation (optional but recommended)

### 2. Commit and Push

```bash
git add .
git commit -m "Initial A2A agent implementation"
git push origin main
```

### 3. Deploy on Health Universe

1. Go to your [Health Universe workspace](https://docs.healthuniverse.com/overview/building-apps-in-health-universe/creating-a-workspace)
2. Click **"Deploy a new app"**
3. Fill in the deployment form:
   * **GitHub Repository**: Select your repository
   * **App Name**: "Medical Data Analyzer"
   * **Description**: "Analyzes medical datasets and generates clinical insights"
   * **Runtime**: Select **FastAPI** → **Add to Navigator**
   * **Main File**: `main.py`
4. Click **"Deploy App"**

### 4. Monitor Deployment

Watch the build logs to ensure your agent deploys successfully. Once complete, your agent will be available in Health Universe Navigator.

## Using Your Agent in Navigator

1. **Open Navigator** in your Health Universe workspace
2. **Upload documents** to a thread (medical data files, reports, etc.)
3. **Search for your agent** by name or description
4. **Click "Use Tool"** to run your agent
5. **Monitor progress** as your agent processes the documents
6. **View results** in the artifacts panel when complete

## Next Steps

Now that you have a basic agent working, you can:

* [Learn about document operations](https://docs.healthuniverse.com/overview/building-apps-in-health-universe/developing-your-health-universe-app/working-with-a2a-agents/document-operations) for advanced file handling
* [Explore inter-agent communication](https://docs.healthuniverse.com/overview/building-apps-in-health-universe/developing-your-health-universe-app/working-with-a2a-agents/inter-agent-communication) for building agent workflows
* [Add validation](https://github.com/Health-Universe/docs/blob/main/building-apps-in-health-universe/developing-your-health-universe-app/working-with-a2a-agents/validation-and-error-handling.md) to make your agents more robust
* [Integrate with LLMs](https://github.com/Health-Universe/docs/blob/main/deploying-your-app-to-health-universe/connecting-to-an-llm.md) for AI-powered analysis

## Common Issues

**Agent not appearing in Navigator?**

* Ensure you selected "Add to Navigator" during deployment
* Check that your agent implements all required methods

**Local testing not working?**

* Make sure you activated your virtual environment
* Verify the `test_data/source/` directory exists with sample files

**Deployment fails?**

* Check your `requirements.txt` includes `health-universe-a2a`
* Ensure your `main.py` file is in the repository root
* Review the build logs for specific error messages

**Need help?**

* Check the [Health Universe documentation](https://docs.healthuniverse.com)
* Review the [SDK source code](https://github.com/Health-Universe/health-universe-a2a-sdk) for examples
