Colrows SDK for Python

The Colrows SDK connects your code to Colrows. Use it to build AI agents and apps grounded in the semantic layer, and to run your agents on your own compute. Most agent frameworks give an agent a loop and tools. They do not give it a shared meaning of "revenue", governed access to data, or proof that an answer is correct. Colrows adds that layer, and Quorum, the agent control plane, gives each run an identity, limits the agent to its semantic scope, records every tool call, and checks that each answer has real evidence. This page is the reference for the Python package: how to install it, what the two modules do, the three ways to build an agent, and how to run a worker.

The SDK is open source on GitHub.

The package, the developer documentation, the conformance fixtures, and the stock worker image live at github.com/colrows/colrows-sdk under the Apache License 2.0. It is production ready: the worker protocol is version 1, and the package runs governed agents against Colrows today. The Versions and support section covers releases and what is next.

What the SDK gives you

Your agent, your model, and your model provider key stay in your environment. Colrows never runs your agent code and never receives your model provider keys. The package has two parts.

ImportUse it to
colrows.semanticCall the Colrows tools directly: semantic search, the join graph, value resolution, verified queries, governed SQL, and document questions. AgentTools wraps the Agent REST API; AgentMcp wraps Agent MCP.
colrows.quorumRun agents for Quorum on compute that you own: Worker, RunContext, AgentFailure. colrows.quorum.loop adds the default semantic loop: default_agent.

The shared errors, ColrowsError, ToolError, and AuthenticationError, are on the top-level colrows import.

How Quorum agents run

Quorum stores the agent definition, issues a short-lived identity for each run, enforces the agent's semantic scope at the data boundary, records every tool call, and checks that each answer has real evidence. Your agents run on your own infrastructure: VMs, Kubernetes, EKS, or other compute that you own.

  1. An admin defines an agent in Quorum: its purpose, its semantic scope, its allowed tools, and its limits.
  2. A user or a schedule starts a run. Quorum puts the run in a queue.
  3. Your worker claims the run and gets a run token. The token works only for this run.
  4. Your agent calls Colrows tools with the run token. Quorum allows only the tools and the data in the agent's scope.
  5. Your worker sends the result. Quorum checks that every finding refers to real evidence from this run.
Outbound HTTPS only.

Calls to Colrows are outbound from your environment. Colrows never connects into your network. The worker refuses plain http:// except for local hosts, so the client secret never travels in clear text.

Install

pip install colrows                       # the core: worker, tools, results
pip install "colrows[agent,openai]"       # add the default semantic loop and a model provider

The core needs Python 3.10 or later, and depends only on httpx and pydantic. The default loop needs Python 3.11 or later and Pydantic AI. Provider extras are openai, anthropic, google, and bedrock. Framework adapters are mcp and langgraph, and otel adds OpenTelemetry spans; the default loop needs none of them.

Three ways to build an agent

Most teams should not write an agent loop, a verification step, or a retry policy. The SDK has them. Pick the level that fits the agent.

LevelYou writeColrows gives you
No codeNothing. An admin defines the agent in Quorum and selects a pattern.The stock worker: the default loop, the self-check, and a container image.
Low codeOne line to use the default loop in your own worker, plus your own steps around it.The default loop and the self-check.
Full codeYour own loop, or another framework.The governed tools, the run identity, and the result builders.

No code: run the stock worker

Run the stock worker on your own Kubernetes or VMs with your own model provider. No agent code. It runs the default loop for every agent that the worker client is assigned to in Quorum, so a new agent needs no change to the deployment.

export COLROWS_URL=https://colrows.example.com
export COLROWS_CLIENT_ID=... COLROWS_CLIENT_SECRET=...
export COLROWS_MODEL=openai:gpt-5 OPENAI_API_KEY=...
colrows quorum check   # checks the URL, the credentials, and the scope, and takes no run
colrows quorum serve

To serve only some agents, set COLROWS_AGENTS to their keys, separated by commas. For a self-hosted model with an OpenAI-compatible API, set COLROWS_MODEL_BASE_URL. The container image and a Kubernetes example are in the deploy/ directory.

Low code: the default loop in your worker

