KairosClient Reference
The KairosClient is your single entry point into the Ananke ecosystem. It uses httpx for every request to the Kairos Nexus REST API. The streaming methods read the response as NDJSON, one trace step per line.
Initialization
Section titled “Initialization”from kairos import KairosClient
client = KairosClient( url="https://api.anankelabs.io", # Optional if KAIROS_URL is set api_key="krs_...", # Optional if KAIROS_API_KEY is set timeout=30.0, # Request timeout in seconds engine_version="1.4.4", # Optional pinned engine version max_retries=3, # Max transient error retries retry_backoff=1.0, # Exponential backoff base delay)Reproducibility via Version Pinning
Section titled “Reproducibility via Version Pinning”For peer-reviewed research, reproducible simulation traces are necessary years later. If you lock the engine_version, KAIROS guarantees bit-for-bit reproducibility.
# Pins your client to a specific release of the continuous physics engine.client = KairosClient(engine_version="1.4.4")If the requested engine version is no longer active on the server, the SDK raises an EngineVersionError. This error details the valid available constraints.
Running Simulations
Section titled “Running Simulations”The highest-level method to execute a scenario is .run(). It creates the simulation and streams the execution to completion.
client.run(...)
Section titled “client.run(...)”This method executes a scenario eagerly into memory.
trace = client.run( scenario=my_scenario, ticks=1000, organization_id="org_id" # Optional, for billing/tracking purposes)client.stream_run(...)
Section titled “client.stream_run(...)”If simulations cause Out-Of-Memory (OOM) errors when eagerly loaded, use the iterator.
# Yields TraceStep objects iteratively from an NDJSON streamfor step in client.stream_run(scenario, ticks=100_000): if step.stability < 0.1: print(f"Danger at tick {step.t}")Asynchronous Execution
Section titled “Asynchronous Execution”For high-throughput evaluations (for example, Monte Carlo sampling of different capability jumps), the client provides a full asyncio interface. The prefix a marks all async methods.
import asynciofrom kairos import KairosClientfrom kairos.domains.ai_safety import AISafetyScenario, AISafetyEventType
async def capability_sweep(): """Sweep over capability values to find the critical destabilization threshold.""" client = KairosClient()
async def run_one(capability): scenario = ( AISafetyScenario(f"sweep_{capability}", seed=capability) .add_model( name="model", capability_index=capability, alignment_score=70, guardrail_coverage=60, ) .add_event(100, AISafetyEventType.CAPABILITY_JUMP, target="model", magnitude=0.3) ) trace = await client.arun(scenario, ticks=500) return { "capability": capability, "final_phase": trace.final_phase(), "mean_stability": trace.mean_stability(), "basin_losses": len(trace.basin_losses()), }
# Run 51 simulations concurrently tasks = [run_one(cap) for cap in range(100, 1001, 18)] results = await asyncio.gather(*tasks)
for r in results: print(f" cap={r['capability']:>4} phase={r['final_phase']:<10} " f"stability={r['mean_stability']:.4f} losses={r['basin_losses']}")
asyncio.run(capability_sweep())For a full version with DataFrame collection and threshold analysis, see the Monte Carlo Parameter Sweep use case.
Error Handling & Resiliency
Section titled “Error Handling & Resiliency”The SDK is designed for integration into automated ML evaluation harness pipelines. The client catches and retries 429 Too Many Requests, 502 Bad Gateway, 503 Service Unavailable, and 504 Gateway Timeout status codes. It retries up to max_retries times with exponential backoff. On a 429, it waits at least the time in the Retry-After header.
By default, the client does not retry connection errors and timeouts on POST requests, such as simulation create and step. A retry of these requests can apply the mutation twice. To allow these retries, pass retry_mutations=True. Streaming methods never retry.
Exceptions
Section titled “Exceptions”Check kairos.errors for the exception hierarchy. Every SDK exception is a subclass of KairosError:
KairosError: Base class for all SDK errors. The client also raises it for connection failures after the last retry and for error responses that no subclass covers.AuthenticationError: Invalid or expired credentials (HTTP 401 or 403).NotFoundError: The requested resource does not exist (HTTP 404).RateLimitError: Standard 429 backoff failures (includesretry_after).IdempotencyError: An idempotency key was reused with a different request body (HTTP 409).UsageLimitError: The organization exceeded the limits of its license tier.SimulationError: Core engine calculation faults.ValidationError: Invalid scenario or input parameters (includeserrors). The domain scenario builders raise it before a request, and the client raises it for an HTTP 400 response.EngineVersionError: The pinned engine version is not available on the server (includesrequestedandavailable).