> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mycura.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Best Practices

> Optimize your Cura AI integration for performance and accuracy

## Patient Context

### Use Patient IDs When Possible

Always include a `patientId` when available to leverage stored context and enable audit logs:

```javascript theme={null}
{
  "message": "What are my medication interactions?",
  "patientId": "patient-uuid-123",
  "conversationHistory": []
}
```

**Benefits:**

* Richer, more accurate responses based on patient history
* Complete audit trails for compliance
* Automatic context retrieval from stored patient data

### Phone Number Lookup

When you don't have a patient ID, use phone number lookup in ANY format:

```javascript theme={null}
{
  "message": "What should I know about my prescription?",
  "phone": "5551234567"  // Any format works!
}
```

<Tip>
  Phone numbers can be in ANY format - the system automatically normalizes them:

  * `+15551234567`, `15551234567`, `5551234567`
  * `(555) 123-4567`, `555-123-4567`, etc.

  All formats work equally well!
</Tip>

## Conversation Management

### Provide Compact History

Include the last 5-10 conversation turns for continuity without overwhelming the context:

```javascript theme={null}
{
  "message": "Any side effects I should watch for?",
  "patientId": "patient-uuid-123",
  "conversationHistory": [
    {"role": "user", "content": "I was prescribed Lisinopril"},
    {"role": "assistant", "content": "Lisinopril is an ACE inhibitor..."},
    {"role": "user", "content": "What's the typical dosage?"},
    {"role": "assistant", "content": "Typical starting dose is 10mg..."}
  ]
}
```

### Conversation History Format

Each conversation entry should include:

* `role`: Either `"user"` or `"assistant"`
* `content`: The message content as a string

## Performance Optimization

### Client-Side Caching

Cache responses for repeated prompts to reduce latency:

```javascript theme={null}
const cache = new Map();

async function getCachedResponse(message, patientId) {
  const cacheKey = `${patientId}-${message}`;
  
  if (cache.has(cacheKey)) {
    return cache.get(cacheKey);
  }
  
  const response = await callCuraAPI(message, patientId);
  cache.set(cacheKey, response);
  
  return response;
}
```

### Request Batching

For multiple related questions, consider the conversation flow rather than making separate requests:

```javascript theme={null}
// Instead of multiple separate requests
// Better: Structure as a conversation
{
  "message": "I also wanted to ask about exercise restrictions",
  "patientId": "patient-uuid-123",
  "conversationHistory": [
    {"role": "user", "content": "What side effects should I expect from Lisinopril?"},
    {"role": "assistant", "content": "Common side effects include..."}
  ]
}
```

## Error Handling

### Implement Robust Error Handling

```javascript theme={null}
async function callCuraAPI(message, options = {}) {
  try {
    const response = await fetch(`${baseUrl}/api/cura/chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': apiKey
      },
      body: JSON.stringify({
        message,
        ...options
      })
    });

    if (!response.ok) {
      throw new Error(`API Error ${response.status}: ${await response.text()}`);
    }

    const data = await response.json();
    
    if (!data.success) {
      throw new Error(`Cura API Error: ${data.error || 'Unknown error'}`);
    }

    return data.response;
  } catch (error) {
    console.error('Cura API call failed:', error);
    throw error;
  }
}
```

### Handle Network Errors

Implement retry logic for network failures:

```javascript theme={null}
async function callWithRetry(apiCall, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await apiCall();
    } catch (error) {
      if (error.message.includes('network') && attempt < maxRetries) {
        const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      throw error;
    }
  }
}
```

## Data Management

### Patient Data Override

Use `patientData` to provide or override specific patient information:

```javascript theme={null}
{
  "message": "What should I know about this medication?",
  "patientId": "patient-uuid-123",
  "patientData": {
    "medications": [
      {
        "name": "Lisinopril",
        "dosage": "10mg",
        "condition": "Hypertension"
      }
    ],
    "allergies": ["Penicillin"],
    "conditions": ["Hypertension", "Type 2 Diabetes"]
  }
}
```

### Provide Updated Patient Data

Use the `patientData` parameter to provide the most current information:

```javascript theme={null}
// Include updated medications in chat request
await fetch(`${baseUrl}/api/cura/chat`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': apiKey
  },
  body: JSON.stringify({
    message: 'What should I know about my new prescription?',
    patientId: patientId,
    patientData: {
      medications: updatedMedications
    }
  })
});
```

## Security Considerations

### API Key Management

* Store API keys in environment variables
* Use different keys for different environments
* Rotate keys regularly
* Never expose keys in client-side code

### Data Privacy

* Only send necessary patient information
* Implement proper access controls
* Log API usage for audit purposes
* Follow healthcare data compliance requirements (HIPAA, etc.)

## Monitoring and Logging

### Track API Usage

Monitor your API usage patterns:

```javascript theme={null}
const apiMetrics = {
  totalCalls: 0,
  errorRate: 0,
  averageResponseTime: 0
};

async function monitoredAPICall(message, options) {
  const startTime = Date.now();
  apiMetrics.totalCalls++;
  
  try {
    const result = await callCuraAPI(message, options);
    const responseTime = Date.now() - startTime;
    apiMetrics.averageResponseTime = 
      (apiMetrics.averageResponseTime + responseTime) / 2;
    return result;
  } catch (error) {
    apiMetrics.errorRate = 
      (apiMetrics.errorRate * (apiMetrics.totalCalls - 1) + 1) / apiMetrics.totalCalls;
    throw error;
  }
}
```

### Log Important Events

```javascript theme={null}
// Log successful interactions
console.log('Cura API Response', {
  patientId,
  messageLength: message.length,
  responseTime: Date.now() - startTime,
  timestamp: new Date().toISOString()
});
```

<Warning>
  Be careful not to log sensitive patient information in your application logs.
</Warning>
