Recommendation
Tell the engine about users, items and interactions, train a model, and ask what to show each user next.
The Recommendation engine learns from what your users do. You register users and items, send interaction events, train, and then ask for a ranked list for any user.
register users + items ─▶ send events ─▶ train ─▶ recommend
(once, and on change) (continuously) (background job) (per request)Behind a request it runs three stages: candidate generation (find items that might suit the user), ranking (score them with the trained model), and re-ranking (apply your freshness, boost and diversity rules). Until a model has been trained, or for a user the model hasn't seen, it falls back to simpler strategies, so a call is never empty just because training hasn't happened yet.
pip install aice-recommendationCreate a client
A client is bound to one of your project's verticals (ecommerce, entertainment and so on), which the console shows on the project. Each vertical is a separate catalog with its own items, events, models and config. Users belong to the project and are shared by its verticals. To work with two verticals, build two clients with the same key.
import os
from aice_recommendation import RecommendationClient
client = RecommendationClient(
base_url=os.environ["AICE_RECO_URL"], # http://localhost:6400
api_key=os.environ["AICE_API_KEY"],
vertical="ecommerce",
user_id=current_user.id,
user_role="admin", # writing and training need admin or owner
)| Argument (Python / TypeScript) | Default | Meaning |
|---|---|---|
base_url / baseUrl | the service host, such as http://localhost:6400, with no vertical on the end | |
vertical | none | the vertical to read and write. Every call except list_verticals / get_vertical needs it, and fails before sending anything without it |
api_key / apiKey | the project key. Needs Recommendation enabled on the project | |
user_id / userId | sent as X-User-Id. Required by the service. It names who acts, not whom you recommend for | |
user_role / userRole | none | sent as X-User-Role, which decides what the call may do (below) |
timeout | 30.0 s / 30000 ms | per-request timeout |
max_retries / maxRetries | 3 | retries on network errors and 5xx |
In Python base_url, api_key and timeout can also be passed positionally; the rest are keyword-only. AsyncRecommendationClient has the same methods with await, and closes with await client.aclose().
X-User-Role decides what the call may do: admin, owner and service_role can read, write and train. Any other role, or none, can only read; a write or train call is a 403 (AiceForbiddenError).
Two different users
user_id on the client is the person operating the call in your system. The user_id you pass to recommend and track is the end user you are recommending for. They are separate, and the engine's users are identified by any string you choose (up to 255 characters).
The loop
Register users and items
Users and items must exist before events can refer to them, so register each one first. Metadata becomes features the model can learn from, so include what describes them.
user = client.create_user("user-1", metadata={"country": "KE", "age_group": "18-25"})
item = client.create_item("item-42", metadata={"category": "Electronics", "brand": "acme"})
print(user.user_id, user.created_at, item.item_id, item.project_id)
client.update_user("user-1", metadata={"country": "KE", "age_group": "26-35"})- Creating an ID that already exists is a
409(ConflictErrorin both languages). Treat it as "already registered". update_userandupdate_itemreplace the wholemetadata; they don't merge. Send the complete set.- An
item_idonly has to be unique within the vertical, and auser_idwithin the project. - Metadata is capped at 64 KiB per user or item.
- If a model has already been trained, a new item gets a content-based embedding straight away, so it can be recommended before the next training run. A catalog that changes often benefits from registering items as they appear.
get_user,get_itemraiseNotFoundErrorfor an unknown ID.delete_item/deleteItemremoves an item from candidates and future training, with its events, embeddings and popularity.anonymise_user/anonymiseUseris the right-to-erasure call. It replaces the user's ID with a random token everywhere and clears their profile and their events' metadata. Their events stay as anonymous training data. It can't be undone, and the old ID returns404afterwards. Users are never deleted outright.
Track interactions
Send an event whenever a user does something that signals interest. The event type is a string you choose, such as view, click, add_to_cart or purchase. How much each type counts is the interaction_weights setting in your project's configuration.
from datetime import datetime, timezone
n = client.track(
"user-1", "item-42", "purchase",
timestamp=datetime.now(timezone.utc), # optional; the server's clock if omitted
metadata={"price": 29.99}, # optional; up to 50 keys
)track sends one event and returns how many were ingested (1). An event naming a user or item that isn't registered is a 422 (ValidationError). An event's metadata is capped at 16 KiB, and a timestamp more than an hour in the future is rejected. Backfilled timestamps in the past are fine.
For a backfill or a queue drain, track_batch / trackBatch sends up to 10,000 events in one call. It ingests the valid ones and reports the rest instead of failing the whole call:
from aice_recommendation import Event
result = client.track_batch([
Event("user-1", "item-42", "view"),
Event("user-2", "item-7", "purchase", timestamp=then, metadata={"price": 12.5}),
])
print(result.ingested_count, result.failed_count, result.errors) # errors: [{"index": 1, "reason": "…"}]Train
Training runs in the background. Start it and poll the job:
import time
job = client.train(epochs=20) # epochs: 1–200, default 20
while True:
status = client.job_status(job.job_id)
if status.status in ("complete", "failed", "cancelled"):
break
time.sleep(5)
if status.status == "complete":
print(status.result["metrics"]) # recall@10, ndcg@10, coverage
else:
print(status.error)A job's status goes pending → running → complete or failed, or cancelled if you cancel it while pending. A vertical has at most one pending run, so calling train while one is pending returns that same job, and a burst of requests becomes a single run. The job reads the configuration when it starts running, so a config change made while it is pending is included.
When a job completes, result describes the model: n_users, n_items, n_interactions, embedding_dim, epochs, duration_seconds and metrics. metrics comes from holding back a slice of each user's history and checking whether the model predicts it: recall@10, ndcg@10 and catalog coverage. It is {} when there wasn't enough data to evaluate. Track it across runs to see whether the model is improving. A job that keeps failing is eventually marked failed with an explanation in error.
You can also train from the console's Training tab.
Later, or on a schedule. run_after books a run for a later time, up to 90 days ahead, and a pending run can be moved or cancelled. A recurring schedule is a cron expression in an IANA time zone that fires at most once an hour. A vertical has one schedule, and setting it replaces the old one.
from datetime import datetime, timezone
job = client.train(run_after=datetime(2026, 11, 2, 3, tzinfo=timezone.utc))
client.reschedule_job(job.job_id, datetime(2026, 11, 3, 3, tzinfo=timezone.utc))
client.cancel_job(job.job_id) # ConflictError once it has started
schedule = client.set_schedule("0 3 * * *", timezone="Africa/Nairobi", epochs=20)
print(schedule.next_run_at)
client.get_schedule() # None when there is no schedule
client.delete_schedule()run_after needs a time zone. In Python, pass an aware datetime. In TypeScript, pass an ISO string with an offset or Z.
Recommend
result = client.recommend("user-1", n=10) # n: 1–200, default 10
for rec in result.recommendations:
print(rec.rank, rec.item_id, rec.score, rec.explanation)result.count is how many came back. Each recommendation has an explanation describing why it was chosen, including:
| Key | Meaning |
|---|---|
source or strategy | which path produced it (see below) |
model_version | when the model that produced it was trained, or null if none has been. Log it next to your conversion events to see which training run is working |
task_scores | per-event-type probabilities (for example the chance of a purchase), when a trained ranker served the request |
rules_applied, original_score, final_score | which of your re-ranking rules adjusted the score |
Cold start. A user the model has never seen is not an error. The engine tries, in order: content_cold_start (the user's profile metadata matches your configured user features, so the trained model can place them), preference_match (their metadata matches a preference map you configured, such as preferred genres, blended with popularity), and finally popular_fallback (what is popular overall). explanation.strategy tells you which one fired. Registering users with good metadata is what makes the first recommendations good.
For a user the model does know, their most recent positive interactions are blended in, so what someone does in this session shapes the next list without waiting for retraining.
Configuration
get_config returns the vertical's base settings, your project's overrides, and the effective result of the two.
cfg = client.get_config()
print(cfg.vertical, cfg.overrides)
print(cfg.effective["interaction_weights"])
cfg = client.update_config({
"interaction_weights": [{"event_type": "view", "weight": 2.0}],
})update_config replaces the overrides, so send the whole set each time, or {} to go back to the vertical's defaults. Within what you send, the pieces combine with the base like this:
| Setting | How your value combines with the base |
|---|---|
interaction_weights | merged by event_type; a weight of null removes that type |
user_features, item_features | merged by name; "remove": true deletes one |
rerank_rules, cold_start_preference_map | the whole list is replaced |
other values (session_recent_n, candidate_pool_multiplier…) | replaced directly |
vertical, embedding_dim and model_backend are locked. Naming an unknown or locked key, or a malformed value, is a 422. The console's Ranking config page edits the same thing. Settings that shape the model (features, weights) only affect a model once you train again.
Training and cross-ranker settings are set by the platform. loss, learning_rate, batch_size, hidden_dims, n_negatives and the cross_ranker_* keys decide what a training run costs, so the AICE platform team sets them per project. get_config shows them in overrides once set, and update_config keeps them whatever you send: sending one back unchanged is fine, changing or adding one is a 403.
get_config_schema / getConfigSchema describes every key: its group, type, default, whether it is locked, whether it applies_at the next request (serve) or the next training run (train), and required_role (super_admin for the platform's keys). The console builds its config form from it, and you can use it to build your own.
Verticals
A vertical is a starting configuration for a kind of product. list_verticals returns [{id, name}] and get_vertical(name) returns {id, name, config}, the base settings you would be overriding. Both are public, need no key, and work on any client, including one built without a vertical.
Typed results
Unlike the other services, this client returns typed objects rather than plain dictionaries. Python returns dataclasses with snake_case fields; TypeScript returns interfaces with camelCase fields.
| Result | Python fields | TypeScript fields |
|---|---|---|
User / UserResult | user_id, organization_id, metadata, created_at, updated_at | userId, organizationId, metadata, createdAt, updatedAt |
Item / ItemResult | item_id, project_id, metadata, created_at, updated_at | itemId, projectId, … |
RecommendResult | user_id, recommendations, count | userId, recommendations, count |
Recommendation | item_id, score, rank, explanation | itemId, score, rank, explanation |
TrainJob | job_id, status, message, run_after | jobId, status, message, runAfter |
TrainJobStatus | job_id, status, epochs, run_after, enqueued_at, started_at, completed_at, result, error | jobId, status, epochs, runAfter, enqueuedAt, startedAt, completedAt, result, error |
TrainSchedule | cron, timezone, epochs, enabled, next_run_at, last_enqueued_at, last_job_id | cron, timezone, epochs, enabled, nextRunAt, lastEnqueuedAt, lastJobId |
BatchIngestResult | ingested_count, failed_count, errors, message | ingestedCount, failedCount, errors, message |
ProjectConfig | vertical, base, overrides, effective | same |
Vertical / VerticalSummary | id, name, config | same |
Timestamps are ISO 8601 strings in both. The metadata and explanation objects keep the server's snake_case keys.
Reference
{v} is the client's vertical. The SDK covers every route the engine serves to a project key.
| Method (Python / TypeScript) | Endpoint |
|---|---|
create_user / createUser | POST /{v}/users |
get_user / getUser | GET /{v}/users/{id} |
update_user / updateUser | PUT /{v}/users/{id} |
anonymise_user / anonymiseUser | POST /{v}/users/{id}/anonymise |
create_item / createItem | POST /{v}/items |
get_item / getItem | GET /{v}/items/{id} |
update_item / updateItem | PUT /{v}/items/{id} |
delete_item / deleteItem | DELETE /{v}/items/{id} |
track | POST /{v}/ingest |
track_batch / trackBatch | POST /{v}/ingest/batch |
recommend | GET /{v}/recommend/{user_id}?n= |
train | POST /{v}/train |
job_status / jobStatus | GET /{v}/train/{job_id} |
reschedule_job / rescheduleJob | PATCH /{v}/train/{job_id} |
cancel_job / cancelJob | DELETE /{v}/train/{job_id} |
get_schedule / getSchedule | GET /{v}/train/schedule |
set_schedule / setSchedule | PUT /{v}/train/schedule |
delete_schedule / deleteSchedule | DELETE /{v}/train/schedule |
get_config / getConfig | GET /{v}/config |
get_config_schema / getConfigSchema | GET /{v}/config/schema |
update_config / updateConfig | PUT /{v}/config |
list_verticals / listVerticals | GET /verticals |
get_vertical / getVertical | GET /verticals/{name} |
IDs are escaped as a single path segment, so an ID containing / or ? is safe.
Errors
The client raises the shared AICE errors.
| Situation | Python | TypeScript |
|---|---|---|
401 bad key or missing user_id | AuthenticationError | AuthenticationError |
403 role can't write or train, or a config change to a training or cross-ranker key | RecommendationError with status_code == 403 | AiceForbiddenError |
404 unknown user, item or job | NotFoundError | NotFoundError |
409 already registered, or rescheduling or cancelling a run that has already started | ConflictError | ConflictError |
422 bad value, unregistered user or item, unknown config key | ValidationError | ValidationError |
5xx | ServerError | ServerError |
In Python each of these also derives from RecommendationError, so except RecommendationError catches every error this client raises, and a handler for the matching aice_core class catches it too. In TypeScript, RecommendationError is the same class as AiceError.
GET, PUT and DELETE calls always retry on transient failures. POST and PATCH calls (create_*, track, track_batch, train, anonymise_user, reschedule_job) retry under an automatic Idempotency-Key. See Errors and retries.
Upgrading to the vertical argument
aice-recommendation 0.0.2 and @aiceafrica/recommendation 0.2 picked the vertical by ending the base URL with it. aice-recommendation 0.1.0 and @aiceafrica/recommendation 0.3.0 take it as its own argument, which also lets list_verticals and get_vertical work from the same client:
| Before | Now |
|---|---|
RecommendationClient(base_url="http://localhost:6400/ecommerce", …) | RecommendationClient(base_url="http://localhost:6400", vertical="ecommerce", …) |
new RecommendationClient({ baseUrl: "http://localhost:6400/ecommerce", … }) | new RecommendationClient({ baseUrl: "http://localhost:6400", vertical: "ecommerce", … }) |
umbrella base_urls={"reco": "…/ecommerce"} | base_urls={"reco": "…"}, reco_vertical="ecommerce" (TypeScript: recoVertical) |
A base URL that still ends with the vertical is refused when the client is built, because every call would otherwise go to /ecommerce/ecommerce/…. The rest of the API is unchanged, apart from Python's recommend() no longer taking persist. These versions add batch ingest, item deletion, user anonymisation, scheduled training and the config schema.
Migrating from reco-sdk
Before aice-recommendation 0.0.2 / @aiceafrica/recommendation 0.2.0 this package was aice-reco-sdk / @aice/reco-sdk with a RecoClient class. Only the names changed:
| Before | After |
|---|---|
from reco import RecoClient | from aice_recommendation import RecommendationClient |
import { RecoClient } from "@aice/reco-sdk" | import { RecommendationClient } from "@aiceafrica/recommendation" |
RecoError | RecommendationError |
Method names, arguments and responses are unchanged. The Python package also gained AsyncRecommendationClient.