Python Examples
Complete examples for integrating DocBit AI into your Python application.Installation
Copy
pip install requests
Basic Client
Copy
import os
import requests
from typing import List, Optional, Dict, Any
class DocBitClient:
def __init__(self, api_key: str = None):
self.api_key = api_key or os.environ.get('DOCBIT_API_KEY')
self.base_url = 'https://api.docbit.ai'
def _headers(self, org_id: str, user_id: str, roles: List[str]) -> Dict[str, str]:
return {
'Authorization': f'ApiKey {self.api_key}',
'Content-Type': 'application/json',
'X-External-Org-Id': org_id,
'X-External-User-Id': user_id,
'X-External-Roles': ','.join(roles)
}
def chat(
self,
org_id: str,
user_id: str,
roles: List[str],
message: str,
conversation_id: Optional[str] = None
) -> Dict[str, Any]:
response = requests.post(
f'{self.base_url}/api/ai/chat',
json={
'message': message,
'conversationId': conversation_id
},
headers=self._headers(org_id, user_id, roles)
)
response.raise_for_status()
return response.json()
# Usage
client = DocBitClient()
answer = client.chat(
org_id='acme',
user_id='user-456',
roles=['hr', 'all-staff'],
message='What is our vacation policy?'
)
print(answer['content'])
Streaming Chat
Copy
import json
def stream_chat(
client: DocBitClient,
org_id: str,
user_id: str,
roles: List[str],
message: str
):
response = requests.post(
f'{client.base_url}/api/ai/chat/stream',
json={'message': message},
headers=client._headers(org_id, user_id, roles),
stream=True
)
response.raise_for_status()
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
data = json.loads(line[6:])
yield data
# Usage
for event in stream_chat(client, 'acme', 'user-456', ['employee'], 'What are the benefits?'):
if 'token' in event:
print(event['token'], end='', flush=True)
elif 'citations' in event:
print('\n\nCitations:', event['citations'])
Upload Document
Copy
def upload_document(
client: DocBitClient,
org_id: str,
user_id: str,
roles: List[str],
file_path: str,
acl_roles: List[str] = None
) -> Dict[str, Any]:
with open(file_path, 'rb') as f:
files = {'file': f}
data = {}
if acl_roles:
data['aclRoles'] = acl_roles
headers = client._headers(org_id, user_id, roles)
del headers['Content-Type'] # Let requests set multipart
response = requests.post(
f'{client.base_url}/api/documents/upload',
files=files,
data=data,
headers=headers
)
response.raise_for_status()
return response.json()
# Upload HR document
upload_document(
client,
'acme',
'admin-1',
['admin'],
'./hr-policy.pdf',
acl_roles=['hr']
)
FastAPI Integration
Copy
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel
app = FastAPI()
class AskRequest(BaseModel):
question: str
class User(BaseModel):
id: str
org_id: str
roles: List[str]
async def get_current_user() -> User:
# Your auth logic here
return User(id='user-456', org_id='acme', roles=['employee'])
@app.post('/ask')
async def ask(request: AskRequest, user: User = Depends(get_current_user)):
try:
client = DocBitClient()
result = client.chat(
org_id=user.org_id,
user_id=user.id,
roles=user.roles,
message=request.question
)
return result
except requests.HTTPError as e:
raise HTTPException(
status_code=e.response.status_code,
detail=e.response.json().get('error', 'API Error')
)
Django Integration
Copy
# views.py
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
import json
@login_required
@require_POST
def ask_question(request):
client = DocBitClient()
data = json.loads(request.body)
# Get roles from your user model
user = request.user
roles = list(user.groups.values_list('name', flat=True))
try:
result = client.chat(
org_id=user.organization.id,
user_id=str(user.id),
roles=roles,
message=data['question']
)
return JsonResponse(result)
except requests.HTTPError as e:
return JsonResponse(
{'error': e.response.json().get('error')},
status=e.response.status_code
)
Error Handling
Copy
from requests.exceptions import HTTPError
import time
def safe_chat(client, org_id, user_id, roles, message, retries=3):
for attempt in range(retries):
try:
return client.chat(org_id, user_id, roles, message)
except HTTPError as e:
status = e.response.status_code
if status == 429: # Rate limited
wait = 2 ** attempt
print(f'Rate limited, waiting {wait}s...')
time.sleep(wait)
continue
elif status == 401:
raise Exception('Authentication failed. Check API key.')
elif status == 400:
error = e.response.json().get('error', 'Bad request')
raise Exception(f'Bad request: {error}')
else:
raise
raise Exception('Max retries exceeded')
Async Client
Copy
import aiohttp
import asyncio
class AsyncDocBitClient:
def __init__(self, api_key: str = None):
self.api_key = api_key or os.environ.get('DOCBIT_API_KEY')
self.base_url = 'https://api.docbit.ai'
async def chat(
self,
org_id: str,
user_id: str,
roles: List[str],
message: str
) -> Dict[str, Any]:
async with aiohttp.ClientSession() as session:
async with session.post(
f'{self.base_url}/api/ai/chat',
json={'message': message},
headers={
'Authorization': f'ApiKey {self.api_key}',
'Content-Type': 'application/json',
'X-External-Org-Id': org_id,
'X-External-User-Id': user_id,
'X-External-Roles': ','.join(roles)
}
) as response:
response.raise_for_status()
return await response.json()
# Usage
async def main():
client = AsyncDocBitClient()
result = await client.chat('acme', 'user-456', ['hr'], 'What is the policy?')
print(result['content'])
asyncio.run(main())