from colrows.quorum import Worker
from colrows.quorum.loop import default_agent

# Every agent of this worker client runs the default loop.
worker = Worker.from_env(default=default_agent(model="anthropic:claude-sonnet-5-5"))
worker.run_forever()

To run your own code for one agent and the default loop for the others, register that agent with @worker.agent("its-key"). default_agent accepts any Pydantic AI model, so you can add your own provider settings, retries, or fallback models.

Full code: write an agent

Write the agent function yourself and keep the governed tools, the run identity, and the result builders. Every number in a finding comes from the rows of the execution that it cites.

from colrows.quorum import Worker, RunContext

worker = Worker(
    base_url="https://colrows.example.com",
    client_id="...",       # a worker client with the quorum:worker scope
    client_secret="...",   # read it from your secret store
)

@worker.agent("revenue-analyst")
async def revenue_analyst(run: RunContext):
    question = run.input["question"]

    matches = await run.tools.search_semantic_entities(question)
    if not matches.get("entities"):
        await run.tools.report_semantic_gap(question, kind="MISSING_METRIC")
        return run.unable_to_answer("The semantic layer has no metric for this question.")

    # Runs the query, waits until it ends, and reads the first page of rows.
    page = await run.tools.run_verified_query(
        "vq-revenue-by-region",
        version=3,                       # agents run a known definition
        params={"period": "LAST_WEEK"},  # the verified query defines the types
    )
    columns = [column["name"] for column in page["columns"]]
    row = dict(zip(columns, page["rows"][0]))
    change = (row["this_week"] - row["last_week"]) / row["last_week"] * 100

    return run.answer(
        f"Net revenue in {row['region']} fell {abs(change):.0f}% week over week.",
        findings=[run.finding(f"{row['region']} fell from {row['last_week']:g} to {row['this_week']:g}.",
                              evidence=[run.query_evidence(page["executionId"])])],
    )

worker.run_forever()
Tool methodReturns
search_semantic_entities(query){"entities": [{"id", "entityType", "label", "description", ...}]}
run_query(query), run_verified_query(id, version, params)The first page of rows: executionId, columns, rows, nextCursor. It waits until the query ends.
execute_sql(query)The execution status, with no rows. It waits at most 5 seconds.
get_sql_execution_result(execution_id)A page of rows.
report_semantic_gap(term, kind)gapId, occurrences, inquiryOpened. kind is UNKNOWN_TERM, AMBIGUOUS_TERM, MISSING_METRIC, or MISSING_RELATIONSHIP.

Use another framework

To use LangGraph, another agent framework, or your own loop, keep the governed tools of the run and bring your own model calls. await run.harness() returns the system prompt and the allowed tools with their schemas.

from langgraph.prebuilt import create_react_agent
from colrows.quorum import langgraph as colrows_langgraph

@worker.agent("revenue-analyst")
async def agent(run):
    harness = await run.harness()
    graph = create_react_agent(model, await colrows_langgraph.tools(run), prompt=harness.system_prompt)
    state = await graph.ainvoke({"messages": [("user", run.input["question"])]})
    ...  # build the result with run.answer(...) and check it with run.self_check(...)
AdapterUse it when
colrows.quorum.langgraph.tools(run) (extra langgraph)Your agent is a LangGraph or LangChain agent. Each tool of the run becomes a LangChain tool, and each call goes through Agent MCP with the run token.
run.mcp_session() (extra mcp)Your framework takes an MCP client session. The results of this session go to the evidence ledger of the run, so the self-check sees them.
run.mcp_connection()Your framework builds its own MCP client. You get the Agent MCP URL and the run-token headers. Calls made this way do not reach the evidence ledger, so the worker cannot repair a result before it is sent. The answer check on the server still checks every finding.
  • Give the model only the tools in harness.tools. The control plane refuses the others.
  • Never offer raw SQL. A run token never allows it.
  • Give executeSQL and cancelSQLExecution a new idempotencyKey for each model call, and repeat a call that failed on the network with the same key.
  • A ToolCallFailed error is information for the model. Give it back to the model, and let the model try another allowed way.

Patterns

