Skip to main content

Knowledge Bases Quickstart

From an empty organization to a cited answer in seven steps. Every step works with the API and in the portal (Knowledge bases in the sidebar).

The examples use these variables:

export API_KEY="sk-your-api-key"
export BASE="https://api.infus.ai/v1"
Free trial

Every organization gets a free trial allowance (by default 1 knowledge base, 50 MB, 500 queries per billing period and 1 million processing tokens), unless your platform operator has switched it off — GET /v1/knowledge_module → trial.enabled_for_tenant tells you. The trial covers steps 2–6 without a balance or a plan. The chat in step 7 also uses the chat model, whose tokens are billed like any chat request, so that step needs the usual model balance, credit or plan allowance. See Pricing and Billing.

1. Create an API key​

Knowledge access is never granted implicitly: existing keys and the default scope set do not include it. In the portal open API Keys → Create. While knowledge bases are available, the form starts on the purpose Knowledge app (search + chat): an inference key with inference:chat and knowledge:read, limited to the knowledge bases you pick. To upload or manage documents with the key, also tick knowledge:write under Advanced settings; for anything else choose the Inference purpose and tick the knowledge scopes there. See Key purposes. The knowledge scopes:

Portal labelScopeAllows
Knowledge: read & searchknowledge:readList knowledge bases and documents, search, download originals, chunk previews, usage summaries, answer feedback. With inference:chat, chat with knowledge bases.
Knowledge: manageknowledge:writeEverything knowledge:read allows, plus create/rename/delete knowledge bases, upload/replace/delete documents, edit metadata and exports.

To chat with a knowledge base the key also needs inference:chat.

Once a knowledge scope is ticked, Knowledge base access appears with three choices. They map to the key's kb_allowlist field:

Portal choicekb_allowlistEffect
All knowledge basesnullEvery knowledge base of the organization, including ones created later.
None[]The key keeps its scope but every knowledge route is refused with 403 kb_not_in_allowlist (only GET /v1/knowledge_module works).
Only selected["<kb id>", …] (1–100 ids)Only the listed knowledge bases.
Only an unrestricted key creates knowledge bases

Creating a knowledge base needs a key with All knowledge bases (or the portal, as an organization admin or owner). A key with Only selected or None gets 403 kb_not_in_allowlist on POST /v1/knowledge_bases, and nothing is created. Set up with an unrestricted key or in the portal, then add the new knowledge base to the restricted key's list.

When a request names a knowledge base the key may not use, the whole request is refused with 403 kb_not_in_allowlist; nothing is silently skipped. When you manage keys through the API (/api/v1/api-keys, portal session), kb_allowlist follows the same three states: omitted on create means null; on PATCH, omitting the field leaves it unchanged, null means all, [] means none.

Portal users are not limited by an allowlist: every member can read and search every knowledge base, and admins and owners can change them.

2. Check that knowledge bases are available​

curl "$BASE/knowledge_module" -H "Authorization: Bearer $API_KEY"
{
"object": "knowledge_module",
"enabled": true,
"maintenance": false,
"supported_file_types": ["pdf", "docx", "pptx", "xlsx", "csv", "html", "txt", "md"],
"limits": { "max_file_bytes": 50000000, "max_files_per_upload": 50, "max_knowledge_bases": 20, "max_documents_per_kb": 1000, "max_top_k": 20, "max_kbs_per_query": 5, "…": "…" },
"trial": { "enabled_for_tenant": true, "knowledge_bases": 1, "storage_bytes": 50000000, "queries_per_period": 500, "processing_tokens": 1000000, "idle_days": 30 },
"price_card_url": "…"
}

A 404 with code module_disabled means the module is not enabled on your platform.

3. Create a knowledge base​

Requires knowledge:write (portal: admin or owner).

First pick the embedding model. List the models your platform offers; the recommended one comes first:

curl "$BASE/knowledge_embedding_models" -H "Authorization: Bearer $API_KEY"
{
"object": "list",
"data": [
{
"id": "3f1d2c4b-8e7a-4c1b-9d2e-6a5b4c3d2e1f",
"model_name": "your-embedding-model",
"display_label": "Your embedding model",
"dimensions": 1024,
"recommended": true,
"processing_price_per_1m_tokens": "…",
"currency": "USD",
"…": "…"
}
],
"has_more": false,
"next_cursor": null
}

Send the entry's id as embedding_model. Leave the field out to use the recommended model. The model cannot be changed after the knowledge base is created; to use another model, create a new knowledge base.

curl -X POST "$BASE/knowledge_bases" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: kb-hr-policies-1" \
-d '{"name": "HR policies", "description": "Handbook and leave rules", "embedding_model": "3f1d2c4b-8e7a-4c1b-9d2e-6a5b4c3d2e1f"}'
{
"id": "3f6c2b1e-8d4a-4c1f-9e2b-7a5d6c3b2a10",
"object": "knowledge_base",
"name": "HR policies",
"status": "active",
"document_count": 0,
"total_bytes": 0,
"embedding_model": {
"id": "3f1d2c4b-8e7a-4c1b-9d2e-6a5b4c3d2e1f",
"model_name": "your-embedding-model",
"display_label": "Your embedding model",
"dimensions": 1024,
"…": "…"
},
"…": "…"
}

