RaiCentral

Docs / Getting started

Quickstart

Start a local instance and run an agent that is allowed, held for approval, and denied.

You will register one agent and one tool, add two rules, and run a program that sends three orders. Allow about fifteen minutes, mostly for the first container build.

Before you start

  • Docker with Docker Compose 2.24 or newer
  • Python 3.10 or newer
  • Git

1. Start RaiCentral

macOS / Linux
git clone https://github.com/ztechnium/raicentral.git
cd raicentral
cp .env.example .env
docker compose up --build
Windows PowerShell
git clone https://github.com/ztechnium/raicentral.git
cd raicentral
Copy-Item .env.example .env
docker compose up --build

Wait until the API reports healthy. The console is at http://localhost:3000 and the API at http://localhost:8001. The development sign-in is [email protected] with password ChangeMe123!.

On a brand-new database the first sign-in can return 401, because the development administrator is created by the first call to a protected route. Run curl http://localhost:8001/v1/auth/me once (a 401 response is expected), then sign in.

2. Register the agent, tool and rules

In a second terminal, install the Python SDK and save this program as setup_rai.py. Run it once: the keys it creates must be unique.

bash
pip install rai-control-plane-sdk
python setup_rai.py
setup_rai.py
"""Register one agent, one tool and two rules in a local RaiCentral instance."""

import os

import httpx

BASE = os.getenv("RAI_BASE_URL", "http://localhost:8001")

api = httpx.Client(base_url=BASE, timeout=30)


def call(method: str, path: str, **body):
    response = api.request(method, path, json=body)
    if response.is_error:
        raise SystemExit(f"{method} {path} -> {response.status_code}: {response.text}")
    return response.json()


# 1. Sign in
token = call(
    "POST",
    "/v1/auth/login",
    email=os.getenv("RAI_ADMIN_EMAIL", "[email protected]"),
    password=os.getenv("RAI_ADMIN_PASSWORD", "ChangeMe123!"),
)["access_token"]
api.headers["Authorization"] = f"Bearer {token}"

# 2. Register the AI system, agent and tool
system = call("POST", "/v1/ai-systems", system_key="orders-ai", name="Orders AI", risk_tier="HIGH")
agent = call("POST", f"/v1/ai-systems/{system['id']}/agents", agent_key="orders-agent", name="Orders agent")
tool = call(
    "POST",
    "/v1/registry/tools",
    tool_key="place_order",
    name="Place order",
    description="Create a customer order.",
    category="sales",
    consequential_action=False,  # True always requires approval, whatever the rules say
)

# 3. Create a version and declare what it may use
version = call("POST", f"/v1/agents/{agent['id']}/versions", change_summary="First version")
call(
    "POST",
    f"/v1/agent-versions/{version['id']}/dependencies",
    resource_type="tool",
    resource_id=tool["id"],
    required=True,
)

# 4. Move the system, agent and version to APPROVED
for path in (
    f"/v1/ai-systems/{system['id']}",
    f"/v1/agents/{agent['id']}",
    f"/v1/agent-versions/{version['id']}",
):
    for status in ("UNDER_REVIEW", "APPROVED"):
        call("POST", f"{path}/lifecycle", status=status)


# 5. Add the rules: approval from 1,000 and a hard stop from 10,000
def tool_rule(title: str, effect: str, minimum: int, **extra):
    call(
        "POST",
        f"/v1/ai-systems/{system['id']}/policies/tool-rules",
        title=title,
        tool_id=tool["id"],
        effect=effect,
        **extra,
        conditions=[
            {"parameter_path": "amount", "operator": "gte", "value_type": "number", "value": minimum}
        ],
    )


tool_rule("Approve orders from 1000", "REQUIRE_APPROVAL", 1000, required_approver_role="rai_officer")
tool_rule("Block orders from 10000", "DENY", 10000)

# 6. Give the agent an identity, a credential and an SDK integration
identity = call(
    "POST",
    "/v1/runtime-identities",
    agent_id=agent["id"],
    agent_version_id=version["id"],
    name="orders-dev",
    environment="DEVELOPMENT",
)
credential = call("POST", f"/v1/runtime-identities/{identity['id']}/credentials")
integration = call(
    "POST",
    "/v1/productization/integrations",
    integration_key="orders-app",
    name="Orders application",
    runtime_identity_id=identity["id"],
    environment="DEVELOPMENT",
)

