API Reference

Complete reference for all 15 AI modalities and 82 endpoints. Every endpoint uses JSON over REST with JWT authentication.

Authentication

All protected endpoints require a valid JWT token. Obtain one by calling any of the four login endpoints, then include it in every request:

HTTP Header
Authorization: Bearer <your-token>

Tokens are issued for one of four roles: admin, company, employee, or customer. Each role has different access levels, especially for database endpoints.

Making Requests

All endpoints accept and return JSON unless otherwise noted (e.g. file uploads use multipart/form-data, document downloads return binary). The base URL for all requests is:

Base URL
https://api.jamiiai.com

Interactive Swagger documentation is available at /docs when running the API server.

AI Chat

Conversational AI powered by GPT-4o-mini with persistent conversation history, custom system prompts, and streaming support. Each user session maintains its own conversation context.

POST /chat Bearer

Send a message and receive an AI-generated response. The conversation history is maintained server-side.

Request Body

FieldTypeRequiredDescription
messagestringYesThe message to send to the AI

Response

JSON
{
  "response": "Quantum computing uses qubits..."
}
GET /chat/history Bearer

Return the full conversation history for the current session.

Response

JSON
{
  "history": [
    {"role": "user", "content": "Hello"},
    {"role": "assistant", "content": "Hi! How can I help?"}
  ]
}
POST /chat/reset Bearer

Clear the conversation history and start fresh.

Response

JSON
{"message": "Conversation history cleared"}
PUT /chat/system-prompt Bearer

Update the system prompt that guides the AI's behaviour.

Request Body

FieldTypeRequiredDescription
promptstringYesThe new system prompt

Response

JSON
{"message": "System prompt updated", "prompt": "You are a pirate..."}

Voice Chat

Full audio pipeline β€” speech-to-text transcription with OpenAI Whisper, text-to-speech synthesis, and end-to-end audio conversations. Upload audio files and receive text or audio responses.

POST /voice/audio-to-audio Bearer

Send audio, get transcription + AI text response + audio response. Full STT β†’ Chat β†’ TTS pipeline.

Request

multipart/form-data with a file field containing the audio file.

Response

JSON
{
  "transcription": "What is AI?",
  "response": "AI stands for...",
  "audio": "<base64-encoded MP3>"
}
POST /voice/speech-to-text Bearer

Transcribe an audio file to text using OpenAI Whisper.

Request

multipart/form-data with a file field.

Response

JSON
{"text": "Hello, how are you?"}
POST /voice/text-to-speech Bearer

Convert text to MP3 audio using OpenAI TTS.

Request Body

FieldTypeRequiredDescription
textstringYesText to synthesize

Response

Binary MP3 audio (audio/mpeg).

POST /voice/text-to-audio Bearer

Send text, get AI text response + audio response (Chat β†’ TTS).

Request Body

FieldTypeRequiredDescription
textstringYesMessage to send

Response

JSON
{
  "response": "Here is my answer...",
  "audio": "<base64-encoded MP3>"
}

Video Chat

Extract audio and frames from uploaded videos using ffmpeg. Transcribe video audio, have conversations about video content, and describe video frames with GPT-4 Vision.

POST /video/video-to-audio Bearer

Upload video β†’ extract audio β†’ AI chat β†’ text + audio response.

Request

multipart/form-data with a file field containing the video.

POST /video/video-to-text Bearer

Upload video β†’ extract audio β†’ transcribe to text with Whisper.

POST /video/text-to-video-reply Bearer

Send text β†’ chat β†’ TTS β†’ text + audio response.

Request Body

FieldTypeRequiredDescription
textstringYesMessage to send
POST /video/video-to-description Bearer

Upload video β†’ extract a frame at 1 second β†’ describe with AI Vision.

Code Assistant

Generate, review, explain, and refactor code using AI with task-specific system prompts for focused, high-quality results. Supports all programming languages.

POST /code/generate Bearer

Generate code from a natural-language description.

Request Body

FieldTypeRequiredDescription
descriptionstringYesWhat to generate
languagestringNoTarget language (e.g. "python")
POST /code/review Bearer

Review code and return feedback on bugs, security issues, and improvements.

Request Body

FieldTypeRequiredDescription
codestringYesCode to review
POST /code/explain Bearer

Explain what a piece of code does in plain language.

Request Body

FieldTypeRequiredDescription
codestringYesCode to explain
POST /code/refactor Bearer

