# OpenAI Assistants

**Use Case Overview**

**Scenario**: HIPAA-Compliant Healthcare Support Assistant\
**Objective**:

* Extend an OpenAI medical Q\&A assistant with:
  * Real-time auditing of model outputs
  * Automated PHI (Protected Health Information) redaction
  * Multi-region deployment for low-latency patient interactions

***

#### **Prerequisites**

* AgentGPT ≥3.2 + OpenAI API Enterprise Plan
* **AgentGPT Plugin**: `openai-enterprise-connector`
* Dedicated VPC with Healthcare API endpoints

***

#### **1. Designing the Augmented Assistant**

**Architecture:**

```python
from agentgpt import Agent, PHI_Redactor
from openai import OpenAI

class HIPAA_Assistant(Agent):
    def __init__(self):
        super().__init__(
            name="MedQA-v3",
            compliance_tags=["HIPAA", "HITECH"],
            audit_level="strict"
        )
        
        # Initialize OpenAI Assistant with medical fine-tuning
        self.openai_client = OpenAI(api_key=os.getenv("OPENAI_ENTERPRISE_KEY"))
        self.assistant = self.openai_client.beta.assistants.retrieve("asst_medicalV2")
        
        # Attach PHI redaction tool
        self.redactor = PHI_Redactor(mode="structured")
        
    async def process_query(self, patient_query: str) -> dict:
        """Process and audit medical questions"""
        # Step 1: Remove PHI before sending to OpenAI
        sanitized_input = self.redactor.redact(patient_query)
        
        # Step 2: Get OpenAI response
        openai_response = await self.openai_client.chat.completions.create(
            model=self.assistant.id,
            messages=[{"role": "user", "content": sanitized_input}]
        )
        
        # Step 3: Audit response for compliance
        self.audit_log.log_interaction(
            original_input=patient_query,  # Encrypted storage  
            sanitized_input=sanitized_input,
            model_output=openai_response.choices[0].message.content,
            compliance_check=self.run_compliance_checks(openai_response)
        )
        
        return self.redactor.restore_phi(openai_response.choices[0].message.content)
```

***

#### **2. Deployment Configuration**

**Multi-Region Support:**

```yaml
# hipaa-deployment.yaml
regions:
  - name: us-east-med
    openai_endpoint: https://api.med-openai.com/v1  
    agentgpt_node: cluster-aws-useast
    phi_storage: encrypted-s3://hipaa-bucket-east
    compliance:
      - hipaa
      hit_level: HITECH
      
  - name: eu-central-med
    openai_endpoint: https://api.med-openai.eu/v1
    agentgpt_node: cluster-gcp-eucentral
    phi_storage: encrypted-gcs://hipaa-bucket-eu
    compliance:
      - gdpr
      hit_level: EU_MDR
```

Deploy with:

```bash
agentgpt deploy assistants --file hipaa-deployment.yaml --healthcheck
```

***

#### **3. Audit & Compliance Workflow**

**Automated Compliance Checks:**

```python
def run_compliance_checks(response: str) -> dict:
    """Validate responses against healthcare regulations"""
    checks = {
        "phi_leakage": self.redactor.detect_phi(response) == 0,
        "clear_medical_advice": self.med_api.validate_advice_quality(response),
        "source_citations": self.check_citations(response, min_sources=2)
    }
    
    if not all(checks.values()):
        self.emergency_shutdown(response_thread_id)
        
    return checks
```

**Audit Log Structure:**

```json
{
  "timestamp": "2025-02-08T14:23:18Z",
  "session_id": "sess_7d3a",
  "input_hash": "sha256:a1b2...",
  "sanitized_input": "Patient with [REDACTED] reports chest pain lasting [REDACTED] hours",
  "model_used": "asst_medicalV2",
  "compliance_status": {
    "phi_checks_passed": true,
    "sources_verified": ["PMID:33264521", "CDC-2024-HeartGuidelines"],
    "risk_score": 0.04
  },
  "actor": "MedQA-v3 (OpenAI+AgentGPT)"
}
```

***

#### **4. Monitoring Dual Systems**

**Unified Performance Dashboard:**

```bash
agentgpt monitor openai --assistant MedQA-v3 --interval 5m
```

**Output**:

```
OPENAI PERFORMANCE (LAST 5M)
- Requests: 1,224  | Avg Latency: 420ms  
- Tokens: 189,402  | Cost: $2.31  

AGENTGPT OVERHEAD
- Redaction Time: 32ms avg  
- Compliance Checks: 0.1% failed  
- Regional Balance: 62% US-East, 38% EU Central  

ALERTS:
- EU Central: 3 responses exceeded 500ms SLA
```

***

#### **5. Best Practices**

1. **Model Version Control**:

```bash
agentgpt assistant version set MedQA-v3 \
  --openai_model asst_medicalV2 \
  --fallback asst_medicalV1
```

2. **Zero-Trust Data Handling**:

```python
self.enable_secure_context(
    sandbox="gvisor",
    data_flow={
        "openai": "redacted_only",
        "storage": "encrypted_persistent"
    }
)
```

3. **Regional Failover**:

```yaml
# Auto-route to alternate region if >2s latency
routing_rules:
  - metric: latency
    threshold: 2000ms
    action: reroute_to:eu-central-med
```

***

#### **6. Troubleshooting**

| **Issue**                    | **Resolution Protocol**                                                                |
| ---------------------------- | -------------------------------------------------------------------------------------- |
| PHI detection false positive | <p>1. Validate redactor patterns<br>2. Use <code>agentgpt phi test --sample</code></p> |
| High OpenAI latency          | <p>1. Check regional endpoint status<br>2. Activate backup model</p>                   |
| Audit log encryption failure | <p>1. Rotate KMS keys<br>2. Replay logs with <code>--decrypt=false</code></p>          |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://agent-gpt.gitbook.io/agent-gpt/examples/openai-assistants.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
