Welcome to the Lilith API! This guide will help you get up and running with our AI-powered wisdom platform in just a few minutes.
Prerequisites#
Before you begin, ensure you have:
- A Lilith developer account (sign up here)
- Basic understanding of REST APIs and JSON
- An HTTP client (cURL, Postman, or your preferred programming language)
System Requirements#
- API Version: v1 (current)
- Transport: HTTPS only (TLS 1.2+)
- Format: JSON request/response bodies
- Authentication: JWT Bearer tokens
- Rate Limits: 1000 requests/hour (upgradeable)
API Keys#
1. Create Your API Key#
- Log in to the Lilith Developer Dashboard
- Navigate to API Keys in the sidebar
- Click Generate New Key
- Choose your key permissions:
- Read: Access chat, lectures, and content
- Write: Submit content for ingestion
- Admin: Access test endpoints (staff only)
- Copy and securely store your API key
2. Key Management Best Practices#
- Never commit API keys to version control
- Store keys in environment variables or secure config files
- Rotate keys regularly (recommended: every 90 days)
- Use different keys for development, staging, and production
- Monitor key usage in the dashboard
# Environment variable example
export LILITH_API_KEY="your_api_key_here"
Authentication#
The Lilith API uses JWT (JSON Web Token) authentication. Include your token in
the Authorization header of every API request.
Authentication Flow#
# 1. Authenticate and get JWT token
curl -X POST "https://api.lilith.app/v1/auth/login" \
-H "Content-Type: application/json" \
-d '{
"email": "your-email@example.com",
"password": "your-secure-password"
}'
// JavaScript/Node.js example
const response = await fetch('https://api.lilith.app/v1/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'your-email@example.com',
password: 'your-secure-password',
}),
});
const auth = await response.json();
const token = auth.token;
// Kotlin example
val client = OkHttpClient()
val json = """
{
"email": "your-email@example.com",
"password": "your-secure-password"
}
""".trimIndent()
val body = json.toRequestBody("application/json".toMediaType())
val request = Request.Builder()
.url("https://api.lilith.app/v1/auth/login")
.post(body)
.build()
val response = client.newCall(request).execute()
val authData = response.body?.string()
// Swift example
let url = URL(string: "https://api.lilith.app/v1/auth/login")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let loginData: [String: Any] = [
"email": "your-email@example.com",
"password": "your-secure-password"
]
request.httpBody = try JSONSerialization.data(withJSONObject: loginData)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
// Handle authentication response
}
task.resume()
Using Your JWT Token#
Once authenticated, include the JWT token in all subsequent requests:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
First API Call#
Let's make your first API call to check system health and verify your setup:
Health Check#
curl -X GET "https://api.lilith.app/v1/health" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
const healthResponse = await fetch('https://api.lilith.app/v1/health', {
headers: {
Authorization: `Bearer ${token}`,
},
});
const health = await healthResponse.json();
console.log('API Status:', health.status);
val request = Request.Builder()
.url("https://api.lilith.app/v1/health")
.addHeader("Authorization", "Bearer $token")
.build()
val response = client.newCall(request).execute()
println("API Status: ${response.body?.string()}")
var request = URLRequest(url: URL(string: "https://api.lilith.app/v1/health")!)
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
print("API Status: \(String(data: data, encoding: .utf8) ?? "")")
}
}
task.resume()
Expected Response:
{
"status": "ok",
"uptime_s": 86400,
"version": "1.0.0",
"services": {
"chat": "healthy",
"tts": "healthy",
"ingestion": "healthy"
}
}
Your First Chat Interaction#
Now let's create a simple chat interaction with an AI wisdom persona:
curl -X POST "https://api.lilith.app/v1/chat" \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"persona": "zen_master",
"input": {
"text": "What is the essence of mindfulness?"
},
"mode": "text",
"options": {
"cite": true,
"depth": "practical",
"stream": false
}
}'
const chatResponse = await fetch('https://api.lilith.app/v1/chat', {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
persona: 'zen_master',
input: {
text: 'What is the essence of mindfulness?',
},
mode: 'text',
options: {
cite: true,
depth: 'practical',
stream: false,
},
}),
});
const chat = await chatResponse.json();
console.log('AI Response:', chat.text);
val chatJson = """
{
"persona": "zen_master",
"input": {
"text": "What is the essence of mindfulness?"
},
"mode": "text",
"options": {
"cite": true,
"depth": "practical",
"stream": false
}
}
""".trimIndent()
val chatBody = chatJson.toRequestBody("application/json".toMediaType())
val chatRequest = Request.Builder()
.url("https://api.lilith.app/v1/chat")
.addHeader("Authorization", "Bearer $token")
.post(chatBody)
.build()
val chatResponse = client.newCall(chatRequest).execute()
println("AI Response: ${chatResponse.body?.string()}")
let chatData: [String: Any] = [
"persona": "zen_master",
"input": [
"text": "What is the essence of mindfulness?"
],
"mode": "text",
"options": [
"cite": true,
"depth": "practical",
"stream": false
]
]
var chatRequest = URLRequest(url: URL(string: "https://api.lilith.app/v1/chat")!)
chatRequest.httpMethod = "POST"
chatRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
chatRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
chatRequest.httpBody = try JSONSerialization.data(withJSONObject: chatData)
let chatTask = URLSession.shared.dataTask(with: chatRequest) { data, response, error in
if let data = data {
let chatResult = try? JSONSerialization.jsonObject(with: data)
print("AI Response: \(chatResult)")
}
}
chatTask.resume()
Expected Response:
{
"message_id": "msg_abc123",
"conversation_id": "conv_def456",
"text": "The essence of mindfulness lies in bringing your full attention to the present moment, without judgment. It's about observing your thoughts, feelings, and sensations as they arise, acknowledging them with kindness, and gently returning your focus to the here and now.",
"citations": [
{
"source_uri": "buddhist_teachings.pdf",
"span": { "start": 0, "end": 85 },
"confidence": 0.95,
"license": "CC-BY-SA-4.0"
}
],
"audio_url": null
}
Error Handling#
The Lilith API uses standard HTTP status codes and provides detailed error information:
Common Error Responses#
400 Bad Request#
{
"code": "VALIDATION_ERROR",
"message": "Required field 'persona' is missing from the request",
"details": {
"field": "persona",
"provided": null,
"expected": "string (zen_master, philosopher, stoic, mystic, teacher)"
},
"trace_id": "550e8400-e29b-41d4-a716-446655440000"
}
401 Unauthorized#
{
"code": "INVALID_TOKEN",
"message": "JWT token is expired or invalid",
"trace_id": "550e8400-e29b-41d4-a716-446655440001"
}
429 Rate Limited#
{
"code": "RATE_LIMIT_EXCEEDED",
"message": "API rate limit exceeded. Please retry after 60 seconds.",
"details": {
"limit": 1000,
"remaining": 0,
"reset_time": "2023-12-01T13:00:00Z"
},
"trace_id": "550e8400-e29b-41d4-a716-446655440002"
}
Error Handling Best Practices#
async function makeAPICall(endpoint, data) {
try {
const response = await fetch(`https://api.lilith.app${endpoint}`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
const error = await response.json();
switch (response.status) {
case 400:
console.error('Validation Error:', error.message);
break;
case 401:
console.error('Authentication Error:', error.message);
// Refresh token or redirect to login
break;
case 429:
console.error('Rate Limit Exceeded:', error.message);
// Wait and retry after the specified time
break;
case 500:
console.error(
'Server Error:',
error.message,
'Trace ID:',
error.trace_id
);
// Log trace_id for support
break;
default:
console.error('API Error:', error.message);
}
throw new Error(`API Error: ${error.message}`);
}
return await response.json();
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}
Rate Limits#
The Lilith API implements rate limiting to ensure fair usage and system stability:
Rate Limit Details#
| Plan | Requests/Hour | Concurrent | Streaming |
|---|---|---|---|
| Free | 1,000 | 5 | 2 |
| Pro | 10,000 | 20 | 10 |
| Enterprise | 100,000+ | 100+ | 50+ |
Rate Limit Headers#
Every API response includes rate limit information:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1701432000
Retry-After: 3600
Handling Rate Limits#
function handleRateLimit(response) {
const remaining = parseInt(response.headers.get('X-RateLimit-Remaining'));
const reset = parseInt(response.headers.get('X-RateLimit-Reset'));
if (remaining < 10) {
const resetTime = new Date(reset * 1000);
console.warn(
`Rate limit warning: ${remaining} requests remaining until ${resetTime}`
);
}
if (response.status === 429) {
const retryAfter = parseInt(response.headers.get('Retry-After'));
console.log(`Rate limited. Retry after ${retryAfter} seconds`);
// Implement exponential backoff
setTimeout(() => {
// Retry the request
}, retryAfter * 1000);
}
}
Environment Setup#
Development Environment#
# Set environment variables
export LILITH_API_BASE_URL="https://staging-api.lilith.app"
export LILITH_API_TOKEN="your_staging_token"
export LILITH_DEBUG="true"
Production Environment#
# Production settings
export LILITH_API_BASE_URL="https://api.lilith.app"
export LILITH_API_TOKEN="your_production_token"
export LILITH_DEBUG="false"
Configuration File Example#
{
"development": {
"baseURL": "https://staging-api.lilith.app",
"timeout": 30000,
"debug": true,
"retryAttempts": 3
},
"production": {
"baseURL": "https://api.lilith.app",
"timeout": 10000,
"debug": false,
"retryAttempts": 5
}
}
Next Steps#
Congratulations! You've successfully made your first API calls. Here's what to explore next:
π Core Features#
- Chat Integration - Build conversational AI experiences
- Audio Streaming - Add voice synthesis and streaming
- WebSocket API - Real-time bidirectional communication
π Advanced Topics#
- Authentication Guide - Detailed authentication patterns
- Offline Support - Building offline-capable applications
- Error Handling - Comprehensive error reference
π οΈ SDKs and Tools#
- TypeScript SDK - Official TypeScript/JavaScript SDK
- Android SDK - Native Android integration
- iOS SDK - Native iOS integration
π Examples and Tutorials#
- Authentication Flow - Complete auth implementation
- Chat Conversation - Building chat interfaces
- Audio Streaming - Voice-enabled applications
π§ Development Tools#
- Postman Collection - Ready-to-use API collection
- OpenAPI Specification - Complete API schema
- Mock Server - Test without affecting production
π¬ Support and Community#
- Community Forum - Connect with other developers
- GitHub Issues - Report bugs and request features
- Discord Server - Real-time chat with the community
- Email Support - Direct support from our team
π Monitoring and Analytics#
- Developer Dashboard - Monitor usage and manage keys
- Status Page - Real-time system status
- API Metrics - Performance analytics
Quick Reference#
Base URLs#
- Production:
https://api.lilith.app - Staging:
https://staging-api.lilith.app - Mock Server:
https://mock-api.lilith.app
Essential Endpoints#
| Endpoint | Method | Description |
|---|---|---|
/v1/health |
GET | System health check |
/v1/auth/login |
POST | User authentication |
/v1/chat |
POST | Chat with AI personas |
/v1/lectures |
POST | Generate wisdom lectures |
/v1/tts/synthesize |
POST | Text-to-speech synthesis |
HTTP Headers#
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json
Accept: application/json
User-Agent: YourApp/1.0.0
Response Formats#
- Success: HTTP 200/201 with JSON response
- Client Error: HTTP 4xx with error details
- Server Error: HTTP 5xx with trace ID
- Streaming:
text/event-streamfor real-time data
Ready to build something amazing? Let's get started! π