Refactor code for better quality, readability, and maintainability.

Request Body

FieldTypeRequiredDescription
codestringYesCode to refactor
instructionsstringNoSpecific refactoring instructions

AI Agent

Autonomous task execution with built-in tools. The agent plans, calls tools, observes results, and iterates until the task is complete. Built-in tools: calculator, datetime_now, text_transform, json_extract.

POST /agent/task Bearer

Submit a task for the AI agent to execute autonomously using tool calling.

Request Body

FieldTypeRequiredDescription
taskstringYesTask description

Response

JSON
{
  "result": "The answer is 15.",
  "tools_available": ["calculator", "datetime_now", "text_transform", "json_extract"]
}
GET /agent/history Bearer

Return the agent's conversation and tool-use history.

POST /agent/reset Bearer

Clear the agent's conversation history.

Image Intelligence

Describe images, answer visual questions with GPT-4 Vision, and generate images from text prompts with DALL-E 3. Supports PNG, JPEG, GIF, and WebP formats.

POST /image/image-to-text Bearer

Describe an uploaded image using OpenAI Vision.

Request

multipart/form-data with a file field.

Response

JSON
{"description": "A sunset over a mountain range..."}
POST /image/image-to-answer Bearer

Answer a specific question about an uploaded image.

Request

multipart/form-data with file and question fields.

POST /image/text-to-image Bearer

Generate an image from a text prompt using DALL-E 3.

Request Body

FieldTypeRequiredDescription
promptstringYesImage description
sizestringNo1024x1024, 1024x1792, or 1792x1024
qualitystringNostandard or hd

Response

JSON
{"url": "https://oaidalleapi...", "prompt": "A cat wearing a top hat"}

Document Generation

Transform text into professional Word documents, PowerPoint presentations, and PDF files β€” ready for download. Uses python-docx, python-pptx, and fpdf2.

POST /document/text-to-word Bearer

Generate a Word document (.docx) from text. Returns binary file download.

Request Body

FieldTypeRequiredDescription
textstringYesDocument content
titlestringNoDocument title
POST /document/text-to-powerpoint Bearer

Generate a PowerPoint presentation (.pptx) from text. Long text is automatically split across slides.

POST /document/text-to-pdf Bearer

Generate a PDF document (.pdf) from text.

Database Intelligence

Ask questions in plain English β€” Jamii AI translates them to SQL, executes securely, and returns human-readable answers. Features four-role row-level access control: admins see everything, employees are restricted to allowed tables, customers are filtered by their own data.

POST /db/chat Bearer

Natural-language database query with row-level access control per role.

Request Body

FieldTypeRequiredDescription
questionstringYesQuestion in plain English

Response

JSON
{"answer": "There were 1,247 orders placed in February."}
GET /db/schema Bearer

Return the database schema (tables and columns).

POST /db/query Admin

Execute a raw SELECT or SHOW query. Admin/company role only.

Request Body

FieldTypeRequiredDescription
querystringYesSQL SELECT or SHOW statement
POST /db/chat/reset Bearer

Clear the DB chatbot conversation history.

POST /db/select_for_customer Bearer

Select a working database after customer login.

GET /db/companies Admin/Employee

List companies the user belongs to.

POST /db/select_for_company Admin/Employee

Select a company database by company number.

Text AI

Translate text between languages, generate summaries with configurable style, analyse sentiment with confidence scores, and extract structured data from unstructured text β€” all powered by GPT.

POST /text/translate Bearer

Translate text to a target language.

Request Body

FieldTypeRequiredDescription
textstringYesText to translate
target_languagestringYesTarget language (e.g. "French")
source_languagestringNoSource language (auto-detected if omitted)

Response

JSON
{"translated": "Bonjour le monde", "target_language": "French"}
POST /text/summarize Bearer

Summarize text with configurable style and length.

Request Body

FieldTypeRequiredDescription
textstringYesText to summarize
max_lengthstringNoTarget length (e.g. "100 words")
stylestringNoSummary style (e.g. "concise", "detailed")

Response

JSON
{"summary": "A concise summary of the input text..."}
POST /text/sentiment Bearer

Analyse text sentiment β€” returns sentiment label, confidence score, and explanation.

Request Body

FieldTypeRequiredDescription
textstringYesText to analyse

Response

JSON
{
  "sentiment": "positive",
  "confidence": 0.95,
  "explanation": "Strong positive language detected"
}
POST /text/extract Bearer

