KYC
Verify identity documents, match a live face to them, and review the results.
The KYC service checks a customer's identity document against a national registry, reads the portrait off the document, matches it to a live capture of the customer's face, and keeps a record your team can review.
pip install aice-kycThe customer is the acting user
Like every AICE service, KYC is called with the project key and the user the request acts for (X-User-Id). In KYC that user is the customer: verification, uploads, the face flow and GET /status act on X-User-Id and take no customer_id. Sending one is a 422, so an old caller fails loudly instead of acting on the wrong person.
Your backend holds the key, so it names the customer: use the UUID you already give them. Only the review calls name another customer, and they need an admin role. Nobody accepts or reviews their own document: that is a 403.
Staff never act as a customer. The console's KYC page, playground and test chats run every self-service call as the signed-in member, which is a test of the flow on their own record. For a customer, staff can look up status, recheck, accept and review a face match the customer ran in your app, and each decision is recorded with the reviewer's name.
Create a client
import os
from aice_kyc import KycClient
kyc = KycClient(
base_url=os.environ["AICE_KYC_URL"], # http://localhost:6700/api/v1/kyc
api_key=os.environ["AICE_API_KEY"],
user_id=customer.id, # the customer being verified
)| Argument (Python / TypeScript) | Default | Meaning |
|---|---|---|
base_url / baseUrl | the service host and its /api/v1/kyc path | |
api_key / apiKey | the project key. Needs KYC enabled on the project | |
user_id / userId | sent as X-User-Id: the customer. Required | |
user_role / userRole | none | sent as X-User-Role. admin, owner and service_role add kyc:admin; viewer may only read |
user_scopes / userScopes | none | sent as X-User-Scopes. kyc:* entries narrow the caller, never widen it |
timeout | 30.0 s / 30000 ms | per-request timeout |
max_retries / maxRetries | 3 | retries for reads and analyze_document; the other writes are sent once |
To serve many customers from one client in Python, wrap each request in acting_as. It is safe across threads and asyncio tasks:
from aice_core import acting_as
with acting_as(customer.id):
kyc.verify.start(doc_type="national_id", doc_number="12345678")In TypeScript, build a client per customer (clients are cheap). Python also has AsyncKycClient with the same resources (await every call, await kyc.aclose() to close).
Every route is under /api/v1/kyc. Over HTTP, send the same headers the client does:
Authorization: Bearer <project key>
X-User-Id: <customer UUID>The tenant is the key's project and is never a request field. IDs (customer_id, kyc_document_id, analysis_id) are UUIDs.
Concepts
| Term | Meaning |
|---|---|
| Customer | the person being verified: the acting user (X-User-Id) |
| KYC document | one identity document for a customer: a national ID, passport, KRA PIN and so on. A customer has at most one per doc_type, so submitting the same type again updates it |
| Verifier | the provider that checks a document against a registry (IPRS, KRA, SmileID). The service picks one from the country and doc_type |
| Analysis | a read of a document image: the portrait found on it, its quality, and any text extracted. Identified by analysis_id |
| Capture session | a short-lived token that lets one customer's live frames be matched to one analysis |
Document types and statuses
doc_type is one of national_id, passport, kra_pin, drivers_license, birth_certificate. country is a two-letter code and defaults to KE. GET /admin/verifiers lists what this project can verify; submitting a pair no verifier on the project handles is a 422.
A document, and the customer's rolled-up status, is always one of:
| Status | Meaning |
|---|---|
pending | submitted, the check is running |
verified | the registry confirmed it |
failed | the registry rejected it, or the check errored |
admin_accepted | a person accepted it by hand |
needs_recheck | queued to be checked again |
The customer's overall status is rolled up from their documents each time one changes.
Verify a customer
Start verification
doc = kyc.verify.start(doc_type="national_id", doc_number="12345678")
print(doc["kyc_document_id"], doc["status"]) # "pending"Over HTTP:
curl -X POST "$AICE_KYC_URL/verify" \
-H "Authorization: Bearer $AICE_API_KEY" -H "X-User-Id: $CUSTOMER_ID" \
-H "Content-Type: application/json" \
-d '{"doc_type": "national_id", "doc_number": "12345678", "country": "KE"}'Optional fields: metadata (passed to the verifier) and triggered_by (onboarding, admin, recheck or agent; default onboarding).
The service answers 202 straight away with the document's ID and status: "pending"; the registry check runs in the background.
{
"kyc_document_id": "6f1c…",
"customer_id": "…",
"doc_type": "national_id",
"verifier_id": "iprs",
"status": "pending",
"message": "Verification submitted"
}Keep kyc_document_id: the face flow and the admin calls take it. The document number is stored only as a hash.
Check the result
status = kyc.verify.status()
print(status["kyc_status"], [d["status"] for d in status["documents"]])Over HTTP:
curl "$AICE_KYC_URL/status" -H "Authorization: Bearer $AICE_API_KEY" -H "X-User-Id: $CUSTOMER_ID"{
"customer_id": "…",
"kyc_status": "verified",
"kyc_verified_at": "2026-10-08T09:14:02Z",
"kyc_last_checked_at": "2026-10-08T09:14:02Z",
"documents": [
{ "id": "6f1c…", "doc_type": "national_id", "country": "KE", "verifier_id": "iprs", "status": "verified" }
]
}Poll this until kyc_status leaves pending. To read another customer's status, an admin calls GET /status/{customer_id} (admin.customer_status / admin.customerStatus).
Match a face to the document
Face matching has four calls: upload the images, read the document, open a capture session, then match the customer's frames. Every one acts on the acting customer.
Upload the images
POST /uploads signs a direct upload to storage, so images go from the customer's device to storage without passing through your backend:
up = kyc.face.create_upload(content_type="image/jpeg", filename="id-front.jpg")
# POST the file to up["upload_url"] as multipart: every entry of up["fields"], then the file last, as "file".The answer is {object_key, upload_url, fields, expires_in, max_bytes}. content_type is image/jpeg, image/png or image/webp. The key is scoped to the customer, so it can't be used for anyone else's analysis.
Analyse the document
analysis = kyc.face.analyze_document(object_key=up["object_key"], kyc_document_id=doc["kyc_document_id"])
if not analysis["portrait"]["found"]:
print("retake:", analysis["portrait"]["reasons"])Optional: doc_type (default national_id), country, side (front or back), instance_id, consent_version, consent_ip.
The result carries an analysis_id and:
| Field | Meaning |
|---|---|
portrait.found | whether a usable face was found. The back of a card legitimately has none |
portrait.quality, portrait.reasons | image quality measures, and why a portrait was rejected (blur, glare, too dark, face too small…) |
portrait.faces_detected | how many faces were seen |
extraction | text read from the document, to pre-fill a form |
warnings | anything worth showing the customer |
If portrait.found is false, ask for a better photo and analyse again.
Open a capture session
session = kyc.face.create_capture_session(analysis_id=analysis["analysis_id"]){ "capture_token": "…", "expires_at": 1791450000, "required_frames": 3, "max_attempts": 3 }The token is bound to this customer and analysis, expires after 60 seconds by default, and expires_at is a Unix time. Capture required_frames frames first and open the session last, just before matching.
Match
result = kyc.face.match(
analysis_id=analysis["analysis_id"],
capture_token=session["capture_token"],
object_keys=selfie_keys, # or frames=[...] as bytes
)
print(result["band"], result["next_action"], result["attempts_remaining"])Send up to 8 frames, either uploaded (object_keys) or inline (frames). match is sent once, never retried: a retry would spend one of the customer's attempts. Optional: instance_id, name_matches (whether the name on the document matched the one the customer gave).
| Field | Meaning |
|---|---|
band | pass, review, fail or insufficient_quality |
next_action | what to do next: auto_pass, retake_selfie, retake_document, manual_review |
match_score | 0–100, or null when quality was too low to score |
reasons | why, for example a quality problem with the selfie |
attempts_remaining | retakes left in this session |
quality, thresholds | the measurements, and the thresholds they were judged against |
Act on next_action rather than comparing scores yourself: the thresholds are configurable. A reply of manual_review is for a person; record their decision with face-review below.
Errors to handle: 403 for a bad, expired or mismatched capture token, 400 for undecodable or missing frames, 410 when the stored document template has expired (analyse the document again), and 409 when the template was produced by a different model than is running now (also analyse again).
Build the face check in your app
The four calls above are everything the console's own Face check wizard uses. To put the same flow in your app you need two pieces: three or four routes on your backend, which hold the project key and act as the signed-in customer, and a small piece of browser code that captures the images, uploads them and asks for the match. The key never reaches the browser, and neither do other customers' records.
| Step in the browser | Your backend route | KYC call |
|---|---|---|
| Sign an upload for each image | POST /kyc/upload | face.create_upload |
| Read the document photo | POST /kyc/analyze | face.analyze_document |
| Capture the selfie frames, then match | POST /kyc/match | face.create_capture_session, then face.match |
Answer your customer with the band and the next step only. Don't show the match score: it tells someone trying to get past the check how close they are.
1. The backend routes
Each route reads who is signed in from your own session, builds a client for that customer, and calls KYC. Return only what the browser needs.
import os
from fastapi import Depends, FastAPI
from pydantic import BaseModel
from aice_kyc import KycClient
app = FastAPI()
def kyc_for(user) -> KycClient:
return KycClient(
base_url=os.environ["AICE_KYC_URL"],
api_key=os.environ["AICE_API_KEY"],
user_id=str(user.id), # the signed-in customer, never a request field
)
class UploadIn(BaseModel):
content_type: str # image/jpeg, image/png or image/webp
filename: str
class AnalyzeIn(BaseModel):
object_key: str
kyc_document_id: str
doc_type: str = "national_id"
country: str = "KE"
class MatchIn(BaseModel):
analysis_id: str
object_keys: list[str]
@app.post("/kyc/upload")
def upload(body: UploadIn, user=Depends(current_user)):
return kyc_for(user).face.create_upload(content_type=body.content_type, filename=body.filename)
@app.post("/kyc/analyze")
def analyze(body: AnalyzeIn, user=Depends(current_user)):
result = kyc_for(user).face.analyze_document(
object_key=body.object_key,
kyc_document_id=body.kyc_document_id,
doc_type=body.doc_type,
country=body.country,
side="front",
consent_version="my-app-consent-v1", # the version of the consent text you showed
)
return {"analysis_id": result["analysis_id"], "portrait": result["portrait"]}
@app.post("/kyc/match")
def match(body: MatchIn, user=Depends(current_user)):
kyc = kyc_for(user)
# The capture token lasts about a minute and is single-purpose: open it last,
# on the server, right before matching. It never needs to reach the browser.
session = kyc.face.create_capture_session(analysis_id=body.analysis_id)
result = kyc.face.match(
analysis_id=body.analysis_id,
capture_token=session["capture_token"],
object_keys=body.object_keys,
)
return {
"band": result["band"],
"next_action": result["next_action"],
"attempts_remaining": result.get("attempts_remaining"),
"reasons": result.get("reasons", []),
}The document must exist before the face check: call verify.start first and give the browser the kyc_document_id. Handle KYC's errors by status (see Errors and retries); a 403 or 410 on /kyc/match means the customer should analyse the document again.
2. The browser code
This is the wizard's own logic, without the framework. It runs in any browser; it needs only fetch, FormData and, for the camera, getUserMedia.
const FRAMES = 3 // the minimum a capture session asks for; send up to 8
const FRAME_GAP_MS = 350 // frames must differ: identical ones are flagged as duplicates
async function post<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
credentials: "include", // your own session cookie identifies the customer
})
if (!res.ok) throw new Error(`Request failed (${res.status})`)
return res.json()
}
/** Signs an upload on your backend, then sends the image with the signed form. */
async function uploadImage(blob: Blob, filename: string): Promise<string> {
const type = ["image/jpeg", "image/png", "image/webp"].includes(blob.type) ? blob.type : "image/jpeg"
const up = await post<{ object_key: string; upload_url: string; fields: Record<string, string>; max_bytes: number }>(
"/kyc/upload",
{ content_type: type, filename },
)
if (blob.size > up.max_bytes) throw new Error("That image is too large.")
const form = new FormData()
for (const [name, value] of Object.entries(up.fields)) form.append(name, value)
form.append("file", blob, filename) // the file must be the last field
const sent = await fetch(up.upload_url, { method: "POST", body: form })
if (!sent.ok) throw new Error(`The upload failed (${sent.status})`)
return up.object_key
}
/** Step 1: the front of the document. Resolves with the analysis, or null if there is no usable portrait. */
export async function readDocument(file: File, kycDocumentId: string) {
const objectKey = await uploadImage(file, file.name || "document.jpg")
const analysis = await post<{ analysis_id: string; portrait: { found: boolean; reasons: string[] } }>(
"/kyc/analyze",
{ object_key: objectKey, kyc_document_id: kycDocumentId, doc_type: "national_id", country: "KE" },
)
return analysis.portrait.found ? analysis : null // null: ask for a sharper, well-lit photo
}
/** Grabs a few distinct frames from a playing <video> that shows the camera. */
async function grabFrames(video: HTMLVideoElement): Promise<Blob[]> {
const canvas = document.createElement("canvas")
canvas.width = video.videoWidth
canvas.height = video.videoHeight
const frames: Blob[] = []
for (let i = 0; i < FRAMES; i++) {
canvas.getContext("2d")!.drawImage(video, 0, 0)
const blob = await new Promise<Blob | null>((done) => canvas.toBlob(done, "image/jpeg", 0.9))
if (!blob) throw new Error("Couldn't capture a frame.")
frames.push(blob)
if (i < FRAMES - 1) await new Promise((done) => setTimeout(done, FRAME_GAP_MS))
}
return frames
}
/** Step 2: the selfie, from the camera (a <video> element) or from at least three different photos. */
export async function matchSelfie(analysisId: string, source: HTMLVideoElement | File[]) {
const frames = source instanceof HTMLVideoElement ? await grabFrames(source) : source
if (frames.length < FRAMES) throw new Error(`Add at least ${FRAMES} different photos.`)
const keys = await Promise.all(
frames.map((frame, i) => uploadImage(frame, frame instanceof File ? frame.name : `selfie-${i + 1}.jpg`)),
)
return post<{ band: "pass" | "review" | "fail" | "insufficient_quality"; next_action: string; attempts_remaining?: number }>(
"/kyc/match",
{ analysis_id: analysisId, object_keys: keys },
)
}To use the camera, ask for it and attach the stream to a <video> you show on screen, and stop it when you are done:
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: "user", width: 640, height: 480 },
audio: false,
})
videoElement.srcObject = stream
await videoElement.play()
// ...after matchSelfie:
stream.getTracks().forEach((track) => track.stop())3. Show the result
Show the outcome from band and next_action, never a score. This is what the console does:
| What came back | Tell the customer |
|---|---|
band: "pass" | "Face matches. The document is now verified." |
band: "review" or "fail", next_action: "manual_review" | The outcome ("Needs a person's review" or "Face doesn't match") and "A reviewer will look at this match and decide." |
band: "insufficient_quality" | "Image quality too low", with the reasons in plain words (blur, glare, too dark…) |
next_action: "retake_selfie" | Offer another selfie |
next_action: "retake_document" | Send them back to step 1 for another photo of the document |
Offer a retry whenever the band is not pass and attempts_remaining is above 0 (and next_action isn't retake_document); show the number of attempts left. A reviewer settles review and fail results with POST /admin/face-review, and the document's status changes as soon as the decision is recorded.
4. What your deployment needs
- HTTPS. Browsers only give
getUserMediato secure pages (localhostcounts). Without it the customer can still choose photos. - Uploads from the browser.
upload_urlmust be reachable from your customer's browser, and the bucket must allow a cross-originPOSTfrom your site's origin (a CORS rule). If your site sets a Content-Security-Policy, add the upload address toconnect-src. - Camera permission. If you send a
Permissions-Policyheader, allow the camera for your own origin:camera=(self).camera=()blocks it everywhere. - Consent. Show your customer what the face check is for and get their agreement before the first upload, and send the version of the text they agreed to as
consent_version. The service records it with the analysis. - Reassure, briefly. Tell customers their photos are handled securely and kept private, and that only the result is shown to them. Your customer doesn't need to know where the images travel. Neither the model nor an agent ever sees them: an agent can only ask for a face check and read the outcome.
- Frames must differ. Identical frames are flagged as duplicates, so leave a short gap between camera frames (about 350 ms works) or ask for different photos.
Review
These calls are about any customer, so they name one and need kyc:admin (role admin, owner or service_role). The acting user is the reviewer and is recorded as such.
| Endpoint | Body | Does |
|---|---|---|
GET /status/{customer_id} | any customer's status, with reviewer notes | |
GET /admin/stats | counts: total, verified, pending, failed, admin_accepted, needs_recheck. Any role may read it | |
POST /admin/accept | {customer_id, kyc_document_id, note?} | accept a document by hand. Answers {status, message} with the customer's new rolled-up status |
POST /admin/recheck | {customer_id, kyc_document_id?} | queue the checks again; omit the document to recheck all of the customer's. Answers 202 with {queued, message} |
GET /admin/verifiers | every verifier as this project uses it (see Verifiers). Any role may read it | |
POST /admin/face-review | {customer_id, kyc_document_id, decision, note?} | record a person's face-match decision. decision is a status such as verified or failed |
A face override records who reviewed it and when, so no decision with legal effect rests on automation alone (the service cites Kenya's Data Protection Act, 2019, section 35).
Accepting and re-checking are compliance actions: don't retry them blindly after a timeout. Check the status first.
Verifiers
Each project chooses its own verifiers, within what the platform allows. In the console that's the Verifiers table on the project's KYC page (editors and admins); with the SDK it's admin.configure_verifier / admin.configureVerifier.
Settings come from three places, the most specific winning:
- The platform (a super admin, in Platform → Configuration → KYC): each verifier's registry keys, address and default mode, and the ceiling: whether projects may use it at all, and whether it may run live.
- The project: on or off,
sandboxorlive, which countries and documents it checks, itsprioritywhen two verifiers handle the same document (lower first, default 100), and optionally the project's own registry credentials, used instead of the platform's. - Anything the project leaves unset follows the platform.
kyc = KycClient(api_key=AICE_API_KEY, user_id=admin_user_id, user_role="admin")
kyc.admin.configure_verifier("smile_id", enabled=False) # Kenyan IDs only, through IPRS
kyc.admin.configure_verifier("iprs", mode="live", credentials={"api_key": IPRS_KEY})
kyc.admin.test_verifier("iprs") # {"ok": True, "mode": "live", ...}
kyc.admin.configure_verifier("iprs", reset=True) # back to the platform's settingsOnly the fields you send change; null puts one back on the platform's value, and credentials: null removes the project's keys. Credentials are write-only: GET /admin/verifiers shows only the last four characters of each and whose keys a verifier runs with (credentials.source: project, platform or none). A request past the platform's ceiling answers 409: turning on a verifier the platform doesn't offer, or asking for live where it allows sandbox only, or where no credentials exist. A verifier set to live without credentials fails its checks instead of quietly running in sandbox.
A super admin can also change any project's verifiers from the project's page under Platform → Projects; the change is recorded in the platform audit log, and in KYC's.
GET /healthz reports the service, and GET /healthz/face reports whether the face models loaded. If they didn't, document verification still works and face calls answer 503.
Agents
An agent with KYC tools acts for the run's user, who is the customer. It never sees a customer ID, a document number or an image:
| Tool | Does |
|---|---|
kyc_get_customer_status | the customer's status and each document's. No arguments |
kyc_verify_document | checks one document against its registry and waits for the verdict. Takes only doc_type |
kyc_request_face_check | asks the customer for a face check on one of their documents and returns the outcome. Takes only doc_type. Gate it (below) |
kyc_list_verifiers, kyc_get_stats | what can be verified, and counts by status |
kyc_verify_document takes the number from the run's kyc_context, which your backend sends with the run. The Agent Platform encrypts it for KYC only, so the model never reads it:
{
"config": {
"configurable": {
"agent_id": "…",
"kyc_context": { "documents": [{ "doc_type": "national_id", "doc_number": "12345678", "country": "KE" }] }
}
}
}Up to five documents, one per type. In the console, Agent Studio's test chat has a Test documents button for this.
Face check from chat
Photos and selfies never go through chat. Instead the agent calls kyc_request_face_check, and the run pauses for approval:
- The model calls
kyc_request_face_check({ doc_type }). The run stops with an interrupt naming that tool. - Your app shows the customer a face check for their document of that type: upload the document image, then a selfie, straight to storage (Match a face to the document, made as the customer).
- The customer approves, which resumes the run with
{ "decisions": [{ "type": "approve" }] }. - The tool returns
{ doc_type, done, face_band, face_checked_at, document_status, customer_kyc_status }. Never a score or an image.done: falsemeans nothing was recorded (approved without a check, or the tool wasn't gated).
The customer needs a document of that type first, so the agent runs kyc_verify_document before asking. A close match goes to a reviewer, never to the customer.
Gate only this tool. On the Agent Platform, set HITL_TOOLS=kyc_request_face_check and leave HITL_ENABLED=false (true gates every tool). Or per agent: approval_mode: "selected" with approval_tools: ["kyc_request_face_check"]. A helper agent (subagent) can't pause, so the tool is refused there.
In the console's chats (Agent Studio test chat and the playground) the approval card holds the face check itself, and Approve unlocks once it has run.
Reference
| Python | TypeScript | Endpoint (under /api/v1/kyc) | Retried? |
|---|---|---|---|
verify.start(doc_type=, doc_number=, country="KE", …) | verify.start({…}) | POST /verify | no |
verify.status() | verify.status() | GET /status | yes |
face.create_upload(content_type=, filename=) | face.createUpload({…}) | POST /uploads | no |
face.analyze_document(object_key=, …) | face.analyzeDocument({…}) | POST /documents/analyze | yes |
face.create_capture_session(analysis_id=) | face.createCaptureSession({…}) | POST /face/capture-session | no |
face.match(analysis_id=, capture_token=, object_keys= or frames=) | face.match({…}) | POST /face/match | no |
admin.customer_status(customer_id) | admin.customerStatus(customerId) | GET /status/{customer_id} | yes |
admin.stats() | admin.stats() | GET /admin/stats | yes |
admin.accept(customer_id=, kyc_document_id=, note=None) | admin.accept({…}) | POST /admin/accept | no |
admin.recheck(customer_id=, kyc_document_id=None) | admin.recheck({…}) | POST /admin/recheck | no |
admin.list_verifiers() | admin.listVerifiers() | GET /admin/verifiers | yes |
admin.configure_verifier(verifier_id, **changes) | admin.configureVerifier(id, {…}) | PUT /admin/verifiers/{id} | no |
admin.test_verifier(verifier_id) | admin.testVerifier(id) | POST /admin/verifiers/{id}/test | no |
admin.face_review(customer_id=, kyc_document_id=, decision=, note=None) | admin.faceReview({…}) | POST /admin/face-review | no |
The calls marked "no" are sent once because the service doesn't yet deduplicate them, and a duplicate verification, decision or spent match attempt would be costly. A transient failure reaches you immediately: check the status before trying again. See Errors and retries.
Upgrading from 0.1
aice-kyc 0.1.0 is the first Python release, so this only concerns @aiceafrica/kyc. 0.2.0 is a rewrite that matches the service, which no 0.1.x call reached correctly. Keep apiKey (the project key) and add userId: the customer. Drop customer_id from verify.start and every face.* call. verify.status(customerId) becomes verify.status() for the acting customer, or admin.customerStatus(customerId) for an admin. The base URL includes /api/v1/kyc, and face.analyzeDocument takes the object_key from face.createUpload instead of a file. See the changelog.