An embedding_model that is not in the list is refused with 422 validation_failed (param: embedding_model). See Error Codes for the other refusals.

4. Upload documents​

POST /v1/knowledge_bases/{kb_id}/documents is a multipart/form-data request. Repeat the files part once per file (1–50 files, each ≤50 MB, ≤500 MB in total).

Form fieldRequiredMeaning
filesyesOne part per file. The part's file name becomes the document name.
metadatanoJSON object applied to every file of this request — see Metadata rules.
on_duplicatenoreject (default): a file whose content already exists in this knowledge base is refused with 409 duplicate_content. allow: store it as a new, independent document.
max_processing_costnoUSD ceiling (decimal string, e.g. "2.50") for processing all files of this request. A document whose processing would exceed the remaining ceiling fails with processing_budget_exceeded.

Send an Idempotency-Key header: if the connection drops, retry with the same key and you get the original response back, without a second upload or charge.

curl -X POST "$BASE/knowledge_bases/$KB_ID/documents" \
-H "Authorization: Bearer $API_KEY" \
-H "Idempotency-Key: upload-2026-09-23-001" \
-F "files=@handbook.pdf" \
-F "files=@leave-policy.docx" \
-F 'metadata={"department":"hr","year":2025}'

The answer is 202 Accepted with one result per file. A rejected file does not affect the others:

{
"object": "upload_result",
"upload_id": "0b7d…",
"knowledge_base_id": "3f6c2b1e-8d4a-4c1f-9e2b-7a5d6c3b2a10",
"accepted_count": 1,
"rejected_count": 1,
"results": [
{ "index": 0, "filename": "handbook.pdf", "status": "accepted",
"document": { "id": "1d2e3f40-5a6b-4c7d-8e9f-0a1b2c3d4e5f", "status": "uploaded", "…": "…" } },
{ "index": 1, "filename": "leave-policy.docx", "status": "rejected",
"error": { "code": "macro_file", "message": "Office files with macros are not accepted." } }
]
}

Request-level problems (missing scope, too many files, knowledge base frozen, trial or billing refusal for the whole request) return an error status instead of 202. See Error Codes.

5. Wait until documents are ready​

Poll one document:

curl "$BASE/knowledge_bases/$KB_ID/documents/$DOC_ID" -H "Authorization: Bearer $API_KEY"

or track many at once. updated_since returns documents changed after a timestamp, oldest change first, so a poller can resume from the last updated_at it saw:

curl "$BASE/knowledge_bases/$KB_ID/documents?status=processing,failed&limit=100" \
-H "Authorization: Bearer $API_KEY"

curl "$BASE/knowledge_bases/$KB_ID/documents?updated_since=2026-09-23T10:00:00Z" \
-H "Authorization: Bearer $API_KEY"

When status is ready the document is searchable. For large imports prefer webhooks (knowledge.document.ready, knowledge.document.failed) over polling. A failed document carries failure.code; if failure.retryable is true, POST …/documents/{id}/retry queues it again. A document in awaiting_budget is waiting for a paid allowance — top up or raise your limits, and it continues automatically within 24 hours.

curl -X POST "$BASE/knowledge_bases/$KB_ID/search" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"query": "How many days of annual leave do new employees get?",
"top_k": 5,
"filter": { "must": [ { "key": "department", "eq": "hr" } ] }
}'
{
"object": "search_result",
"knowledge_base_id": "3f6c2b1e-8d4a-4c1f-9e2b-7a5d6c3b2a10",
"request_id": "b3a4…",
"results": [
{
"knowledge_base_id": "3f6c2b1e-8d4a-4c1f-9e2b-7a5d6c3b2a10",
"doc_id": "1d2e3f40-5a6b-4c7d-8e9f-0a1b2c3d4e5f",
"document_name": "handbook.pdf",
"page": 12,
"chunk_index": 41,
"section": "Annual leave",
"text": "Employees with less than five years of service receive 14 working days …",
"score": 0.0312,
"location": { "page": 12 },
"metadata": { "department": "hr", "year": 2025 }
}
],
"usage": { "query_units": 1 }
}

One successful search is one query, even with zero results. score ranks the hits of this response only — it is not a probability and cannot be compared across searches. Filters and parameters are described in Metadata and Search Filters.

7. Chat with citations​

Add knowledge_base_ids (1–5 ids) to a normal chat request. The platform retrieves sources for the last user message, adds them to the prompt, and returns a citations array next to choices. Details, streaming and the retrieval options are in Chat with Citations.

curl​