Extract structured data from unstructured text given a schema description.

Request Body

FieldTypeRequiredDescription
textstringYesText to extract from
schema_descriptionstringYesWhat fields to extract (e.g. "name, email, phone")

Response

JSON
{
  "data": {"name": "Alice", "email": "alice@example.com", "phone": "555-1234"}
}

Content Moderation

Detect harmful, hateful, violent, or sexual content instantly with OpenAI's moderation model. Returns per-category flags and confidence scores for fine-grained content filtering.

POST /moderation/check Bearer

Check text for harmful content using the OpenAI Moderation API.

Request Body

FieldTypeRequiredDescription
textstringYesText to moderate

Response

JSON
{
  "flagged": false,
  "categories": {},
  "category_scores": {"violence": 0.0012, "hate": 0.0003}
}

Embeddings

Generate text embedding vectors for semantic search, clustering, and recommendation. Compute cosine similarity between any two texts. Uses OpenAI's text-embedding-3-small model.

POST /embeddings/generate Bearer

Generate an embedding vector for a text string.

Request Body

FieldTypeRequiredDescription
textstringYesText to embed

Response

JSON
{
  "embedding": [0.012, -0.034, 0.056, ...],
  "dimensions": 1536
}
POST /embeddings/similarity Bearer

Compute the cosine similarity between two texts (0 to 1).

Request Body

FieldTypeRequiredDescription
text1stringYesFirst text
text2stringYesSecond text

Response

JSON
{"text1": "cat", "text2": "kitten", "score": 0.92}

Web Intelligence

Fetch any public URL, extract its text content, and get an AI-powered summary or ask specific questions about the page. Includes SSRF protection that blocks private IPs and non-HTTP schemes.

POST /web/summarize Bearer

Fetch a URL and summarize its content, or answer a specific question about it.

Request Body

FieldTypeRequiredDescription
urlstringYesPublic URL to fetch (http/https only)
questionstringNoSpecific question about the page content

Response

JSON
{
  "url": "https://example.com/article",
  "summary": "The article discusses..."
}

Long-term Memory

Store, semantically recall, and manage persistent memories with embedding-based search. Perfect for building context-aware AI assistants that remember user preferences and past interactions.

POST /memory/store Bearer

Store a memory with optional metadata. An embedding vector is generated automatically for semantic recall.

Request Body

FieldTypeRequiredDescription
contentstringYesMemory content to store
metadataobjectNoOptional key-value metadata

Response

JSON
{
  "id": 0,
  "content": "User prefers dark mode",
  "metadata": {"category": "preferences"}
}
POST /memory/recall Bearer

Recall the most relevant memories by semantic similarity to a query.

Request Body

FieldTypeRequiredDescription
querystringYesSearch query
top_kintegerNoMax results to return (default: 5)

Response

JSON
{
  "memories": [
    {"id": 0, "content": "User prefers dark mode", "metadata": {}, "score": 0.92}
  ],
  "count": 1
}
POST /memory/clear Bearer

Clear all stored memories.

Response

JSON
{"message": "All memories cleared"}

Knowledge Base

Namespace-scoped document ingestion (text & URL) with Retrieval-Augmented Generation (RAG) for AI-powered Q&A. Build custom knowledge stores for any web application.

POST /kb/ingest Bearer

Ingest plain text into a knowledge base namespace. Text is automatically chunked and embedded.

Request Body

FieldTypeRequiredDescription
namespacestringYesKnowledge base name (e.g. your app name)
textstringYesText content to ingest
sourcestringNoOptional source label (e.g. filename)

Response

JSON
{"namespace": "my-app", "chunks_added": 3, "source": "faq.md"}
POST /kb/ingest-url Bearer

Fetch a URL, extract text, chunk, embed, and store into a knowledge base. SSRF-protected.

Request Body

FieldTypeRequiredDescription
namespacestringYesKnowledge base name
urlstringYesPublic URL to fetch (http/https only)

Response

JSON
{"namespace": "my-app", "chunks_added": 12, "source": "https://example.com/faq"}
POST /kb/query Bearer

Query a knowledge base with a question. Uses RAG to find relevant chunks and generate an answer.

Request Body

FieldTypeRequiredDescription
namespacestringYesKnowledge base to search
questionstringYesQuestion to answer
top_kintegerNoMax context chunks (default 5, max 20)

Response

JSON
{"answer": "Returns are accepted within 30 days.", "sources": ["faq.md"], "namespace": "my-app"}
GET /kb/list Bearer