A pattern is a ready-made agent shape. An admin selects one in the agent spec with "pattern": "MONITOR". The pattern, the Colrows grounding rules, and the author's instructions become the agent's harness.

PatternWhat the agent does
ANALYSTAnswers one business question with evidence. The default.
MONITORChecks governed metrics against the thresholds in its instructions, usually on a schedule, and raises an alert.
INVESTIGATORExplains why a metric changed: measures the change and breaks it down by the connected dimensions.
DOCUMENT_ANALYSTAnswers from documents, and from governed data when the question needs numbers.

What the default loop does

The default loop knows how to use a semantic layer: find the meaning, resolve the values, prefer a verified query, read the rows, and cite the evidence. Generic agent frameworks do not know these steps.

  1. Gets the harness of the run: the system prompt, the allowed tools with their server schemas, and the limits.
  2. Lets the model call only the tools in the agent's spec, through Agent MCP with the run token. A tool error goes back to the model, so it can try another allowed way.
  3. Records each execution, each set of rows that the model read, and each document citation.
  4. Runs the self-check before it accepts an answer. The model must fix an answer that fails it.
  5. Returns an ANALYST_ANSWER result. The Quorum check on the server checks it again.

The self-check

The self-check repeats the rules of the Quorum check on the server, with the same rule codes, before the worker accepts an answer. It also checks two things that only the worker can check, because only the worker saw the rows: that a finding's numbers appear in the cited rows, and that the model read those rows. If the answer still fails after the repairs, the run fails with SELF_CHECK_FAILED, and Quorum does not retry it. The self-check runs for agent code that you write too; call await run.self_check_async(result) before you return a result. The number check is a check, not a proof, so a failed number is a warning, and evaluation suites measure answer quality.

Customer tools: call your own code

Most enterprises already have their domain logic as code: a simulation, a back-test, a pricing model, a scoring rule. The default loop can call these functions as tools. The agent spec declares each tool in tools.customer, a reviewer approves it, and your worker implements it. The function runs only in your worker. Colrows never calls it and never receives its arguments or its output.

from colrows.quorum import RunContext, Worker
from colrows.quorum.loop import default_agent

worker = Worker.from_env(default=default_agent("anthropic:claude-sonnet-5-5"))


@worker.tool("runBacktest")
async def run_backtest(run: RunContext, indexId: str, start: str, end: str) -> dict:
    prices = await run.tools.run_verified_query("vq-constituent-prices", version=4,
                                                params={"index": indexId, "start": start, "end": end})
    return await backtest_engine.run(indexId, prices)    # your existing code
  • The function is async def, takes the RunContext first, and returns a JSON value of at most 256 KB.
  • The loop checks the model's arguments against the declared inputSchema before it calls the function, and stops a call after its timeoutSeconds.
  • A run whose spec declares a tool that the worker did not register fails with CUSTOMER_TOOL_MISSING, which is not retried.
  • The worker records each call with digests of the arguments and the output, and with the query executions that the function read. An answer cites the call as COMPUTATION evidence. Set COLROWS_CODE_VERSION, for example to an image tag, so the record names the version of your code.
  • Agent code that you write calls a customer tool with await run.call_tool("runBacktest", {...}) and gets the same record.

The declaration rules are in customer tools.

Actions: let an agent act

An agent never sends a message or opens a ticket itself. It proposes actions in its result, the control plane checks the result and the proposals together, and a worker runs each released action with a handler. No action runs on a result that failed the check, and each action has a record. A control plane admin registers the action definitions, and the agent spec lists the ones that the agent may use.

Propose an action

The default loop proposes actions with no code from you: when a run may propose actions, the loop adds them to the instructions and to the answer schema. In agent code that you write, use run.propose:

result = run.answer("Alert: tower 1142 is above its limit.", findings, actions=[
    run.propose("notify-ops", {"channel": "ops", "text": "Tower 1142 is at 61 C."}, finding_refs=[0],
                dedupe_key="tower-1142-temperature"),
])

finding_refs are the indexes of the findings that justify the action, and each needs evidence. dedupe_key names the condition, so the action is not repeated inside the definition's dedupe window. The self-check applies the same proposal rules as the server.

