UBONGO: knowledge
UBONGO is Ngamia’s knowledge engine. It stores a workspace’s business knowledge, turns it into searchable chunks, and returns passages with stable citations. It is a Rust service backed by MongoDB Atlas, with local EmbeddingGemma embeddings and Swahili/English-aware text handling.
UBONGO is private. Developers reach it only through the public API at
https://api.ngamia.com (/v1/knowledge/*) and through agents that NAK runs.
This page explains how it works so you can load knowledge well and run the
engine safely.
UBONGO is an early implementation, not a finished v1 engine. Never expose it
to the internet. See UBONGO/docs/IMPLEMENTATION_STATUS.md for what is
accepted and what is still open.
How the platform uses UBONGO
- One tenant per workspace. The UBONGO tenant ID is the workspace ID. The tenant is created the first time the workspace uses knowledge.
- Admin API. The platform calls UBONGO’s admin API
(
/internal/v1/*, bearerUBONGO_ADMIN_TOKEN) to create the tenant and two keys. - Ingest key (
read+ingest): used by the platform’s knowledge endpoints for uploads, documents, jobs and search. - Read key (
readonly): the only key NAK receives. NAK uses it for theknowledge_searchtool. - Both keys are stored encrypted in the platform database (AES-256-GCM).
- The tenant always comes from the API key. Callers never send a tenant ID.
Admin API
Mounted only when UBONGO_ADMIN_TOKEN (at least 32 characters) is set. Serve
it on the private network only; the edge proxy never routes /internal/*.
The token is compared in constant time. Every change is audited with actor
admin-api. If the audit write fails, the change is undone and the call
returns 503 audit_unavailable.
| Call | Body | Result |
|---|---|---|
POST /internal/v1/tenants | {"id", "name"} | 201 {"tenant_id", "created": true}, or 200 with created: false if it exists (idempotent) |
POST /internal/v1/tenants/{tenant_id}/keys | {"scopes": [...], "expires_in_days": 365} | 201 {"tenant_id", "key", "prefix", "scopes", "expires_at"}; 404 tenant_not_found |
Key scopes on this API must be a subset of read, ingest, agent.
expires_in_days is 1 to 3650 (default 365). The secret key is returned
only once.
Documents
A document is one piece of text knowledge. Send it to POST /v1/documents
(synchronous) or POST /v1/jobs (queued).
| Field | Required | Notes |
|---|---|---|
external_id | yes | Your stable ID for the document. |
source_id | yes | Groups documents by origin, for example manual-faqs. |
kind | yes | One of web, doc, faq, business, content, location. |
title | yes | Shown as source_title in search hits. |
text | yes | Plain text or Markdown. Headings shape chunks. |
url | no | Absolute HTTP(S) URL, at most 4,096 characters, no username or password. Stored only; never fetched. |
lang | no | If omitted, UBONGO labels it sw, en or mixed. |
tags | no | Array of strings, usable as a search filter. |
meta | no | JSON object, at most 65,536 serialized bytes. Stored once on the document and returned with each hit. |
loc | no | GeoJSON point, longitude first, for nearby search. |
Upsert semantics
- Documents are keyed by
(tenant, source_id, external_id). Sending the same key again replaces the document. - A changed document returns
201withdocument_id,chunks_writtenandunchanged: false. - An identical payload (including
meta) is detected before embedding and returns200withchunks_written: 0andunchanged: true. - On change, existing chunk vectors are reused when the chunk text hash, model, dimension and embedding version all match. Only new chunks are embedded.
DELETE /v1/documents/{document_id}soft-deletes a document and its chunks (204). Unknown IDs and other tenants’ IDs both return404. Deleted documents are never returned by search. Physical removal is a separate operator command (tenant purge-deleted).
Chunking
- Text is normalized, then split by Markdown heading path. Consecutive paragraphs under the same heading are grouped.
- Chunk size is counted with the model tokenizer over the full embedding prompt, including title and heading context.
- Defaults: 400-token target, 500-token maximum, 40 tokens of overlap. Small sections can stay shorter.
- Each chunk keeps its
heading_path, which is returned in hits.
Embeddings
- Model: EmbeddingGemma 300M, ONNX (int8), run locally. No hosted embedding service is used.
- Output: 768 dimensions by default.
UBONGO_EMBED_DIMcan also be 512, 256 or 128 (prefix-truncated, then re-normalized). - Document prompt:
title: {title} | text: {chunk}. Query prompt:task: search result | query: {query}. - Embeddings are computed in batches of up to 32. Vectors are checked for dimension and finite values before they are stored.
- The model files are never downloaded at startup. Their SHA-256 sums are checked against the pinned manifest before use.
- Ollama is an explicit local fallback (
UBONGO_EMBED_BACKEND=ollama).
Language
The language label is a small keyword heuristic, not a full detector. Send
lang yourself when you know it. Keyword search uses the standard Lucene
analyzer; Swahili-specific analysis is not validated.
File uploads
POST /v1/files accepts one file as multipart/form-data. It is off by
default (UBONGO_FILE_INGEST_ENABLED=false) and on in the production profile.
- Fields:
fileandexternal_id(required);source_id(defaultfile-upload),titleand repeatedtags(optional). - Formats: text-based PDF, DOCX, UTF-8 TXT, Markdown, UTF-8 HTML/HTM. File extension and media type must agree. PDF and ZIP signatures are checked. No OCR: scanned PDFs are rejected.
- Scanning: every file is scanned by a private ClamAV daemon before parsing. Readiness fails if ClamAV is down or its signatures are older than 48 hours.
- Parser isolation: parsing runs in a separate
ubongo-parsercontainer with no internet route, a read-only filesystem, a non-root user, a shared 256-bit token, a 20-second deadline and one parse at a time. - Limits: 8 MiB per file, 250 PDF pages, DOCX up to 1,024 archive
entries and 2 MiB of document XML, HTML up to 2 MiB input, 100,000 nodes
and 256 levels deep, extracted text up to 500,000 bytes. At most
UBONGO_MAX_CONCURRENT_UPLOADS(default 2) uploads run at once. - Originals are not kept. The document stores the safe filename, format and SHA-256 digest.
Queued and synchronous uploads
| Request | Response |
|---|---|
With Idempotency-Key header (recommended) | 202 {"job_id", "state"}. Scan and parse happen in the request; chunking and embedding run in the worker. |
| Without the header | 201 (or 200 if unchanged). Must finish embedding within the request timeout. |
Poll GET /v1/jobs/{job_id} until complete (with document_id and
chunks_written) or failed. Job states are queued, running, complete
and failed. Reusing a key for a different file returns 400. Infected,
malformed, encrypted or disguised files return validation_failed (413 for
size); nothing is stored. Scanner or parser outages return
upstream_unavailable.
Search
POST /v1/search runs vector search and keyword (Atlas Search) retrieval in
parallel, then merges them with weighted reciprocal rank fusion (RRF,
k = 60 by default).
{
"query": "Mnafunga saa ngapi?",
"limit": 8,
"filters": { "kinds": ["faq"], "lang": "sw", "tags": ["hours"],
"updated_after": "2026-01-01T00:00:00Z" },
"min_score": 0.55
}queryis 1 to 4,000 characters.limitdefaults to 8 (1 to 50).- Filters:
kinds,lang,source_id,tags, and inclusive RFC 3339updated_after/updated_before. - The tenant and active-status filters are always added by the server.
min_scoreis 0 to 1 (defaultUBONGO_MIN_SCORE, 0.55).
Hits
The response is {"hits": [...], "score_semantics": "..."}.
| Field | Meaning |
|---|---|
citation_id | Stable citation: the chunk ObjectId as 24 lowercase hex characters. |
chunk_id, document_id | Stored IDs. |
text | The passage. |
score | Normalized fused score (see below). |
kind | Document kind. |
source_title, source_url | Document title and optional URL. |
heading_path | Headings above the passage. |
meta | The parent document’s meta. |
updated_at | Last update time. |
exact_answer | true for an FAQ with score of at least 0.8, which is promoted. |
Score semantics
The score is weighted RRF normalized against the best candidate for this
query. The top hit is always 1.0. Scores are not probabilities and cannot
be compared across queries. The 0.55 and 0.8 thresholds are not calibrated.
Because the top hit always scores 1.0, min_score never removes the best
match. UBONGO does not yet abstain when it has no relevant knowledge
(requirement RET-7 is open). NAK’s citation check is the current guard.
Citations contract
Keep citation_id exactly as returned. Do not replace it with
document_id, external_id or a list index. NAK accepts only 24-hex
citation IDs from the retrieved set, removes invented citations, and
revalidates source_url before showing it as a link.
Nearby search
POST /v1/search/nearby takes longitude, latitude (GeoJSON order),
max_distance_meters (up to 1,000,000), limit and optional text. Its
score is distance-based, not semantic relevance.
HTTP surface
All /v1 routes need Authorization: Bearer ubg_live_.... A bad or missing
key returns 401; a key without the scope returns 403.
| Method and path | Scope | Purpose |
|---|---|---|
GET /healthz | none | Process is alive. |
GET /readyz | none | Dependencies ready (see Operations). |
GET /metrics | metrics token | Prometheus metrics, if enabled. |
POST /v1/documents | ingest | Ingest one document synchronously. |
DELETE /v1/documents/{id} | ingest | Soft-delete a document. |
POST /v1/jobs | ingest | Queue a document (needs Idempotency-Key). |
GET /v1/jobs, GET /v1/jobs/{id} | read | List jobs or read one job. |
POST /v1/files | ingest | Upload a file (when enabled). |
POST /v1/search | read | Hybrid search with citations. |
POST /v1/search/nearby | read | Geospatial search. |
POST/GET /v1/sources, PATCH /v1/sources/{id} | admin | Register, list, rename or disable sources. |
POST /v1/sources/{id}/sync, /sync/batch, /sync/csv, /sync/xlsx | ingest | Push 1 to 16 records for a registered source (xlsx needs file ingest). |
POST /internal/v1/tenants, .../keys | admin token | Platform provisioning. |
Scopes are read, ingest, admin and agent (reserved; no route uses it).
In the current build, admin also passes every route’s scope check.
Errors use {"code", "message", "request_id"}. Codes include
unauthorized, forbidden, not_found, validation_failed,
rate_limited, quota_exceeded, upstream_unavailable and internal. Every
response carries an x-request-id.
Configuration
| Variable | Default | Meaning |
|---|---|---|
UBONGO_ENV | development | development, staging or production. |
UBONGO_MONGO_URI | mongodb://127.0.0.1:27017 | MongoDB connection string. |
UBONGO_DB | ubongo | Database name (1 to 63 characters). |
UBONGO_BIND | 127.0.0.1:8080 | Listen address. |
UBONGO_EMBED_BACKEND | onnx | onnx or ollama. |
UBONGO_EMBED_MODEL_PATH | models/embeddinggemma-300m-onnx-int8 | Model and tokenizer.json directory. |
UBONGO_EMBED_DIM | 768 | 768, 512, 256 or 128. |
UBONGO_EMBED_URL, UBONGO_EMBED_MODEL | local Ollama | Used only with the Ollama backend. |
UBONGO_MIN_SCORE | 0.55 | Default search cutoff, 0 to 1. |
UBONGO_RRF_K | 60 | RRF constant. |
UBONGO_VECTOR_WEIGHT, UBONGO_KEYWORD_WEIGHT | 1 | RRF weights. |
UBONGO_REQUEST_TIMEOUT_SECS | 20 | Whole-request deadline, 1 to 300. Expired requests return 504. |
UBONGO_MAX_BODY_BYTES | 10485760 | Body limit, up to 10 MiB. |
UBONGO_MAX_AUTH_CHECKS | 8 | Concurrent key checks per process, 1 to 64. |
UBONGO_REQUESTS_PER_MINUTE | 120 | Default per-tenant request cap (429 when exceeded). |
UBONGO_REQUESTS_PER_KEY_PER_MINUTE | 0 | Optional per-key cap; 0 disables it. |
UBONGO_FILE_INGEST_ENABLED | false | Turns on /v1/files and /sync/xlsx. |
UBONGO_PARSER_URL | none | Parser origin; must resolve to private addresses. |
UBONGO_PARSER_TOKEN | none | Parser token, at least 32 bytes. |
UBONGO_CLAMD_ADDRESS | none | Private ClamAV address. |
UBONGO_MAX_CONCURRENT_UPLOADS | 2 | 1 to 16. |
UBONGO_METRICS_TOKEN | none | Enables /metrics; at least 32 characters. |
UBONGO_ADMIN_TOKEN | none | Enables the admin API; at least 32 characters. |
UBONGO_OPERATOR_ID | none | Operator name recorded in CLI audit events. |
The three parser and ClamAV settings are required when file ingest is on.
MongoDB Atlas requirements
- Atlas or Atlas Local with Atlas Search and Vector Search. A plain MongoDB server never becomes ready.
- A transaction-capable topology (replica set). Ingestion, quotas, jobs and key rotation use transactions.
- In
production, the URI must use TLS (mongodb+srv://, ortls=true), andUBONGO_BINDmust not be a loopback address. TLS for clients is terminated at the edge in front of UBONGO. serveandensure-indexescreate the indexes, including the Atlas indexeschunks_vec_v2andchunks_text_v2. Atlas builds them asynchronously.- Use a least-privilege database user. It needs insert and
createIndexonaudit_events, but no update or delete there.
Operations
- Health:
GET /healthzchecks only that the process is alive. - Readiness:
GET /readyzis200only when MongoDB answers, the document worker is running, and both v2 search indexes are queryable. With file ingest on, it also needs a healthy parser and fresh ClamAV signatures. Otherwise it returns503. - Metrics: set
UBONGO_METRICS_TOKENand call/metricswith that bearer token (API keys are refused). Series:ubongo_http_requests_total,ubongo_http_request_duration_seconds,ubongo_document_worker_ready. Labels never contain IDs, tenants or content. Logs are JSON on stderr. - Worker: each
servereplica runs one serial job worker. Jobs use MongoDB leases, up to 5 attempts, and a 30-second drain on shutdown. - Evaluation:
ubongo eval --tenant TENANT_ID --golden golden.jsonl --report eval-report.jsonruns a golden set through the real search path. It reports recall@5, MRR, nDCG@10, abstention accuracy and Swahili/mixed share, and exits non-zero when a gate fails (defaults: recall@5 of at least 0.85, MRR of at least 0.70, at least 30%sw/mixedcases). It changes no data. - Operator CLI:
ubongo tenant create|quota|usage|purge-deletedandubongo key create|list|revoke|rotate. Rotation keeps the old key valid until you revoke it. - Runbooks in
UBONGO/docs/RUNBOOKS.mdcover deploy and rollback, readiness triage, index rebuilds, stuck jobs, re-embedding, key compromise, export and deletion, backups and alert thresholds.
Known limits
- No abstention on out-of-knowledge questions yet (RET-7).
- Scores and thresholds are not calibrated against a release golden set.
- No OCR, no retained originals, no crawler or remote source fetching. Sources are push-only.
- Soft delete does not erase backups; purge is an operator CLI step.
- Queue, quota and multi-replica runtime acceptance is still open.
- Production Atlas, restore, load and data-residency acceptance are not done.
EmbeddingGemma is under Google’s Gemma terms, not Apache-2.0. Review and accept those terms before downloading the model, and get legal review before redistribution or commercial launch. Model weights are never in Git or the container image; mount them read-only.
Repository docs
UBONGO/README.mdUBONGO/docs/API_REFERENCE.mdandUBONGO/docs/openapi.yamlUBONGO/docs/ARCHITECTURE.mdUBONGO/docs/NAK_INTEGRATION.mdUBONGO/docs/SECURITY_AND_PRIVACY.mdUBONGO/docs/RUNBOOKS.mdUBONGO/docs/EVALUATION.mdUBONGO/docs/IMPLEMENTATION_STATUS.mdUBONGO/deploy/docker/README.production.mddocs/ARCHITECTURE.md(platform)