Model inference APIs
Serve a preloaded neural classifier or configured language model through fixed native routes, explicit JSON schemas, OpenAPI, bounded admission, credentials and HTTPS.
Implementedaner.api exposes a preconfigured Aner model through a native HTTP service. A fitted neural classifier accepts validated numerical rows and returns class predictions and probabilities. A language model route uses a configured LLMClient or a preloaded native LLMModel. Native routes support streaming, timing telemetry and bounded persistent conversation KV. Model construction, training, checkpoint selection, device placement, and credentials remain explicit program decisions.
Module guide
Begin by describing a configured app, then train or load a classifier (or configure an LLM client), register routes, add the intended authentication/transport settings, and finally call serve in a foreground program. aner.api is one module with immutable builders; route names and transport settings are not separate imports.
| Task | Reference | Complete program |
|---|---|---|
| Inspect an interface without opening a listener | Description only example | OpenAPI configuration |
| Serve a small local classifier | Neural classifier | Local Iris API |
| Separate training from service startup | Load once | Train checkpoint, then checkpoint API |
| Protect an exposed listener | Authentication and HTTPS, aner.secrets | Secure API; requires your checkpoint, dedicated credential and TLS files |
| Serve one configured language model | LLM route, aner.llm | Local completion API; requires your running model service |
| Serve local weights directly | Native chat route, Native local models | Native chat API; requires a native engine build and local GGUF |
| Look up every builder and HTTP contract | API reference, endpoints, limits/errors | Checking these programs opens no listener |
Describe an app without starting a service
The complete description only program constructs an authenticated app with a fictional LLM endpoint and prints its OpenAPI schema. It requires no provider, checkpoint, configured credential or open port:
import aner.api
import aner.llm
import aner.secrets
let model = llm.client(provider: "vllm", model: "example-model",
endpoint: "https://llm.example.invalid/v1",
key: secrets.stored("example-llm-key"))
let app = api.app("Example completion service")
.llm("/generate", model)
.auth(secrets.stored("example-api-token"))
.bind(host: "127.0.0.1", port: 8000)
.limits(max_rows: 64, timeout_ms: 10000)
.output_limit(max_tokens: 256)
.rate_limit(requests_per_minute: 30)
print(app.openapi())Run aner check examples/api_description.aner, then aner examples/api_description.aner. The JSON describes /generate, metadata routes and bearer authentication without resolving either credential or contacting the endpoint. Upstream and inbound credentials are deliberately separate. Replace the fictional settings and configure both credentials before adding app.serve(); serving resolves its inbound credential and blocks until stopped, and inference requests may trigger upstream work.
Capability boundary
The current module serves fitted neural classifiers, configured language model clients and preloaded native language models. It provides immutable route configuration, strict JSON contracts, OpenAPI 3.1 description, bounded transport, and optional native TLS and bearer authentication. Native model routes additionally support NDJSON streaming and explicitly identified KV sessions. It does not execute arbitrary request code, accept uploaded checkpoints, train models in a request, expose general callback routes, or discover remote models. A request cannot choose another provider, endpoint, credential, or model.
A service starts in the foreground and remains running until stopped. The default listener is 127.0.0.1:8000, accessible only from the same host. A loopback listener has no authentication unless explicitly configured; local processes can contact it. Use authentication when the host is shared or a trusted reverse proxy exposes that listener.
Serve a neural classifier
The local example trains a small classifier once, before accepting requests:
import aner.api
import aner.dataset
import aner.nn
import aner.ml
let split = dataset.iris().split(test: 0.2, seed: 2026)
let network = nn.sequential(seed: 42)
.dense(inputs: 4, outputs: 8).tanh()
.dense(inputs: 8, outputs: 3)
let model = ml.classifier(network, standardize: true)
.fit(split.train(), epochs: 200, rate: 0.1)
let app = api.app("Iris inference").model("/predict", model)
app.serve()The fitted classifier retains preprocessing learned from training rows. Inference applies that same preprocessing to incoming feature rows; it does not refit normalization or use held out labels. The service shares the preloaded immutable fitted model across requests. A neural route preserves the fitted model's effective device and precision; serving does not silently retrain, move the model, or lower precision.
In a second terminal, send one feature row in the model's exact column order:
curl --fail-with-body http://127.0.0.1:8000/predict \
-H 'Content-Type: application/json' \
--data '{"inputs":[[5.1,3.5,1.4,0.2]]}'The request object contains exactly inputs, a nonempty matrix of finite numbers. Every row must have the fitted feature width, four in this example. Rows use the units and column order documented by the training dataset. The default maximum is 256 rows per request; max_rows can be set from 1 through 4096, subject to the request byte and numerical element bounds. No labels, dataset paths, model paths, credentials, or additional fields are admitted.
The response has this structure; probability values depend on the trained checkpoint:
{"predictions":[0],"probabilities":[[0.97,0.02,0.01]]}predictions contains one zero based class ID per input row. probabilities contains one probability row in the fitted class order per input row. The probabilities shown are illustrative, not a measured result or an accuracy guarantee. Retain the class mapping and feature schema with the model's deployment documentation.
Load once and organize the service
Training and serving can be separate programs. Run the checkpoint preparation example from a fresh working directory to create iris.anermodel. That example refuses to overwrite an existing checkpoint through the native model contract.
The checkpoint service example loads that checkpoint once and uses a class to retain the configured application:
import aner.api
import aner.ml
class InferenceService {
let app: APIApp
fn run() {
app.serve()
}
}
let model = ml.load_classifier("iris.anermodel")
let service = InferenceService(
app: api.app("Iris inference").model("/predict", model))
service.run()An APIApp is an opaque immutable configuration value. Builder methods return a new app; assign the result or chain calls. App construction and OpenAPI generation bind no socket and resolve no secret. A model route is registered before serving; request bodies cannot replace its checkpoint. aner check validates the source without loading a checkpoint, training a model, or opening a listener.
Authenticate and use HTTPS
Create a dedicated service credential with 32 through 2048 visible ASCII characters without spaces using hidden terminal input:
aner secrets set inference-apiUse a different credential from an upstream provider key. A server bearer token authorizes access to this service; an OpenAI credential authorizes upstream provider work. Keep both outside source. On a headless host, use an explicit injected environment reference or managed file reference described in Credentials.
The secure example configures an explicit bind address, token reference, and TLS files:
import aner.api
import aner.ml
import aner.secrets
let model = ml.load_classifier("iris.anermodel")
let app = api.app("Iris inference")
.model("/predict", model)
.auth(secrets.stored("inference-api"))
.tls(certificate: "server.pem", private_key: "server-key.pem")
.bind(host: "0.0.0.0", port: 8443)
.hostname("models.example.org")
.limits(max_rows: 64, timeout_ms: 10000)
app.serve()A nonloopback bind requires both native TLS and an explicit credential reference. Wildcard binds such as 0.0.0.0 and :: additionally require an explicit permitted hostname. api.hostname adds at most eight exact hostname or IP aliases; URLs, ports, and wildcards are rejected. Clients use the hostname covered by the TLS certificate, models.example.org in this example. The native service validates the HTTP Host against the bind address or configured aliases and the actual listener port. External plain HTTP and anonymous external listeners fail before service admission. Host names other than localhost are not resolved for binding; supply an explicit IPv4 or IPv6 address. localhost binds IPv4 loopback. Native TLS uses a certificate chain and unencrypted private key prepared outside the program. Both TLS files must be readable regular PEM files without leaf symlinks, with 1 through 65536 bytes per file. Each file is opened once; type and private key permission checks and bounded reads apply to that exact open descriptor. The TLS context loads the validated bytes rather than reopening a path. The certificate chain and private key are loaded once at startup; restart the service after certificate renewal or key replacement. On POSIX, the private key must be owned by the current user with no group or other permissions, for example mode 0600 or 0400. api.tls_available() reports this engine's direct TLS build capability on the current platform without starting a listener or reading key files. On supported POSIX hosts, native TLS requires a compatible build with an OpenSSL 3 provider, requires TLS 1.2 or newer, and admits modern authenticated encryption suites. Native TLS serving is unavailable on Windows until private key access control verification is implemented; use an authenticated loopback service behind a trusted HTTPS gateway. Encrypted private keys fail promptly without a passphrase prompt. The runtime rejects invalid files rather than disabling verification or generating a self signed certificate silently.
A TLS enabled engine linked against shared OpenSSL 3 libraries needs those compatible libraries at process startup, even when serving HTTP. The capability query runs after the engine starts and cannot repair a loader failure caused by missing libraries. Choose a compatible engine and runtime, or an engine without direct TLS that serves authenticated loopback HTTP behind a trusted HTTPS gateway.
Clients send Authorization: Bearer TOKEN over verified HTTPS. Supply that header through the client's protected credential mechanism, avoiding literal tokens in saved examples, command history, URLs, notebooks, and logs. Clients must verify the certificate chain and requested hostname. The server has no session cookie, password login, or token issuance endpoint. A configured token protects inference and metadata routes, including health and OpenAPI. It is resolved once at service startup and compared using the native bounded constant time comparison. The resolved token remains cached in the running listener. Changing or deleting its credential store entry does not revoke that listener's existing token; stop or restart the service to apply rotation or removal. A restarted service must resolve a valid configured credential before accepting requests.
For deployment behind an existing HTTPS reverse proxy, retain the native loopback listener and configure authentication. Terminate verified public TLS at the trusted same host proxy, forward only intended routes, and protect access to the loopback upstream. Set the upstream Host to the native listener address and port, for example 127.0.0.1:8000; retain the public host in external TLS and routing configuration. The server does not treat X-Forwarded-Proto, X-Forwarded-For, or other forwarded headers as evidence of encryption or caller identity. It does not automatically configure a proxy, certificates, firewall, DNS, or an operating system service. Restrict ingress, set proxy body and timeout limits consistent with Aner, and let the deployment supervisor manage restarts.
Serve a configured language model
A route can share the same API listener with a configured LLMClient:
import aner.api
import aner.llm
let model = llm.client("ollama", "llama3.2:3b")
let app = api.app("Local completion").llm("/generate", model)
.output_limit(max_tokens: 256).rate_limit(requests_per_minute: 30)
app.serve()The language model service example requires the named local model to be installed and already served. A request contains a nonempty prompt and optional max_tokens and temperature. The application owns an output token ceiling through api.output_limit, with default 512 and configurable range 1 through 16384. A request above that configured ceiling is rejected before provider work. Omitting a request budget uses the smaller of 512 and the application ceiling. The example limits output to 256 tokens per request and admits 30 requests per minute. These limits bound admitted work; they are not provider billing guarantees. Temperature must be finite and from 0.0 through 2.0. Stricter provider limits still apply:
{"prompt":"Explain validation data.","max_tokens":64,"temperature":0.2}The response contains text, model, finish_reason, input_tokens, and output_tokens. Missing provider token accounting is represented as JSON null. Native LLMResponse token accessors use -1 for the same unavailable state; neither representation means zero usage. Completion limits and upstream transport requirements remain those of Language model connections. Upstream cloud requests can incur provider charges; configuring inbound service authentication does not replace the upstream credential. Application owners control data submitted to the preselected provider. Requests cannot supply arbitrary upstream URLs or credential labels.
Serve a native chat model
The memory aware local server guide provides CPU only and fitted local model examples, including models larger than available GPU VRAM.
The unpublished development Remote Devices guide and controller server example keep this HTTP listener on the application computer while a preselected native LLM worker owns the model and performs all inference/sampling on another computer. Connect and load explicitly before serving. Request bodies cannot change the worker, model or SSH configuration. A worker failure does not fall back to local execution or replay an incomplete stream.
Register a preloaded LLMModel with the same immutable api.llm builder. This
executes local weights directly, without an Ollama process:
import aner.api
import aner.llm
let model = llm.load("models/research-model.gguf", context: 16384,
device: "metal", kv_cache_type: "q8_0", flash_attention: "on")
.with_context_pool(max_idle: 1)
let app = api.app("Native chat").llm(path: "/chat", model: model)
.bind(host: "127.0.0.1", port: 11435)
.limits(max_rows: 64, timeout_ms: 120000)
.output_limit(max_tokens: 512).session_limit(max_sessions: 2)
app.serve()The complete example requires a compatible
local model and native engine. Choose device/cache settings supported on your
machine; the shown configuration targets Metal. The model and execution
configuration remain fixed for the route. The native request supplies exactly
one of prompt or messages, with optional max_tokens, temperature, seed,
session, reset_session, stream, model, and options fields. Unknown fields fail.
messages is an ordered array of 1..256 objects containing exactly role and
content; roles are system, user, and assistant. Native output budgets
are 0 through the server's output ceiling, temperature is finite in [0,2],
and seed is 0..4294967295. Defaults are min(512, ceiling), greedy temperature
0.0, seed 0, and stream:false. An optional model must exactly match the
route's model name or fingerprint; it cannot select or load a different model.
{"messages":[{"role":"user","content":"What is a validation set?"}],"session":"research-chat","max_tokens":128,"stream":true}Each request still supplies the complete intended conversation. To continue,
include the earlier messages, generated assistant text and next user message.
The session identifier selects reusable KV, not server owned message history.
Identifiers are case sensitive, 1..64 ASCII letters, digits, underscore, period
or hyphen, and are scoped to the registered route. reset_session:true requires
a session identifier and clears that session before processing the supplied
conversation. Omitting a session uses a stateless worker lease: its logical KV
and sampler start fresh, while a compatible empty context/workspace allocation
may come from the registered model's bounded pool. Such requests still report
cached_input_tokens:0. The default retains one idle context. Configure a
separate registered lease with model.with_context_pool(max_idle: 0) to disable
idle retention, or 1..4 to set its bound. The request cannot change this policy.
api.session_limit bounds retained sessions across all native routes of one
server: default 2, accepted range 1..16. An idle least recently used session may
be evicted to admit another; the caller's next complete history request remains
valid and recomputes the missing prefix. A busy session returns 409
session_busy; a named session registry containing only busy entries returns 503
session_capacity. Each retained context consumes memory, so choose the bound
alongside context capacity and model size. Separate API server instances retain
separate named session registries. Stateless pools belong to the registered
model leases, so registering the same model in multiple routes or servers may
share its compatible empty context pool. Model weights remain shared through
their native leases. Named conversation sessions remain independent of
stateless pooling, and resetting a session still releases its own KV context.
A nonstreaming response includes text, model, fingerprint, backend,
finish_reason, token counts, cached_input_tokens, cache_write_input_tokens,
tokens_per_second and a timings object. It also includes
message:{"role":"assistant","content":"..."}, done_reason, and root
Ollama style duration/count aliases. Durations in timings use nanoseconds;
its measurement scope and decode step counts define throughput. Unknown outer
token/throughput fields are JSON null; unavailable fields inside the native
timings record retain its -1 sentinel. Client wall clock
time to first received text includes HTTP and server admission costs; the native
first token measurement covers its documented runtime stages.
Pool hits are allocation reuse, not prompt cache hits. The native timings
record includes pool reuse/counter snapshots and context clear duration; see
stateless context pools. Read
model.load_summary() before serving to inspect metadata admission, both
complete SHA256 verification passes, resident loading, and total startup time.
Startup timing is separate from each request's generation timing. Pooling can
retain idle KV storage, so evaluate the registered model's memory summary along
with the separate named session limit.
Streaming uses application/x-ndjson: token events contain done:false, a
response text piece and the equivalent assistant message.content. The final event has done:true
with the complete response fields and telemetry. UTF8 pieces are buffered until
complete characters can be sent. The transport closes after the final event.
An error after streaming headers may produce a terminal
{"done":true,"error":{"code":"native_inference_failed"}} event; a deadline
or disconnect may close the connection without one. Validate that the stream
ended successfully before treating its partial text as a completed response.
Native cancellation is cooperative between prefill/decode steps and discards
failed session state; an already running device kernel drains safely.
The native route supports a limited Ollama chat compatible subset. Its
options object accepts only num_predict, temperature, seed and num_ctx.
num_ctx, when supplied, must equal the loaded model's admitted context. Setting
the same generation control through both root and options fields is rejected;
choose one form. To use an existing Aner Ollama client, register the native
model at /api/chat and use the listener as the client's base endpoint:
// Server route: api.app().llm("/api/chat", model)
// Client identifier: the server's exact model.model() or fingerprint value.
let client = llm.client("ollama", "ARTIFACT_MODEL_NAME", "http://127.0.0.1:11435")GET /api/tags discovers the native models already configured on this listener.
Each models entry includes name, model, digest (the effective native
fingerprint), route, admitted context, backend, device,
details:{"format":"gguf"}, and memory and load objects. memory uses the
native model's memory summary scope, including the idle context pool counters
and estimates; it is not a measured process footprint. load is the original
base load timing record, including both full content verification passes. These
snapshots do not reload the model or collect another set of startup timings.
Use an entry's exact model or digest as the
chat request's model identifier, and its route for direct HTTP requests. There
is one entry per native route; multiple routes may refer to the same weights.
A service with only classifier or upstream client routes returns {"models":[]}.
Discovery performs no inference, loading, downloading or filesystem scan, and
does not return local artifact paths. It follows the same authentication, Host,
rate and metadata body rules as health and OpenAPI. This provides basic Ollama
model discovery fields for the configured native routes; it is not a full Ollama
model management API.
The client sends /api/chat; a custom path such as /chat remains available
for direct HTTP callers. Use the exact
model.model() name or model.fingerprint() as the request model identifier.
There is no dynamic model selection, model registry, model downloads,
keep_alive control, or complete Ollama generate API. The embedded pretrained
backend remains pinned llama.cpp; backend identity is reported so experiments
can distinguish serving changes from engine changes.
OpenAPI and endpoint contracts
app.openapi() returns the OpenAPI description without starting the listener. GET /openapi.json serves the same configured route description. Inference bodies are represented with explicit schemas, required fields, rejected additional fields, and numerical shape limits. Authenticated applications advertise the bearer security requirement. TLS configuration changes the transport, not the JSON inference contract.
| Endpoint | Method | Result |
|---|---|---|
/health | GET | Service health response; requires the bearer token when authentication is configured. |
/ready | GET | Readiness response; requires the bearer token when configured. Readiness does not run a trial inference. |
/openapi.json | GET | Generated OpenAPI 3.1 JSON. No credential value or private key content is included. |
/api/tags | GET | Configured native model identity/configuration, memory/pool snapshots and original base load timings. No local artifact paths; no model load or inference. |
| Registered classifier path | POST | Validated inputs matrix, then predictions and probabilities. |
| Registered language model client path | POST | Validated prompt and generation settings, then completion fields. |
| Registered native language model path | POST | Prompt or explicit messages, optional bounded session/streaming settings, then text and native telemetry. |
Route paths are fixed during application construction. Reserved metadata paths cannot be replaced. App titles contain 1 through 128 UTF8 bytes; at most 16 model routes may be registered. A route is a literal path with 2 through 128 ASCII characters drawn from letters, digits, slash, hyphen and underscore, with no repeated or trailing slash. Query strings, encoded route tricks, and alternative methods are rejected. JSON requests require Content-Type: application/json, optionally with UTF8 charset; compressed request bodies are unsupported. Browser requests containing Origin are rejected. CORS is disabled in this initial release, so the supported integration is service to service. A browser application should contact its own authenticated server integration rather than embed a shared service token in public client code.
Limits, reliability, and errors
Requests have a 1 MiB body limit and responses an 8 MiB limit. The parser accepts at most 32 headers with 4 KiB line bounds, and a 2 KiB request target. JSON nesting is bounded to 32 levels and 100000 structural nodes. A connection handles one request and then closes; keep alive, HTTP/2 and arbitrary request transfer encodings remain outside the current contract. NDJSON response streaming is available for native LLM routes only. Four socket workers admit at most eight additional queued connections. A full connection queue closes the new connection without pretending inference succeeded. Classifier and upstream client routes share serialized inference admission. Native routes admit one request per session; sessions sharing a native weight owner retain the engine's adapter registry serialization. Independent native weight owners do not use the classifier/provider inference lock.
The default global fixed minute rate limit is 120 parsed requests. api.rate_limit accepts 1 through 100000 requests per minute. Valid Host and authentication checks and the browser Origin exclusion run before this quota. Failed authentication and rejected Origin attempts do not consume the legitimate allowance. Admitted metadata calls, including health, readiness, OpenAPI and native model discovery, count toward it. An unauthenticated loopback app counts admitted local requests. A rate rejection returns 429 and Retry-After: 60; this is a conservative retry interval. The limit is neither per user nor shared between processes. Deployment ingress controls are still needed for a public service.
api.limits sets the admitted classifier row count and an absolute connection processing budget from 1 through 600000 ms. The default is 10000 ms, starting when a socket worker begins processing the connection. TLS handshake, headers, body reads, inference admission and response writes share that fixed budget; continuing to send small amounts of data does not reset it. The separate eight connection queue has a count bound; time spent there before a worker begins is outside this budget.
Expiry can close a connection without returning an HTTP 504 or JSON response. A running CPU or GPU operation cannot be forcibly preempted: it drains, and its late result is discarded. The budget is therefore not a hard wall clock bound for arbitrary model computation. Configure rows, model size, upstream timeout, client deadline and proxy deadlines together. No retry is performed automatically; a client timeout can occur after inference began, so retries may repeat upstream provider work.
| HTTP status | Meaning |
|---|---|
| 400 | Invalid HTTP request syntax, Host, query string, or metadata body. |
| 401 | Missing or invalid bearer authentication. |
| 403 | Unsupported browser Origin request. |
| 404 | Unknown route. |
| 405 | Unsupported method for a known route. |
| 409 | The requested native conversation session is already busy. |
| 413 | Request body exceeds its bound. |
| 415 | Unsupported content type or body encoding. |
| 422 | Invalid JSON or request violates the registered input schema. |
| 429 | Global fixed minute request allowance exceeded. |
| 502 | Configured language model provider failed. |
| 503 | Inference admission is busy or unavailable. |
| 504 | Request exceeded its queue or completed inference deadline. |
| 500 | Sanitized internal failure. |
Native application configuration and serving failures use source located R3301 diagnostics. HTTP failures return a sanitized envelope such as {"error":{"code":"invalid_input"}} and do not include authorization values, prompts, generated text, model weights, private keys, or internal source traces. This protects native error reporting; explicitly printing ordinary input or output Strings retains ordinary program visibility. The module does not create an access log containing inference content. Each parsed response receives a locally generated X-Request-ID for caller correlation; an incoming identifier does not replace it.
Stop with Ctrl+C or an operating system termination signal. Shutdown stops new admission, skips queued connections and interrupts pending network waits. Active CPU or GPU computation drains subject to the boundaries above. A supervisor should allow for completion of an active native operation. Persist checkpoints before starting the service; requests do not mutate or save the fitted classifier.
API reference
| Call | Result | Contract |
|---|---|---|
api.app() | APIApp | Empty configuration titled Aner API, loopback port 8000, default bounds; no listener. |
api.app(title: String) | APIApp | Explicit nonempty application title. |
api.model(app: APIApp, path: String, model: FittedClassifier) | APIApp | New configuration with a fixed fitted classifier route. |
api.llm(app: APIApp, path: String, client: LLMClient) | APIApp | New configuration with a fixed language model route. |
api.llm(app: APIApp, path: String, model: LLMModel) | APIApp | New configuration serving preloaded local weights, explicit KV sessions, telemetry and optional streaming. |
api.bind(app: APIApp, host: String, port: Int64) | APIApp | Explicit IPv4/IPv6 bind (or localhost) and port from 1 through 65535; does not open a socket. |
api.hostname(app: APIApp, hostname: String) | APIApp | Add an explicit permitted Host alias, at most eight; wildcard binds require one. |
api.auth(app: APIApp, key: SecretRef) | APIApp | Explicit inbound bearer reference, resolved only at startup. |
api.tls(app: APIApp, certificate: String, private_key: String) | APIApp | Explicit certificate chain and private key file paths. |
api.limits(app: APIApp, max_rows: Int64, timeout_ms: Int64) | APIApp | Explicit row limit and absolute budget starting when a socket worker begins processing; active kernels cannot be preempted. |
api.rate_limit(app: APIApp, requests_per_minute: Int64) | APIApp | Process global fixed minute allowance, default 120, range 1 through 100000. |
api.output_limit(app: APIApp, max_tokens: Int64) | APIApp | Server owned ceiling for every language model route, default 512, range 1 through 16384. |
api.session_limit(app: APIApp, max_sessions: Int64) | APIApp | Server wide retained native session ceiling, default 2, range 1 through 16. Idle entries may be evicted. |
api.openapi(app: APIApp) | String | OpenAPI 3.1 JSON without network or credential resolution. |
api.tls_available() | Bool | Inspect native TLS build capability without opening a listener or reading TLS files. |
api.serve(app: APIApp) | Unit | Blocking foreground service using the configured listener. |
api.serve(app: APIApp, port: Int64) | Unit | Blocking foreground service with an explicit port override from 1 through 65535. |
Instance methods omit the first app parameter, for example app.model(path, model), app.auth(key), and app.serve(). Immutable builders require retaining their return value. A printed APIApp remains opaque and does not reveal routes, credentials, or model content. OpenAPI is an explicit interface description, not a secret export.
Development and production
Develop a model with protected Dataset roles, device reports, and bounded development observations before exposing inference. Both execution modes run the same validated routes and use the same precision, checkpoint, credentials, and transport settings. Production disables automatic development recording; it does not weaken input validation or silently enable external access. Inspect model training separately from a long running API process.
Use standalone .aner programs for the foreground listener. Calling serve in a notebook cell blocks that cell and its interpreter session until stopped; notebook request cells should contact a separately supervised API service. Checking the complete examples opens no listener. VS Code extension 0.1.35 or newer supplies APIApp signatures, immutable builder methods, security parameter help, and the apilocal, apicheckpoint, apiauth, apitls, and apillm snippets. The engine must also support aner.api; an editor update alone does not install the native module.
Time and space complexity
Let s be route descriptor bytes, q request bytes, r response bytes, b admitted input rows, f input feature width, and c output class count. For a Dense classifier, let layer widths be d0 through dL with d0 = f and dL = c. These bounds describe native serving overhead and inference arithmetic; network waits and an external language model's computation are separate.
| Operation | Time | Space |
|---|---|---|
| Create an empty app | O(title bytes) | O(title bytes) retained configuration |
| Immutable builder update | O(s) descriptor copying | O(s) new descriptors; fitted model handles share immutable storage |
| Generate OpenAPI | O(s) plus schema description bytes | O(schema description bytes) returned String |
| Parse, validate, and serialize a request | O(q + r) | O(q + r), within transport bounds |
| Dense classifier forward pass | O(b × sum of adjacent layer width products), plus preprocessing and activations | O(bf + bc + largest layer activations), plus retained model parameters and backend workspace |
| Return class IDs and probabilities | O(bc) | O(bc) response values, plus JSON bytes |
Each registered route retains its configured model or client; classifier routes also retain fitted preprocessing, native conversation sessions retain KV contexts, and a stateless model pool may retain its bounded count of empty context/workspace allocations. Neural inference does not build a training graph or retain gradients. CPU or accelerator libraries may allocate device context, kernels, and workspace beyond input/output storage; report actual device memory separately when benchmarking. The fixed socket worker, connection queue, native session and idle stateless context counts bound their respective bookkeeping or retained context counts, not total process RAM. A larger model still requires its full parameter storage. External completion latency and memory belong to the selected provider; no universal inference Big O or completion estimate is asserted.
See Neural networks, Neural learning, research, and devices, Tensor devices and performance, Credentials, and Language model connections for the underlying model and credential contracts.
Interface standards
The interface description follows OpenAPI 3.1. Methods, status codes and authentication challenges use the semantics in HTTP Semantics, RFC 9110. These standards describe interoperability; the admitted Aner routes and limits remain those defined above.
See the complete callable index for the native module and method name catalogue.