Run released actions

from colrows.quorum import ActionContext, ActionFailed, ActionResult

@worker.action_handler("teams.ops")
async def notify(action: ActionContext) -> ActionResult:
    message = await teams.post(CHANNELS[action.input["channel"]], action.input["text"], link=action.run_url)
    return ActionResult(external_ref=message.id)
RuleWhat it means for you
The worker claims only actions whose handler it registered.You can run Teams handlers and ticket handlers in different workers. A worker with only handlers claims no runs.
A handler has action_timeout seconds (default 45, at most 55).A slow handler fails with HANDLER_TIMEOUT and is tried again.
Raise ActionFailed(code, message, retryable=...) for a known failure.A retryable failure is tried again, up to 5 attempts. A failure that a retry cannot fix ends the action, and the agent owner is told.
Delivery is at least once.Give action.idempotency_key to the target when it accepts one. The key is the same for every attempt.
The input never names a recipient.Map an input value, such as a channel name, to a real target in the handler.

colrows.quorum.handlers has reference handlers that you can register as they are: teams_handler posts a card with a link to the run, email_handler sends plain text over SMTP to a fixed list, and webhook_handler posts the action as signed JSON to your own service. action.approval tells a handler who approved the action and when.

Change a system of record

A CHANGE action needs a person's approval before it runs, and the approval can take days. The data can change in that time. change_handler reads the current state of the target, and makes the change only when the state is still the state that the agent saw. The agent puts that state in the input, in a field such as expectedBalance:

from colrows.quorum import ActionResult
from colrows.quorum.handlers import change_handler

async def read_balance(action):
    return await billing.balance(action.input["accountId"])

async def credit(action):
    ref = await billing.credit(action.input["accountId"], action.input["amount"],
                               expected_balance=action.input["expectedBalance"],
                               idempotency_key=action.idempotency_key)
    return ActionResult(external_ref=ref)

worker.action_handler("billing.credit")(change_handler(read_balance, credit, expected_field="expectedBalance"))

A different state fails the action with STATE_CHANGED and no retry. Run the agent again on new data.

Reports

When the spec's output contract is REPORT, the default loop writes a report with a title, a summary, sections, and gaps. The model never types table rows. A table names an execution of the run, the columns to show, and the number of rows, and the loop fills the rows from what the run read. Every value in a table is therefore from the source. A handler for a DELIVER_REPORT action renders the report as HTML or plain text with render_report.

Questions that span datasources

A business question often needs data from more than one source, for example incidents in an operational database and deliveries in a warehouse. Each source is queried with its own governed query. In agent code that you write, run.combine then joins the results of two to four executions of the run on the identity of a semantic object, and can group, aggregate, sort, and limit the output. The SDK reads all rows of each input, and refuses an input that is not complete or has more than 5,000 rows, because a join on part of a result gives a wrong answer. An answer cites the output as COMPUTATION evidence, and the control plane checks that every input was a successful execution of the same run.

Configuration

Worker.from_env() reads the connection and worker settings from the environment. The stock worker, colrows quorum serve, also reads COLROWS_AGENTS, the three COLROWS_MODEL variables, and COLROWS_LOG_LEVEL; in your own worker you pass the agents and the model in code. Secrets stay in memory, and the client secret can come from a mounted file instead of the process environment.

VariableMeaning
COLROWS_URLThe Colrows base URL.
COLROWS_CLIENT_IDThe worker client ID, with the quorum:worker scope.
COLROWS_CLIENT_SECRET or COLROWS_CLIENT_SECRET_FILEThe secret, or a file that contains it. Prefer the file.
COLROWS_AGENTSAgent keys, separated by commas. Leave it empty to serve every agent that the worker client is assigned to.
COLROWS_MODELA model name, for example openai:gpt-5 or anthropic:claude-sonnet-5-5. Required for the default loop.
COLROWS_MODEL_BASE_URL, COLROWS_MODEL_API_KEYAn OpenAI-compatible model server, and its key if it needs one. COLROWS_MODEL is then the model name on that server.
COLROWS_WORKER_IDThe worker name in Quorum. The default is the host name, the process ID, and a random suffix.
COLROWS_CODE_VERSIONYour code version, for example the image tag or Git commit. Quorum records it on each run.
COLROWS_MAX_CONCURRENT_RUNSRuns in progress at the same time in one worker. Default 4.
COLROWS_SHUTDOWN_GRACESeconds that runs get to finish after SIGTERM. Default 60.
COLROWS_HEALTH_PORTPort for /healthz and /readyz.
COLROWS_LOG_LEVELLog level. Default INFO.

