NNU Chatbot REST API
The NNU chatbot exposes a small, stable HTTP surface for third-party integrations. This page covers everything you need to embed conversational university search into your own app: the chat endpoint, streaming, domain selection, and citation/source retrieval.
Overview
Base URL for production:
https://chatbot.najahapps.com/api
All endpoints accept and return application/json (UTF-8). The chat endpoint
also supports Server-Sent Events when stream: true is set in the request body.
All responses include a session_id you should echo back on subsequent turns
to keep conversation context coherent.
Authentication
The public chat endpoints require no authentication. They are intended for embedding on third-party sites and are rate-limited per client IP (see Rate limits). If your integration needs higher limits or domain-scoped admin write access, contact the NNU team for an account.
X-Forwarded-For for rate-limit attribution, so requests routed
through a reverse proxy will be metered against the original client IP. Make sure your proxy
forwards that header.
Rate limits
Public API requests are metered per client IP over two fixed windows. The limits are configured by the university administration and may change without notice; the numbers below are the defaults, not a guarantee.
| Limit | Window | Default |
|---|---|---|
| Per-minute | 60 seconds, fixed | 20 requests |
| Per-hour | 3600 seconds, fixed | 200 requests |
Exceeding either limit returns HTTP 429 Too Many Requests with a JSON body of
{"detail": "Rate limit exceeded. Please try again later."}. Counters reset
at the end of their window and no Retry-After header is sent, so back off instead of
polling: the per-minute window clears within a minute, the per-hour window within the hour.
POST/chat
The primary endpoint. Sends a user message and receives a grounded, cited answer.
Request body
| Field | Type | Required | Description |
|---|---|---|---|
message | string | yes | The user's question. Max 500 characters by default. |
session_id | string | no | Opaque session id returned by a previous call. Pass it back to preserve conversation context (last 10 turns). |
lang_hint | string | no | "ar" or "en". Influences answer language. If omitted, the bot auto-detects from the message script. |
domain | string | no | Domain slug (e.g. "fmhs"). Scopes retrieval to that domain's documents. If omitted, all globally-visible content is used. |
stream | boolean | no | If true, response is an SSE stream — see streaming below. |
Response (non-streaming)
{ "session_id": "c3d8d550-3eee-4682-b75c-d1dacba11c33", "answer": "The FMHS Optometry Clinic is located in New Campus, Building 19, Room 19B1020...", "intent": "contact_info", "confidence": 0.92, "citations": [ { "title": "Medical Support for FMHS Students", "document_id": 14, "chunk_id": 231, "effective_date": null, "source_url": "https://fmhs.najah.edu/en/students/students-support/medical-support/", "snippet": "Optometry Clinic delivers specialized diagnostic and treatment service..." } ], "handoff": null, "tool_calls_made": ["search_contacts", "search_knowledge_base"], "tokens_used": 3151, "clarification_needed": null, "follow_up_suggestions": [] }
Examples
curl -X POST https://chatbot.najahapps.com/api/chat \
-H "Content-Type: application/json" \
-d '{
"message": "What are the admission requirements for the MD program?",
"domain": "fmhs",
"lang_hint": "en"
}'
const resp = await fetch("https://chatbot.najahapps.com/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message: "What are the admission requirements for the MD program?",
domain: "fmhs",
lang_hint: "en",
session_id: localStorage.getItem("nnu_chat_session"), // optional
}),
});
const data = await resp.json();
localStorage.setItem("nnu_chat_session", data.session_id); // reuse next turn
console.log(data.answer);
console.log("Sources:", data.citations.map(c => c.title));
import requests
resp = requests.post(
"https://chatbot.najahapps.com/api/chat",
json={
"message": "What are the admission requirements for the MD program?",
"domain": "fmhs",
"lang_hint": "en",
},
timeout=30,
)
data = resp.json()
print(data["answer"])
for c in data["citations"]:
print(" -", c["title"], c.get("source_url"))
POST/chat · streaming
Set stream: true in the request body and the server returns an
text/event-stream response. Each event is one of:
| Event type | Payload | Description |
|---|---|---|
session | { session_id } | Sent first; capture this to reuse on the next turn. |
intent | { intent, confidence } | Once intent classification completes. |
status | { message } | Human-readable progress hint (e.g. "Thinking..."). |
tool_call | { tools: [name, ...] } | Names of tools the agent is about to invoke. |
token | { content: string } | Partial answer text. Append to your buffer in order received. |
done | Full ChatResponse | Final event with the complete answer + citations + tool_calls_made. |
error | { message } | Sent on safety refusal or unrecoverable error. |
// EventSource doesn't support POST, so use fetch + ReadableStream.
const resp = await fetch("https://chatbot.najahapps.com/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json", "Accept": "text/event-stream" },
body: JSON.stringify({
message: "How do I book a counseling appointment?",
domain: "fmhs",
stream: true,
}),
});
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let answer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let idx;
while ((idx = buffer.indexOf("\n\n")) !== -1) {
const raw = buffer.slice(0, idx);
buffer = buffer.slice(idx + 2);
if (!raw.startsWith("data: ")) continue;
const evt = JSON.parse(raw.slice(6));
if (evt.type === "token") answer += evt.content;
if (evt.type === "tool_call") console.log("tools:", evt.tools);
if (evt.type === "done") console.log("final:", evt.answer);
}
}
import json, requests
with requests.post(
"https://chatbot.najahapps.com/api/chat",
json={"message": "How do I book a counseling appointment?", "domain": "fmhs", "stream": True},
stream=True,
headers={"Accept": "text/event-stream"},
timeout=60,
) as resp:
answer = []
for raw in resp.iter_lines(decode_unicode=True):
if not raw or not raw.startswith("data: "):
continue
evt = json.loads(raw[6:])
if evt["type"] == "token":
answer.append(evt["content"])
elif evt["type"] == "tool_call":
print("tools:", evt["tools"])
elif evt["type"] == "done":
print("final answer length:", len(evt["answer"]))
GET/domains/public
Lists all active domains (faculties / units) you can scope the chat to. Each entry's
slug is what you pass as domain in /chat.
curl https://chatbot.najahapps.com/api/domains/public
# response:
[
{ "slug": "fmhs", "name_en": "Faculty of Medicine and Health Sciences",
"name_ar": "كلية الطب وعلوم الصحة" }
]
GET/domain/{slug}/config
Public widget config for a domain. Use this if you're rendering your own UI (rather than embedding the iframe widget) and want to honor the domain's preferred title, subtitle, and brand color.
curl https://chatbot.najahapps.com/api/domain/fmhs/config
# response:
{
"slug": "fmhs",
"name_en": "Faculty of Medicine and Health Sciences",
"name_ar": "كلية الطب وعلوم الصحة",
"widget_title_en": "FMHS Assistant",
"widget_title_ar": "مساعد كلية الطب",
"widget_subtitle_en": "Ask about programs, policies, and student support",
"widget_subtitle_ar": "اسأل عن البرامج والسياسات ودعم الطلاب",
"primary_color": "#1d3e6b"
}
GET/doc/{document_id}
Retrieves the full text of a cited document. Use this to render a "source card"
inline when a user clicks one of the citations from a chat response. Only documents
whose status = "active" are exposed.
The response includes the full document text plus per-chunk character offsets:
curl https://chatbot.najahapps.com/api/doc/14
# response (truncated):
{
"id": 14,
"title": "Medical Support for FMHS Students",
"language": "en",
"raw_text": "# Medical Support for FMHS Students\n\nSeveral medical-support resources...",
"effective_date": null,
"source_url": "https://fmhs.najah.edu/en/students/students-support/medical-support/",
"chunks": [
{ "id": 230, "index": 0, "start_offset": 0, "end_offset": 420 },
{ "id": 231, "index": 1, "start_offset": 350, "end_offset": 870 }
]
}
Schemas
Citation
| Field | Type | Description |
|---|---|---|
title | string | Display name of the source document. |
document_id | int | ID for GET /doc/{id}. |
chunk_id | int | The specific chunk whose content was retrieved. |
effective_date | string? | ISO date if the document carries an effective date. |
source_url | string? | Origin URL on najah.edu, when known. |
snippet | string? | First ~160 characters of the chunk — useful for source cards. |
Handoff
If the bot's safety filter blocks a request, the response carries a handoff object
pointing the user to a human contact (e.g. the admissions office). Otherwise null.
| Field | Type | Description |
|---|---|---|
type | string | Currently always "contact". |
unit | string? | Office name (e.g. "Admissions Office"). |
phone | string? | Phone number. |
email | string? | Email. |
Error codes
| HTTP | When | Body |
|---|---|---|
400 | Validation failed (e.g. message too long). | {"detail": "..."} |
404 | Unknown domain slug or document id. | {"detail": "..."} |
429 | Rate limit exceeded. | {"detail": "Rate limit exceeded..."} |
500 | Unexpected server error. Safe to retry. | {"detail": "Internal server error"} |
Best practices
- Reuse session ids. Persist the
session_idreturned from the first call in a cookie or localStorage, and pass it back on every subsequent turn from the same user. This gives the bot conversation context (last 10 turns) and dramatically improves follow-up quality. Sessions expire after 30 minutes of inactivity. - Set the domain. If you're integrating in a faculty-specific context (e.g. an FMHS portal), always pass
"domain": "fmhs". Retrieval is scoped to that faculty's documents, which yields more relevant, less noisy answers. - Render citations. Every grounded answer includes a
citationsarray. Showing the source title (and optionally a "read full source" link viaGET /doc/{id}) builds user trust and lets people verify the answer. - Handle the verifier. If the bot's grounded-ness check rejects a generated answer (rare but real), you'll receive a canned "I couldn't verify..." message and empty citations. Treat this as a normal response — do not retry; the bot is intentionally refusing rather than hallucinating.
- Honor refusals. When
handoffis non-null, the safety filter blocked the input. Display the answer and the contact info exactly as returned; do not retry with the same message. - Use streaming for chat UIs. Total response time is 5–20 seconds depending on whether retrieval is needed. With
stream: true, your user sees tokens appear in 1–2 seconds, which feels far more responsive than waiting for the entire response.