List all knowledge base namespaces with their chunk counts.

Response

JSON
{"knowledge_bases": [{"namespace": "my-app", "chunks": 15}]}
POST /kb/clear Bearer

Clear all documents from a knowledge base namespace.

Request Body

FieldTypeRequiredDescription
namespacestringYesKnowledge base to clear

Response

JSON
{"message": "Knowledge base 'my-app' cleared."}

Africa Lang

African language translation & detection, voice STT/TTS with language hints, context-aware chat about African topics, content moderation for African languages, and supported-language listing.

POST /africa/translate Bearer

Translate text between African languages (Swahili, Yoruba, Hausa, Amharic, Wolof, Lingala, Zulu, and more).

Request Body

FieldTypeRequiredDescription
textstringYesText to translate
target_languagestringYesTarget language (e.g. "Swahili")
source_languagestringNoSource language hint

Response

JSON
{"translated": "Habari, u hali gani?", "target_language": "Swahili"}
POST /africa/detect-language Bearer

Detect which African language a text is written in.

Request Body

FieldTypeRequiredDescription
textstringYesText to identify

Response

JSON
{"language": "Swahili", "confidence": 0.95, "script": "Latin", "region": "East Africa"}
GET /africa/languages Bearer

List all supported African languages.

Response

JSON
{"languages": ["Swahili", "Yoruba", "Hausa", "Amharic", "Wolof", "Lingala", "Zulu", "..."]}
POST /africa/transcribe Bearer

Transcribe audio with African language support. Send audio as multipart form data with an optional language hint (ISO-639-1).

Form Fields

FieldTypeRequiredDescription
filefileYesAudio file (mp3, wav, webm)
languagestringNoISO-639-1 code (e.g. "sw", "yo", "ha")

Response

JSON
{"text": "Habari yako"}
POST /africa/synthesize Bearer

Convert African language text to speech. Returns audio/mpeg bytes.

Request Body

FieldTypeRequiredDescription
messagestringYesText to synthesize
POST /africa/chat Bearer

Chat with an AI knowledgeable about African geography, history, cultures, economics, and current affairs.

Request Body

FieldTypeRequiredDescription
messagestringYesQuestion about Africa

Response

JSON
{"response": "Kenya's main exports include tea, coffee, horticultural products, and textiles..."}
POST /africa/chat/reset Bearer

Clear the African context chat conversation history.

Response

JSON
{"message": "African chat history cleared."}
POST /africa/moderate Bearer

Moderate content in African languages, detecting hate speech, tribalism, and misinformation.

Request Body

FieldTypeRequiredDescription
textstringYesText to check

Response

JSON
{"flagged": false, "reason": "", "language_detected": "Swahili", "categories": {"hate_speech": false, "tribalism": false, "misinformation": false, "violence": false, "discrimination": false}}

Africa Life

African currency formatting & conversion, mobile money transaction parsing (M-Pesa, MTN MoMo, Orange Money), agriculture advisory, education & exam prep, and legal & business regulatory guidance.

POST /africa/currency/format Bearer

Format an amount in an African currency (CFA, Naira, Shilling, Rand, Cedi, etc.).

Request Body

FieldTypeRequiredDescription
amountfloatYesNumeric amount
currency_codestringYesISO currency code (e.g. "KES")

Response

JSON
{"formatted": "KSh 1,500.50", "currency_code": "KES", "currency_name": "Kenyan Shilling", "amount": 1500.5}
POST /africa/currency/convert Bearer

Estimate conversion between African currencies.

Request Body

FieldTypeRequiredDescription
amountfloatYesAmount to convert
source_currencystringYesSource ISO code
target_currencystringYesTarget ISO code

Response

JSON
{"source_amount": 1000, "source_currency": "KES", "target_amount": 3150, "target_currency": "NGN", "rate": 3.15, "note": "Approximate rate"}
GET /africa/currencies Bearer

List all supported African currencies.

Response

JSON
{"currencies": {"KES": "Kenyan Shilling", "NGN": "Nigerian Naira", "ZAR": "South African Rand", "...": "..."}}
POST /africa/mobile-money/ask Bearer

Ask a question about mobile money services (M-Pesa, MTN MoMo, Orange Money, Airtel Money, EcoCash).

Request Body

FieldTypeRequiredDescription
questionstringYesQuestion about mobile money

Response