Run in production

The worker handles authentication, claiming, leases, run tokens, cancellation, and results, so your code does not. The key behaviours:

  • Capacity. It never runs more than max_concurrent_runs at once. Extra claimed runs go back to the queue, and when a run finishes the worker claims the next one at once.
  • Shutdown. On SIGTERM, running runs get shutdown_grace seconds. Runs still running then go back to the queue without using an attempt.
  • Lost runs. When the server refuses a heartbeat, or the lease ends with no successful heartbeat, the worker stops the agent, so no model tokens are spent on a run that another worker owns.
  • Health. Set health_port to serve /healthz (the claim loop runs) and /readyz (a claim or a heartbeat reached Colrows recently).
  • Batch jobs. worker.run_batch() processes the queued runs, waits until each one finishes, and stops. colrows quorum serve --once uses it. Use it only for scheduled agents.
  • Errors stay in your environment. The SDK sends only the exception type for an unexpected exception, so exception text with data never leaves your environment.
  • Kill timeout. Set the kill timeout of your platform to at least COLROWS_SHUTDOWN_GRACE plus 20 seconds, so unfinished runs go back to the queue and final reports finish. On Kubernetes this is terminationGracePeriodSeconds.
  • Readiness window. /readyz reports ready when a claim or a heartbeat reached Colrows in the last 120 seconds, with the default settings.
  • Credentials. The worker refreshes its token 60 seconds before the token expires. When three claims in a row are refused because of the credentials, the stock worker exits with code 1, so your platform shows the failure and restarts it. To rotate a credential, create a new worker client, deploy it, and then revoke the old one.
  • Check before you deploy. colrows quorum check tests the URL, the credentials, and the scope from the target network, and takes no run.

Run failure codes

A failed run carries a code. The control plane retries only the codes marked as retried, up to the attempt limit of the run.

CodeCauseRetried
TOOL_UNAVAILABLEA tool call that can pass later: a network error, or a 5xx, 408, 429, or 401 response.Yes
TOOL_REJECTEDThe server refused a tool call, for example a call outside the scope of the agent. Add the tool to tools.colrows and the data to semanticScope, or change the agent.No
RESULT_TOO_LARGE, INVALID_RESULT, RESULT_REJECTEDThe result is over 256 KB, is not a JSON object, or was refused by the server.No
WORKER_ERRORAny other exception in the agent or in the worker.Yes
MODEL_NOT_CONFIGURED, MODEL_CONFIG_INVALIDNo model is set, or the model name, the provider key, or the provider package is wrong or missing.No
MODEL_AUTH_FAILED, MODEL_REQUEST_REJECTEDThe provider refused the key (401, 403) or the request (400, 404, 413, 422), for example a context that is too long.No
MODEL_UNAVAILABLEThe provider is busy or down (408, 429, 5xx).Yes
MODEL_TURN_LIMITThe run used more model turns than maxModelTurns.No
MODEL_OUTPUT_INVALID, SELF_CHECK_FAILEDThe model output does not fit the answer schema, or the answer still fails the self-check after the repairs.No
PATTERN_INVALID, CUSTOMER_TOOL_MISSINGThe spec names an unknown pattern, or declares a customer tool that the worker did not register.No
QUORUM_CHECK_FAILEDThe result failed the answer check on the server. The result is kept for review.No

Agent code that you write fails a run with raise AgentFailure(code, message).

Troubleshooting