curl "$BASE/chat/completions" \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "your-chat-model",
"messages": [{"role": "user", "content": "How many days of annual leave do new employees get?"}],
"knowledge_base_ids": ["3f6c2b1e-8d4a-4c1f-9e2b-7a5d6c3b2a10"]
}'
{
"id": "chatcmpl-9f2c…",
"object": "chat.completion",
"model": "your-chat-model",
"choices": [
{ "index": 0, "finish_reason": "stop",
"message": { "role": "assistant", "content": "New employees get 14 working days of annual leave [1]." } }
],
"usage": { "prompt_tokens": 812, "completion_tokens": 21, "total_tokens": 833 },
"citations": [
{ "index": 1, "knowledge_base_id": "3f6c2b1e-8d4a-4c1f-9e2b-7a5d6c3b2a10",
"doc_id": "1d2e3f40-5a6b-4c7d-8e9f-0a1b2c3d4e5f", "document_name": "handbook.pdf",
"page": 12, "chunk_index": 41, "text": "Employees with less than five years …", "score": 0.0312 }
]
}

Find the available model ids with GET /v1/models.

Python (OpenAI SDK)​

The OpenAI SDK sends unknown request fields through extra_body and keeps unknown response fields in model_extra. The knowledge API itself (upload, search) is plain HTTP; requests is used here.

import os
import time

import requests
from openai import OpenAI

BASE = "https://api.infus.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['API_KEY']}"}

# Create a knowledge base and upload two files
kb = requests.post(f"{BASE}/knowledge_bases", headers=HEADERS,
json={"name": "HR policies"}).json()

with open("handbook.pdf", "rb") as a, open("faq.md", "rb") as b:
upload = requests.post(
f"{BASE}/knowledge_bases/{kb['id']}/documents",
headers={**HEADERS, "Idempotency-Key": "upload-hr-001"},
files=[("files", ("handbook.pdf", a, "application/pdf")),
("files", ("faq.md", b, "text/markdown"))],
data={"metadata": '{"department": "hr"}'},
).json()

doc_ids = [r["document"]["id"] for r in upload["results"] if r["status"] == "accepted"]

# Wait until every accepted document is ready (or failed)
pending = set(doc_ids)
while pending:
for doc_id in list(pending):
doc = requests.get(f"{BASE}/knowledge_bases/{kb['id']}/documents/{doc_id}",
headers=HEADERS).json()
if doc["status"] in ("ready", "failed", "cancelled"):
pending.discard(doc_id)
time.sleep(5)

# Chat with citations
client = OpenAI(api_key=os.environ["API_KEY"], base_url=BASE)
completion = client.chat.completions.create(
model="your-chat-model",
messages=[{"role": "user", "content": "How many days of annual leave do new employees get?"}],
extra_body={"knowledge_base_ids": [kb["id"]]},
)
print(completion.choices[0].message.content)
for c in (completion.model_extra or {}).get("citations", []):
print(f"[{c['index']}] {c['document_name']} p.{c['page']}")

JavaScript (Node.js 20+, OpenAI SDK)​

import fs from "node:fs";
import OpenAI from "openai";

const BASE = "https://api.infus.ai/v1";
const headers = { Authorization: `Bearer ${process.env.API_KEY}` };

// Create a knowledge base
const kb = await (await fetch(`${BASE}/knowledge_bases`, {
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify({ name: "HR policies" }),
})).json();

// Upload (repeat "files" once per file)
const form = new FormData();
form.append("files", await fs.openAsBlob("handbook.pdf"), "handbook.pdf");
form.append("metadata", JSON.stringify({ department: "hr" }));
const upload = await (await fetch(`${BASE}/knowledge_bases/${kb.id}/documents`, {
method: "POST",
headers: { ...headers, "Idempotency-Key": "upload-hr-001" },
body: form,
})).json();

// Wait until every accepted document is ready (or failed) — 202 means accepted, not processed
const pending = new Set(
upload.results.filter((r) => r.status === "accepted").map((r) => r.document.id),
);
while (pending.size > 0) {
for (const id of [...pending]) {
const doc = await (await fetch(`${BASE}/knowledge_bases/${kb.id}/documents/${id}`, { headers })).json();
if (["ready", "failed", "cancelled"].includes(doc.status)) pending.delete(id);
}
if (pending.size > 0) await new Promise((resolve) => setTimeout(resolve, 5000));
}

// Search
const search = await (await fetch(`${BASE}/knowledge_bases/${kb.id}/search`, {
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify({ query: "annual leave for new employees", top_k: 3 }),
})).json();
console.log(search.results.map((r) => `${r.document_name} p.${r.page}: ${r.score}`));

// Chat with citations — extra fields pass through the SDK unchanged
const client = new OpenAI({ apiKey: process.env.API_KEY, baseURL: BASE });
const completion = await client.chat.completions.create({
model: "your-chat-model",
messages: [{ role: "user", content: "How many days of annual leave do new employees get?" }],
// @ts-expect-error knowledge_base_ids is a platform extension
knowledge_base_ids: [kb.id],
});
console.log(completion.choices[0].message.content);
console.log(completion.citations); // [{ index: 1, document_name: "handbook.pdf", page: 12, … }]

Next steps​