JSON
{"response": "To send money via M-Pesa, dial *334# and follow the prompts..."}
POST /africa/mobile-money/parse Bearer

Parse a mobile money transaction message or USSD code into structured data.

Request Body

FieldTypeRequiredDescription
messagestringYesTransaction SMS or USSD code

Response

JSON
{"provider": "M-Pesa", "transaction_type": "send", "amount": 500, "currency": "KES", "recipient": "+254712345678", "reference": "QH45G7Z2", "status": "completed", "raw_text": "Confirmed. Ksh500 sent to +254712345678"}
POST /africa/agriculture/ask Bearer

Ask about African farming, crops, livestock, and agricultural practices.

Request Body

FieldTypeRequiredDescription
questionstringYesAgriculture question

Response

JSON
{"response": "Cassava is one of the most important crops in Sub-Saharan Africa..."}
POST /africa/education/ask Bearer

Ask education and exam prep questions for African educational systems (WAEC, JAMB, KCSE, BaccalaurΓ©at).

Request Body

FieldTypeRequiredDescription
questionstringYesStudy or exam question
exam_systemstringNoTarget exam system (e.g. WAEC, KCSE)

Response

JSON
{"response": "In the WAEC Biology syllabus, photosynthesis is..."}
POST /africa/legal/ask Bearer

Ask about African business law and regulatory guidance.

Request Body

FieldTypeRequiredDescription
questionstringYesLegal or regulatory question
countrystringNoCountry context (e.g. Nigeria, Kenya)

Response

JSON
{"response": "In Nigeria, the Companies and Allied Matters Act (CAMA) requires..."}

Africa Culture

African proverbs & wisdom by theme or culture, and storytelling β€” folktales, legends, and folklore from across the continent.

POST /africa/proverbs/get Bearer

Get an African proverb by theme or culture.

Request Body

FieldTypeRequiredDescription
themestringNoTopic (e.g. wisdom, patience, unity)
culturestringNoCulture or ethnic group

Response

JSON
{"proverb": "If you want to go fast, go alone...", "language": "Igbo", "culture": "Igbo", "meaning": "...", "theme": "unity"}
POST /africa/storytelling/tell Bearer

Tell an African folktale, legend, or story based on a topic or character.

Request Body

FieldTypeRequiredDescription
topicstringYesStory topic or character
culturestringNoCultural context

Response

JSON
{"story": "Long ago, in the land of the Ashanti..."}

Streaming (SSE)

Real-time token-by-token streaming of chat responses via Server-Sent Events. Ideal for building responsive chat UIs that display text as it's generated.

POST /chat/stream Bearer

Stream a chat response token by token. Returns text/event-stream.

Request Body

FieldTypeRequiredDescription
messagestringYesMessage to send

Response (SSE stream)

Event Stream
data: Once
data: upon
data: a
data: time
data: [DONE]

Batch Processing

Process multiple chat messages in a single API call. Each message is processed independently β€” the chatbot is reset between messages so there's no cross-contamination of context.

POST /batch/chat Bearer

Send multiple messages and receive individual responses for each.

Request Body

FieldTypeRequiredDescription
messagesarray of stringsYesList of messages (min 1)

Response

JSON
{
  "results": ["Answer to first...", "Answer to second..."],
  "count": 2
}

Authentication Endpoints

Four-role JWT authentication with row-level access control. Admins, companies, employees, and customers each get tailored access. All credentials use the customers_credential table with case-insensitive secret_answer matching.

POST /auth/customer/login Public

Customer login β€” validates against customers_credential + customers, requires is_verified = 'yes'.

Request Body

FieldTypeRequiredDescription
usernamestringYesUsername (userN)
secret_answerstringYesSecret answer (case-insensitive)

Response

JSON
{
  "access_token": "eyJhbGciOi...",
  "token_type": "bearer",
  "role": "customer",
  "firstname": "Alice"
}
POST /auth/admin/login Public

Admin login β€” requires company_employee_links.is_admin = 1 and status = 1.

POST /auth/employee/login Public

Employee login β€” requires company_employee_links.status = 1. JWT includes allow_tables_list.

POST /auth/company/login Public

Company login β€” requires customers.type = 'webcompany'. Same access rights as admin.

GET /auth/usage Bearer

Get API usage statistics for the currently authenticated user.

System

System-level endpoints for health checks and monitoring.

GET /health Public

Health check β€” returns API status and version. No authentication required.

Response

JSON
{"status": "ok", "version": "0.1.0"}