Skip to Content
The Ngamia platform API is in preview. Endpoints may change before general availability.
EnginesUBONGO: knowledge

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/*, bearer UBONGO_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 (read only): the only key NAK receives. NAK uses it for the knowledge_search tool.
  • 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.

CallBodyResult
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).

FieldRequiredNotes
external_idyesYour stable ID for the document.
source_idyesGroups documents by origin, for example manual-faqs.
kindyesOne of web, doc, faq, business, content, location.
titleyesShown as source_title in search hits.
textyesPlain text or Markdown. Headings shape chunks.
urlnoAbsolute HTTP(S) URL, at most 4,096 characters, no username or password. Stored only; never fetched.
langnoIf omitted, UBONGO labels it sw, en or mixed.
tagsnoArray of strings, usable as a search filter.
metanoJSON object, at most 65,536 serialized bytes. Stored once on the document and returned with each hit.
locnoGeoJSON 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 201 with document_id, chunks_written and unchanged: false.
  • An identical payload (including meta) is detected before embedding and returns 200 with chunks_written: 0 and unchanged: 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 return 404. 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_DIM can 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: file and external_id (required); source_id (default file-upload), title and repeated tags (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-parser container 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

RequestResponse
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 header201 (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.

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 }
  • query is 1 to 4,000 characters. limit defaults to 8 (1 to 50).
  • Filters: kinds, lang, source_id, tags, and inclusive RFC 3339 updated_after / updated_before.
  • The tenant and active-status filters are always added by the server.
  • min_score is 0 to 1 (default UBONGO_MIN_SCORE, 0.55).

Hits

The response is {"hits": [...], "score_semantics": "..."}.

FieldMeaning
citation_idStable citation: the chunk ObjectId as 24 lowercase hex characters.
chunk_id, document_idStored IDs.
textThe passage.
scoreNormalized fused score (see below).
kindDocument kind.
source_title, source_urlDocument title and optional URL.
heading_pathHeadings above the passage.
metaThe parent document’s meta.
updated_atLast update time.
exact_answertrue 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.

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 pathScopePurpose
GET /healthznoneProcess is alive.
GET /readyznoneDependencies ready (see Operations).
GET /metricsmetrics tokenPrometheus metrics, if enabled.
POST /v1/documentsingestIngest one document synchronously.
DELETE /v1/documents/{id}ingestSoft-delete a document.
POST /v1/jobsingestQueue a document (needs Idempotency-Key).
GET /v1/jobs, GET /v1/jobs/{id}readList jobs or read one job.
POST /v1/filesingestUpload a file (when enabled).
POST /v1/searchreadHybrid search with citations.
POST /v1/search/nearbyreadGeospatial search.
POST/GET /v1/sources, PATCH /v1/sources/{id}adminRegister, list, rename or disable sources.
POST /v1/sources/{id}/sync, /sync/batch, /sync/csv, /sync/xlsxingestPush 1 to 16 records for a registered source (xlsx needs file ingest).
POST /internal/v1/tenants, .../keysadmin tokenPlatform 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

VariableDefaultMeaning
UBONGO_ENVdevelopmentdevelopment, staging or production.
UBONGO_MONGO_URImongodb://127.0.0.1:27017MongoDB connection string.
UBONGO_DBubongoDatabase name (1 to 63 characters).
UBONGO_BIND127.0.0.1:8080Listen address.
UBONGO_EMBED_BACKENDonnxonnx or ollama.
UBONGO_EMBED_MODEL_PATHmodels/embeddinggemma-300m-onnx-int8Model and tokenizer.json directory.
UBONGO_EMBED_DIM768768, 512, 256 or 128.
UBONGO_EMBED_URL, UBONGO_EMBED_MODELlocal OllamaUsed only with the Ollama backend.
UBONGO_MIN_SCORE0.55Default search cutoff, 0 to 1.
UBONGO_RRF_K60RRF constant.
UBONGO_VECTOR_WEIGHT, UBONGO_KEYWORD_WEIGHT1RRF weights.
UBONGO_REQUEST_TIMEOUT_SECS20Whole-request deadline, 1 to 300. Expired requests return 504.
UBONGO_MAX_BODY_BYTES10485760Body limit, up to 10 MiB.
UBONGO_MAX_AUTH_CHECKS8Concurrent key checks per process, 1 to 64.
UBONGO_REQUESTS_PER_MINUTE120Default per-tenant request cap (429 when exceeded).
UBONGO_REQUESTS_PER_KEY_PER_MINUTE0Optional per-key cap; 0 disables it.
UBONGO_FILE_INGEST_ENABLEDfalseTurns on /v1/files and /sync/xlsx.
UBONGO_PARSER_URLnoneParser origin; must resolve to private addresses.
UBONGO_PARSER_TOKENnoneParser token, at least 32 bytes.
UBONGO_CLAMD_ADDRESSnonePrivate ClamAV address.
UBONGO_MAX_CONCURRENT_UPLOADS21 to 16.
UBONGO_METRICS_TOKENnoneEnables /metrics; at least 32 characters.
UBONGO_ADMIN_TOKENnoneEnables the admin API; at least 32 characters.
UBONGO_OPERATOR_IDnoneOperator 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://, or tls=true), and UBONGO_BIND must not be a loopback address. TLS for clients is terminated at the edge in front of UBONGO.
  • serve and ensure-indexes create the indexes, including the Atlas indexes chunks_vec_v2 and chunks_text_v2. Atlas builds them asynchronously.
  • Use a least-privilege database user. It needs insert and createIndex on audit_events, but no update or delete there.

Operations

  • Health: GET /healthz checks only that the process is alive.
  • Readiness: GET /readyz is 200 only 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 returns 503.
  • Metrics: set UBONGO_METRICS_TOKEN and call /metrics with 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 serve replica 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.json runs 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/mixed cases). It changes no data.
  • Operator CLI: ubongo tenant create|quota|usage|purge-deleted and ubongo key create|list|revoke|rotate. Rotation keeps the old key valid until you revoke it.
  • Runbooks in UBONGO/docs/RUNBOOKS.md cover 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.md
  • UBONGO/docs/API_REFERENCE.md and UBONGO/docs/openapi.yaml
  • UBONGO/docs/ARCHITECTURE.md
  • UBONGO/docs/NAK_INTEGRATION.md
  • UBONGO/docs/SECURITY_AND_PRIVACY.md
  • UBONGO/docs/RUNBOOKS.md
  • UBONGO/docs/EVALUATION.md
  • UBONGO/docs/IMPLEMENTATION_STATUS.md
  • UBONGO/deploy/docker/README.production.md
  • docs/ARCHITECTURE.md (platform)