SymptomCheck
The worker runs but takes no runs.The agent is seated and has queued runs. COLROWS_AGENTS matches the agent keys exactly. The worker client is assigned to the agent. Not all slots are busy. An idle worker waits up to 30 seconds between claims.
Runs fail with SELF_CHECK_FAILED.The self_check.repair events show the rule codes. Common causes: the model states numbers before it reads the rows, or it cites an execution ID from the instructions. Do not put execution IDs in instructions.
Runs stop with "lease lost".Blocking code delays the heartbeat; move it to asyncio.to_thread. The network to Colrows was down for longer than the lease (120 seconds by default). An admin cancelled the run or unseated the agent.
Runs go back to the queue on every deploy.The kill timeout is shorter than the shutdown grace plus 20 seconds.

Reference agents

The repository has four complete example agents in reference/agents/. They are examples to start from, and you change the queries, the instructions, and the actions to your process. Each one starts from a rule or an alert that you already have, gives the agent the decision that crosses your systems, and puts every change to a system of record behind a person's approval.

FileCaseChange that a person approves
breakdown-response.jsonA machine raises an alarm: repair now, run to the end of the shift, or move the load.Move load to a backup machine.
network-outage-impact.jsonAn outage: the affected enterprise customers, the SLA clock, and the restoration order.Field ticket priority.
offer-leakage-cases.jsonClaims that your rules flagged become cases: abuse, possible abuse, or false alarm.Hold an offer benefit.
franchise-sales-drop.jsonA store below forecast: a stock, price, local, or regional cause.Stock transfer between stores.

Each file holds the parameters to fill with your IDs, the evaluation suites, the agent spec, the action definitions, and notes for the admin. Create the items in this order: the agent, the suites, the action definitions, and then a draft version with the spec. A matching worker for each agent is in python/examples/agents/. The reference/api-sources/ directory has example API source definitions for common business applications.

Test without a server

RecordedTools answers Agent REST and Agent MCP with recorded responses, so an agent runs with no server, no model, and no keys. To test the default loop, give it a scripted Pydantic AI FunctionModel.

from colrows.quorum.testing import RecordedTools, run_agent

tools = RecordedTools({
    "searchSemanticEntities": {"entities": [{"id": "net-revenue", "entityType": "METRIC"}]},
    "executeSQL": {"executionId": "qe_42", "status": "SUCCEEDED"},
    "getSQLExecutionResult": {"executionId": "qe_42", "status": "SUCCEEDED",
                              "columns": [{"name": "region"}, {"name": "last_week"}, {"name": "this_week"}],
                              "rows": [["EMEA", 120.0, 110.4]]},
})
result = await run_agent(revenue_analyst, {"question": "revenue by region"}, tools)
assert result["status"] == "ANSWERED"

Record responses with the fields that the server sends. The conformance fixtures have an example of each tool output, and runnable examples that need no server are in the python/examples/ directory.

Versions and support

The Python package is production ready. The worker protocol is version 1, and the package runs governed agents against Colrows in production today. Pin a version in your dependencies and upgrade on your own schedule.

Each language has its own version and release tags, with a python- prefix for the Python package. A change to the worker protocol updates the conformance fixtures and every released SDK in the same change, so your workers and the server stay in step.

On the roadmap: the Helm chart with a KEDA scaler, more colrows CLI commands, and a Java SDK.

FAQ

How do I run Quorum agents on my own compute?

Install the SDK with pip install colrows, create a worker client in Quorum with the quorum:worker scope, set COLROWS_URL and the client credentials, and run colrows quorum serve. The worker claims queued runs, calls Colrows tools with a per-run token, and sends results. Your model and your provider key never leave your environment.

Do I have to write an agent loop?

No. The stock worker and the default semantic loop answer a business question, verify the answer, and cite evidence with no code. Write code only when you need your own loop or another framework; you then keep the governed tools, the run identity, and the result builders.

Which models does the SDK support?

The default loop accepts any Pydantic AI model. Provider extras are openai, anthropic, google, and bedrock, and you can point COLROWS_MODEL_BASE_URL at any OpenAI-compatible server, including a self-hosted model.

Is the Colrows SDK open source?

Yes. It is on GitHub under the Apache License 2.0. Report security issues as described in the repository's SECURITY.md, not in a public issue.