Usage Examples
Practical examples and use cases for the Arkangel AI API
Explore practical examples of how to integrate the Arkangel AI API into your applications.
Simple Medical Query
The most basic use case: ask a question and get an answer.
async function askMedicalQuestion(question) {
const response = await fetch('https://api.arkangelai.com/v1/chat', {
method: 'POST',
headers: {
'Authorization': 'Bearer your_api_key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: question,
language: 'en'
})
});
const data = await response.json();
return data.message;
}
// Usage
const answer = await askMedicalQuestion(
'What are the common side effects of ibuprofen?'
);
console.log(answer);
Chat with History
Maintain a conversation with full context.
class MedicalChat {
constructor(apiKey) {
this.apiKey = apiKey;
this.conversationId = null;
}
async sendMessage(message) {
const body = { message };
if (this.conversationId) {
body.conversation_id = this.conversationId;
}
const response = await fetch('https://api.arkangelai.com/v1/chat', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
const data = await response.json();
this.conversationId = data.conversation_id;
return data.message;
}
reset() {
this.conversationId = null;
}
}
// Usage
const chat = new MedicalChat('your_api_key');
await chat.sendMessage('What is hypertension?');
await chat.sendMessage('What are its symptoms?');
await chat.sendMessage('How can it be prevented?');
Document Analysis
Upload a medical document and ask questions about it.
async function analyzeDocument(file, question) {
// 1. Upload the file
const formData = new FormData();
formData.append('file', file);
formData.append('purpose', 'analysis');
const uploadResponse = await fetch('https://api.arkangelai.com/v1/files', {
method: 'POST',
headers: {
'Authorization': 'Bearer your_api_key'
},
body: formData
});
const uploadData = await uploadResponse.json();
// 2. Query with the file
const chatResponse = await fetch('https://api.arkangelai.com/v1/chat', {
method: 'POST',
headers: {
'Authorization': 'Bearer your_api_key',
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: question,
file_ids: [uploadData.file_id]
})
});
return chatResponse.json();
}
// Usage
const result = await analyzeDocument(
pdfFile,
'Summarize the main findings of this study'
);
Real-Time Streaming
Display responses as they are generated.
async function streamResponse(message, onChunk) {
const response = await fetch('https://api.arkangelai.com/v1/chat/stream', {
method: 'POST',
headers: {
'Authorization': 'Bearer your_api_key',
'Content-Type': 'application/json'
},
body: JSON.stringify({ message })
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
onChunk(chunk);
}
}
// Usage with React
function ChatComponent() {
const [response, setResponse] = useState('');
const handleSubmit = async (question) => {
setResponse('');
await streamResponse(question, (chunk) => {
setResponse(prev => prev + chunk);
});
};
return <div>{response}</div>;
}
Python Integration
Complete example using Python.
import requests
from typing import Optional
class ArkangelClient:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = 'https://api.arkangelai.com/v1'
self.conversation_id: Optional[str] = None
def _headers(self):
return {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json'
}
def chat(self, message: str, new_conversation: bool = False) -> dict:
if new_conversation:
self.conversation_id = None
payload = {'message': message}
if self.conversation_id:
payload['conversation_id'] = self.conversation_id
response = requests.post(
f'{self.base_url}/chat',
headers=self._headers(),
json=payload
)
response.raise_for_status()
data = response.json()
self.conversation_id = data.get('conversation_id')
return data
def upload_file(self, file_path: str) -> str:
with open(file_path, 'rb') as f:
response = requests.post(
f'{self.base_url}/files',
headers={'Authorization': f'Bearer {self.api_key}'},
files={'file': f},
data={'purpose': 'analysis'}
)
response.raise_for_status()
return response.json()['file_id']
def get_usage(self) -> dict:
response = requests.get(
f'{self.base_url}/usage',
headers=self._headers()
)
response.raise_for_status()
return response.json()
# Usage
client = ArkangelClient('your_api_key')
# Simple chat
response = client.chat('What is cholesterol?')
print(response['message'])
# Continued conversation
client.chat('What are normal values?')
client.chat('How can it be reduced?')
# Check usage
usage = client.get_usage()
print(f"Requests today: {usage['usage']['total_requests']}")
Error Handling
Implement robust error handling.
async function safeApiCall(endpoint, options) {
const maxRetries = 3;
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(endpoint, options);
if (response.status === 429) {
// Rate limit - wait and retry
const retryAfter = response.headers.get('Retry-After') || 60;
await sleep(retryAfter * 1000);
continue;
}
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || 'API error');
}
return response.json();
} catch (error) {
lastError = error;
if (i < maxRetries - 1) {
await sleep(1000 * (i + 1)); // Exponential backoff
}
}
}
throw lastError;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
Next Steps
- HTTP Reference - Complete endpoint documentation
- Support - Get additional help