MedhaOS Integration Guide
This guide explains how to integrate MedhaOS into your web application using the JavaScript SDK.
Table of Contents
- Quick Start
- Installation
- Authentication
- Chat Integration
- Semantic Search
- Embeddable Widget
- Error Handling
- Best Practices
Quick Start
1. Get Your API Keys
First, onboard your tenant to get API keys:
curl -X POST https://api.medhaos.com/api/v1/onboard \
-H "Content-Type: application/json" \
-d '{
"name": "Your Company",
"domain": "yourdomain.com",
"email": "admin@yourdomain.com"
}'
Response:
{
"success": true,
"data": {
"tenant_id": "uuid-here",
"api_key_public": "medha_pk_...",
"api_key_secret": "medha_sk_...",
"endpoint": "https://api.medhaos.com/api/v1"
}
}
Same request in other technologies:
curl -X POST https://api.medhaos.com/api/v1/onboard \
-H "Content-Type: application/json" \
-d '{
"name": "Your Company",
"domain": "yourdomain.com",
"email": "admin@yourdomain.com"
}'
2. Install SDK
npm install @medha-os/sdk
3. Initialize Client
import { MedhaClient } from '@medha-os/sdk';
const client = new MedhaClient({
apiKey: 'your-api-key-public', // Use public key for browser
endpoint: 'https://api.medhaos.com/api/v1'
});
Installation
NPM
npm install @medha-os/sdk
CDN (for widget)
<script src="https://cdn.medhaos.com/sdk.js"
data-medha-tenant="YOUR_TENANT_ID"
data-medha-key="YOUR_PUBLIC_KEY"></script>
Authentication
MedhaOS uses API key authentication. Include your API key in requests:
Browser (Public Key)
Use the public key (medha_pk_*) for browser-based integrations:
const client = new MedhaClient({
apiKey: 'medha_pk_your_tenant_key', // Public key
endpoint: 'https://api.medhaos.com/api/v1'
});
Server (Secret Key)
Use the secret key (medha_sk_*) for server-to-server calls:
// Node.js example
const client = new MedhaClient({
apiKey: 'medha_sk_your_tenant_key', // Secret key
endpoint: 'https://api.medhaos.com/api/v1'
});
Chat Integration
Basic Chat
const response = await client.chat({
message: 'What is this document about?',
file_id: 'file_123' // optional
});
console.log(response.response);
// "This document is about..."
Chat with Context
const response = await client.chat({
message: 'Summarize the key points',
context: {
user_id: 'user_123',
session_id: 'session_456'
}
});
Streaming (if supported)
const response = await client.chat({
message: 'Explain this concept',
stream: true
});
Semantic Search
Basic Search
const results = await client.semanticSearch({
query: 'invoice processing workflow',
limit: 10
});
results.results.forEach(result => {
console.log(result.content);
console.log(`Score: ${result.score}`);
console.log(`Metadata:`, result.metadata);
});
Search with Filters
const results = await client.semanticSearch({
query: 'customer support',
limit: 20,
filters: {
category: 'support',
date_range: '2024-01-01:2024-12-31'
}
});
Embeddable Widget
The easiest way to add MedhaOS chat to your website is using the embeddable widget:
Script Tag
<script src="https://cdn.medhaos.com/sdk.js"
data-medha-tenant="YOUR_TENANT_ID"
data-medha-key="YOUR_PUBLIC_KEY"
data-medha-endpoint="https://api.medhaos.com/api/v1"
data-medha-position="bottom-right"></script>
Attributes
data-medha-tenant: Your tenant ID (required)data-medha-key: Your public API key (required)data-medha-endpoint: API endpoint (optional, defaults to current domain)data-medha-position: Widget position -bottom-right,bottom-left,top-right,top-left(optional, default:bottom-right)
Programmatic Initialization
import { MedhaChatWidget } from '@medha-os/sdk';
const widget = new MedhaChatWidget({
tenant: 'your-tenant-id',
key: 'your-public-key',
endpoint: 'https://api.medhaos.com/api/v1',
position: 'bottom-right'
});
Error Handling
The SDK throws MedhaOSError for API errors:
import { MedhaOSError } from '@medha-os/sdk';
try {
const response = await client.chat({ message: 'Hello' });
} catch (error) {
if (error instanceof MedhaOSError) {
console.error('MedhaOS Error:', error.message);
console.error('Status Code:', error.statusCode);
console.error('Error Code:', error.errorCode);
// Handle specific errors
if (error.statusCode === 401) {
// Invalid API key
} else if (error.statusCode === 429) {
// Rate limit exceeded
}
} else {
// Network or other errors
console.error('Unexpected error:', error);
}
}
Common Error Codes
AUTHENTICATION_ERROR(401): Invalid or missing API keyRATE_LIMIT_EXCEEDED(429): Too many requestsVALIDATION_ERROR(400): Invalid request parametersNOT_FOUND(404): Resource not foundINTERNAL_ERROR(500): Server error
Best Practices
1. API Key Security
- Never expose secret keys in client-side code
- Use public keys for browser integrations
- Store secret keys securely on your server
- Rotate keys regularly via settings page
2. Rate Limiting
MedhaOS enforces rate limits:
- Chat: 100 requests/minute per tenant
- Search: 200 requests/minute per tenant
- Extraction: 50 requests/minute per tenant
The SDK automatically retries with exponential backoff for transient errors.
3. Error Handling
Always handle errors gracefully:
try {
const response = await client.chat({ message: userInput });
displayResponse(response.response);
} catch (error) {
if (error instanceof MedhaOSError) {
showError(`API Error: ${error.message}`);
} else {
showError('Network error. Please try again.');
}
}
4. Domain Registration
Register all domains that will make API calls:
curl -X POST https://api.medhaos.com/api/v1/onboard/domains \
-H "X-API-Key: your-secret-key" \
-H "Content-Type: application/json" \
-d '{
"domain": "app.yourdomain.com",
"origin": "https://app.yourdomain.com"
}'
5. CORS Configuration
CORS is automatically enforced based on registered domains. Ensure your domain is registered before making browser requests.
Examples
React Component
import { useState } from 'react';
import { MedhaClient } from '@medha-os/sdk';
function ChatComponent() {
const [message, setMessage] = useState('');
const [response, setResponse] = useState('');
const [loading, setLoading] = useState(false);
const client = new MedhaClient({
apiKey: process.env.NEXT_PUBLIC_MEDHA_API_KEY!,
endpoint: process.env.NEXT_PUBLIC_MEDHA_ENDPOINT!
});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
try {
const result = await client.chat({ message });
setResponse(result.response);
} catch (error) {
console.error('Chat error:', error);
} finally {
setLoading(false);
}
};
return (
<form onSubmit={handleSubmit}>
<input
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Ask a question..."
/>
<button type="submit" disabled={loading}>
Send
</button>
{response && <div>{response}</div>}
</form>
);
}
Node.js Server
import { MedhaClient } from '@medha-os/sdk';
const client = new MedhaClient({
apiKey: process.env.MEDHA_SECRET_KEY!, // Use secret key on server
endpoint: process.env.MEDHA_ENDPOINT!
});
// Express route example
app.post('/api/chat', async (req, res) => {
try {
const result = await client.chat({
message: req.body.message,
file_id: req.body.file_id
});
res.json(result);
} catch (error) {
res.status(500).json({ error: 'Chat failed' });
}
});
Support
For issues or questions:
- Check the API Documentation
- Review Use Cases
- Contact support: support@medhaos.com
License
Proprietary - © 2025 SASTRA INNOVATIONS (OPC) PRIVATE LIMITED