print("\nSave these. The key is shown only once.\n")
print(f"RAI_BASE_URL={BASE}")
print(f"RAI_AGENT_KEY={credential['plaintext_secret']}")
print(f"RAI_INTEGRATION_ID={integration['id']}")

The program prints three values. Export them in the shell that will run your agent.

macOS / Linux
export RAI_BASE_URL=http://localhost:8001
export RAI_AGENT_KEY=<printed key>
export RAI_INTEGRATION_ID=<printed id>
Windows PowerShell
$env:RAI_BASE_URL = "http://localhost:8001"
$env:RAI_AGENT_KEY = "<printed key>"
$env:RAI_INTEGRATION_ID = "<printed id>"

3. Run the agent

Save the program below as agent.py and run python agent.py.

agent.py
import os
import time
from uuid import uuid4

from rai_sdk import RAIClient

client = RAIClient(
    os.environ["RAI_BASE_URL"],
    api_key=os.environ["RAI_AGENT_KEY"],
    integration_id=os.environ["RAI_INTEGRATION_ID"],
)


def place_order(amount: int) -> None:
    print(f"  order for {amount} created")  # your real side effect


def governed_order(amount: int) -> None:
    session = client.start_session(external_session_id=str(uuid4()), channel="app")
    action = {"tool": "place_order", "parameters": {"amount": amount, "currency": "USD"}}
    decision = session.authorize_action(**action)
    print(f"{amount}: {decision.decision} - {decision.human_message}")

    if decision.decision == "REQUIRE_APPROVAL":
        print("  waiting for a reviewer in the console (Approvals)...")
        status = client.get_approval_status(decision.approval_request_id)
        while not status["terminal"] and not status["can_retry"]:
            time.sleep(3)
            status = client.get_approval_status(decision.approval_request_id)
        if status["can_retry"]:
            # Send the same action again; the approval is used once.
            decision = session.authorize_action(
                **action, approval_request_id=decision.approval_request_id
            )
            print(f"  retry: {decision.decision}")

    if decision.allowed:
        place_order(amount)
        decision.report_execution(client, status="SUCCEEDED")

    session.end()


client.heartbeat()
for amount in (250, 2500, 15000):
    governed_order(amount)
client.close()

4. Approve the held order

The second order pauses. In the console, open Approvals, select the request and choose Approve this action once. The program sends the same action again and continues. Requests expire after 15 minutes.

Expected output
250: ALLOW - No matching tool rules; default allow after authority validation.
  order for 250 created
2500: REQUIRE_APPROVAL - Approve orders from 1000: REQUIRE_APPROVAL
  waiting for a reviewer in the console (Approvals)...
  retry: ALLOW
  order for 2500 created
15000: DENY - Approve orders from 1000: REQUIRE_APPROVAL; Block orders from 10000: DENY
An approval request shows who asked, what for, and why it was held · Community Edition console · sample data

/governance/approvals/{request}

Approval request for a USD 9,100 purchase order with identity, requirement and decision actions

The same agent in Node.js

Use the same environment variables. Install with npm install @ztechnium/rai-sdk and run node agent.js.

agent.js (CommonJS)
const { randomUUID } = require("node:crypto");
const { RAIClient } = require("@ztechnium/rai-sdk");

const client = new RAIClient({
  baseUrl: process.env.RAI_BASE_URL,
  apiKey: process.env.RAI_AGENT_KEY,
  integrationId: process.env.RAI_INTEGRATION_ID,
});

async function main() {
  await client.heartbeat();
  for (const amount of [250, 2500, 15000]) {
    const session = await client.startSession({ externalSessionId: randomUUID(), channel: "app" });
    const decision = await session.authorizeAction({
      tool: "place_order",
      parameters: { amount, currency: "USD" },
    });
    console.log(`${amount}: ${decision.decision} - ${decision.humanMessage}`);
    if (decision.allowed) {
      await decision.reportExecution(client, { status: "SUCCEEDED" });
    } else if (decision.approvalRequestId) {
      const status = await client.request("GET", `/sdk/v1/approvals/${decision.approvalRequestId}`);
      console.log("  approval", status.status, status.terminal, status.can_retry);
    }
    await session.end();
  }
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});

Next steps

  • Open Trajectories to follow each session.
  • Read Policies to understand the default outcome when no rule matches.
  • Run the bundled examples for five more AI systems.