Skip to main content

graticor: the Python SDK of Graticor

pip install graticor
import graticor as gr

The Python SDK of the Graticor Agents platform. Write your agent in any framework (LangGraph, CrewAI, the OpenAI Agents SDK, LlamaIndex, Google ADK, Pydantic AI, smolagents, plain code) and the SDK connects it to Graticor. It installs as graticor, imports as graticor (import graticor as gr), and its command is graticor; its settings are GRATICOR_* environment variables (Configuration reference). Documentation: https://app.graticor.com/docs/python.

  • Tracing. Every LLM call, tool call, retrieval and agent step is sent to Graticor over OpenTelemetry (OTLP), with tokens, cost and the prompts. Installed frameworks are instrumented automatically.
  • Models from the console. Your code asks the Graticor model router for model:<agent>/<slot>; the console decides which model that is: a Graticor deployment, a provider you connected (OpenAI, Anthropic, Mistral...), or the free Simulated model. Swap models without a deploy.
  • Config from the console. Instructions, typed params and model slots live in the console, with a draft for development and published versions for production.
  • Architecture. agent.register(obj) sends the graph of your agent (nodes, tools, handoffs); Graticor draws it and overlays live traces on it.
  • Runs from Graticor. agent.serve() turns your process into a worker: the playground, schedules, webhooks and evaluations run your code.
  • Knowledge, memory, evaluations. Search Graticor knowledge bases with citations, keep long-term memory per end user, and gate CI on evaluation scores.
  • Config as code. Define hosted and workflow agents in Python (gr.define(...)), keep them in your repository, and push them (graticor push); pull any agent as a file or as Python, and pull, diff and push a workflow's steps (graticor workflow ...).
  • Runs and outcomes. Start runs of any agent with your key (gr.runs.create), or with the agent's own API key for your customers' traffic (gr.AgentApi), and report what each run was worth (gr.outcome).
  • Memory review and the sandbox daemon. Review what agents proposed to remember (gr.memories), and run Graticor agents' sandboxes on your own Linux machines (graticor sandbox).

Tracing never breaks your application: with Graticor down, spans are dropped and config pulls fall back to the last good copy, each with one warning on the graticor logger.

Status (as of 2026-11-24)

  • Package. graticor 0.4.0 (src/graticor/_version.py; PyPI has 0.3.0 until this version is published), imported as graticor, with the command graticor (pyproject.toml). Python 3.9 or later. 0.3.0 renamed the import package and the command, which kept the platform's earlier name up to 0.2.0: code written for 0.2.0 changes its imports and commands to graticor. Settings are GRATICOR_* (Configuration reference).
  • Graticor's names. 0.4.0 sends Graticor's names: the headers x-graticor-account, x-graticor-agent-version and x-graticor-lease, and the span attributes graticor.* (graticor.agent.name, graticor.config.hash...). Its files are graticor.agent/v1 (gr.define, graticor pull), graticor.workflow-file/v1 with a $graticor block (graticor workflow pull) and graticor.agent_graph/v1 (graticor graph). Graticor issues personal and SDK tokens as gr_…, agent API keys as gr_ak_…, endpoint keys as gr_sk_…, and sandbox enrollment codes and daemon tokens as gre_… and grd_…. Everything from before Graticor is still accepted, by this package and by Graticor: pac_… keys and tokens, x-pac-* headers, pac.* attributes, files that say pac.agent/v1, pac.workflow-file/v1 ($pac; a push rewrites the base in that block) or pac.agent_graph/v1, and PAC_* settings.
  • Published by CI. .github/workflows/publish-python.yml runs the tests, builds the wheel and the sdist, and publishes them to PyPI with Trusted Publishing (no PyPI token is stored anywhere).
  • Offered by a server only when its operator sets it up. A server offers the wheel only when GRATICOR_SANDBOX_DAEMON_WHEEL points at a built wheel. The production files in this repository (deploy/prod/compose.yaml, deploy/prod/.env.example) neither set it nor mount a wheel, so a server deployed from them offers no Python package yet; Connect code then shows the checkout line. The local Docker setup mounts dist/daemon read-only for it (deploy/local/compose.yaml).
  • Built. Everything this README describes is in the package. The tests (44 files in tests/) run against a faked Graticor API (Development). The publishing workflow runs them on Python 3.9, 3.12 and 3.13 before each release; .github/workflows/ci.yml runs the TypeScript SDK's.
  • Only Python code agents have a worker. The TypeScript SDK (sdks/typescript) has no worker yet, so the playground, schedules and evaluations can run Python code only.
  • Some features depend on the server's settings:
    • platform-claude needs the operator to turn it on (How model assignment works);
    • a Graticor deployment answers with a real model only when it was deployed with GRATICOR_DEPLOY_EXECUTE=1; otherwise it is a dry run and answers through the simulator;
    • knowledge search is always lexical, and semantic too once an embedding model is set up;
    • the sandbox daemon needs the wheel and an https GRATICOR_PUBLIC_API_URL on the server (The sandbox daemon).

Contents

Install

Python 3.9 or later. The package is on PyPI as graticor (never pip install pac-agents, the name it had before it was published: Graticor does not own that name on PyPI).

pip install graticor                  # the core: tracing, config, runs, knowledge, memory, evaluations
pip install "graticor[langchain]"     # with a framework's tracing (extras below)

Two other ways in, for a server that is not connected to PyPI or for a development copy:

# From your Graticor server, when its operator offers the package (Connect code shows the exact line,
# with its sha256; pip checks it):
pip install "graticor[langchain] @ https://<your Graticor>/api/agents/sdk/packages/<token>/graticor-0.4.0-py3-none-any.whl#sha256=<sha256>"

# From a Graticor checkout:
pip install -e "<path to your Graticor checkout>/sdks/python[langchain]"

The server offers the same wheel it serves to sandbox daemons. The operator builds it with node scripts/build-daemon-wheel.mjs (it writes dist/daemon/graticor-0.4.0-py3-none-any.whl and prints its sha256) and points GRATICOR_SANDBOX_DAEMON_WHEEL at it. GET /api/agents/sdk/packages lists what a server offers (apps/api/src/agents/devx/sdkPackages.ts). The download link carries a token derived from the server's GRATICOR_SECRET: it does not expire, but it changes when GRATICOR_SECRET changes. Without the setting the server offers no package, and Connect code shows the checkout line.

The core needs only httpx and OpenTelemetry. Each extra installs the OpenInference instrumentor for a framework (and, for openai and langchain, the client the SDK hands out):

Extra For
[openai] the OpenAI client (agent.openai()), OpenAI tracing
[langchain] LangChain and LangGraph tracing, agent.langchain() (langchain-openai)
[anthropic] Anthropic SDK tracing
[llama-index] LlamaIndex tracing
[crewai] CrewAI tracing
[openai-agents] OpenAI Agents SDK tracing (bridge to OpenTelemetry)
[google-adk] Google ADK tracing
[pydantic-ai] Pydantic AI (native OpenTelemetry, converted by OpenInference)
[smolagents], [dspy], [litellm], [bedrock], [mistral], [groq], [autogen], [agno] those libraries (the smolagents and AutoGen instrumentors need Python 3.10+: on 3.9 those two extras install nothing)
[all] everything above

Install the framework itself as usual (pip install langgraph, pip install crewai...): the extras do not pin your framework versions.

Quickstart (5 minutes)

1. Get a key. In the console, open Agents › More actions › Connect your code (/agents?tab=connect) and click Create SDK key: the key (valid 90 days) is filled into the environment block shown there. (Settings › API tokens does the same: create a token with the Agents SDK scope.) This scope only reaches what the package calls (traces, the model router, configs, workers, knowledge search, memories and evaluations), so a leaked key cannot touch the rest of your account.

export GRATICOR_BASE_URL=http://localhost:8787   # your Graticor API (on a deployed server: the address Connect code shows)
export GRATICOR_API_KEY=gr_...                   # the Agents SDK token
export GRATICOR_ACCOUNT=org_...                  # only for an organization account

2. Write an agent.

import graticor as gr

gr.init()                                     # reads GRATICOR_* from the environment
agent = gr.agent("support-bot")               # registers the code agent "support-bot"
client = agent.openai()                       # an openai.OpenAI on the Graticor model router

@agent.entrypoint
def answer(message, *, history=None):
    reply = client.chat.completions.create(
        model=agent.llm().model,              # "model:support-bot": the console picks the model
        messages=[{"role": "system", "content": agent.instructions},
                  *(history or []), {"role": "user", "content": message}],
    )
    return reply.choices[0].message.content

print(answer("Hello!"))

3. Run it. A new code agent uses the Simulated model, so the first run works before any provider is connected. Open the agent in the console (agent.console_url): the trace is there, with the LLM call, tokens and the prompt.

4. Pick a real model. In the console, open the agent › Build › Models, choose a model (a Graticor deployment or a connected provider), and run again. The code did not change. (A Graticor deployment made while the server runs dry runs answers through the simulator too.)

5. Run it from Graticor. Add agent.serve() (or run graticor serve my_app.py:agent) and chat with your code in the Playground: the agent's Build tab opens it from Preview, and a connected worker answers. (People who can only read the agent get a Playground tab instead.)

How model assignment works

Your code never names a provider model. It sends OpenAI-compatible requests to the Graticor model router ({GRATICOR_BASE_URL}/api/agents/llm/v1) with a model id in the router grammar:

model Resolves to
model:<agent> the agent's main model (config.model)
model:<agent>/<slot> the model of a named slot (config.models[slot]), else the main model
<connection>/<model> a model of one of your provider connections (e.g. openai/gpt-4.1-mini)
sim the Simulated model (free, deterministic, calls tools)
platform-claude Graticor's own Claude, when the operator turns it on

The router takes your personal token (GRATICOR_API_KEY). It is not the deployment gateway at /v1, which takes endpoint keys (gr_sk_…).

platform-claude answers only when the server sets GRATICOR_AGENTS_PLATFORM_CLAUDE=1 and ANTHROPIC_API_KEY, and the account is listed in GRATICOR_AGENTS_PLATFORM_CLAUDE_ACCOUNTS (or the server runs with dev auth) (apps/api/src/agents/llm/models.ts). The production example (deploy/prod/.env.example) does not set it, so there you bring a provider key or use a Graticor deployment. A deployment that is a dry run (the server without GRATICOR_DEPLOY_EXECUTE=1) answers through the simulator, like sim.

agent.llm(slot) returns the handle (base_url, api_key, model, headers), and the helpers build ready clients from it:

agent.openai(slot=None)          # openai.OpenAI
agent.async_openai(slot=None)    # openai.AsyncOpenAI
agent.langchain(slot=None, **kw) # langchain_openai.ChatOpenAI (works in LangGraph nodes)
agent.litellm(slot=None)         # kwargs for litellm.completion(**kw) or crewai.LLM(**kw)

Slots let one agent use several models: agent.langchain("planner") and agent.langchain("writer") show up as two rows in the console (Build > Models), each with its own model picker. A slot nobody assigned falls back to the main model; an agent with no model at all answers 409 model_not_assigned with a link to the console. Graticor keeps up to 20 slots per agent (the first 20 your code declares; later ones still work and use the main model).

Images. The router takes text parts and, in user messages, image_url parts as PNG or JPEG data URLs: at most 8 images per request, 1.5 MB each. It never fetches a link, so send the bytes, not an https:// URL (that answers 400 unsupported_content). The assigned model must read images (and its fallback, when it has one); otherwise the router answers 400 model_reads_no_images with a link to Build > Models, which says under the main model whether it takes images.

client = agent.openai()
client.chat.completions.create(model=agent.llm().model, messages=[{"role": "user", "content": [
    {"type": "text", "text": "What is in this picture?"},
    {"type": "image_url", "image_url": {"url": "data:image/png;base64,…"}},
]}])

Draft and published. The console edits a draft; Publish creates a numbered version. GRATICOR_AGENT_VERSION picks which one the code uses:

  • unset and GRATICOR_ENV=dev (the default): the draft, so console edits apply at once;
  • unset and GRATICOR_ENV=staging: the staging version (the published one while the agent has none);
  • unset in any other environment (GRATICOR_ENV=prod...): the published version (the draft while the agent was never published);
  • draft, published, staging or a version number: exactly that config.

A production server that forgets GRATICOR_ENV reads the draft, so unpublished edits reach your users at once. When neither GRATICOR_ENV nor GRATICOR_AGENT_VERSION is set and the agent has a published version, agent.config() warns once per process (after a pull that worked):

graticor: GRATICOR_ENV is not set: this process reads the draft of support-bot; v3 is published. Set GRATICOR_ENV=prod in production.

Set GRATICOR_ENV=dev on purpose on a dev machine and the warning stays off. Worker runs never warn: they run the version Graticor assigned. The console shows the same thing: the Monitor tab of a published code agent says "N traces in 24 h used the draft".

The clients of agent.openai(), agent.async_openai() and agent.langchain() send x-graticor-agent-version on every request with the version in use at that moment: inside a worker run or an evaluation item of the agent, the run's version (the draft for playground runs, even in a GRATICOR_ENV=prod worker), else GRATICOR_AGENT_VERSION's. So a client made once at import follows each run, and the run's config and its model calls agree. (agent.litellm() and agent.llm().headers carry the value of the moment you call them, as does a client you build with your own http_client.) The router serves the models of the version the request names: the draft's for draft, that version's for a number, and the published version's otherwise (the draft's for a never-published agent). Spans carry graticor.agent.version and graticor.config.hash, so every trace says which config produced it, and experiments compare drafts with published versions.

Defaults from code. gr.agent(name, instructions=..., model="openai/gpt-4.1-mini", models={"writer": "sim"}) seeds a new agent's draft. After that the console owns them.

Tracing

gr.init() sets up OpenTelemetry:

  • a TracerProvider with the resource service.name, graticor.agent.name, gen_ai.main_agent.name, deployment.environment.name and graticor.sdk.version (an existing global provider is reused: our exporter is added to it);
  • a batch exporter sending protobuf OTLP/HTTP (gzip) to {GRATICOR_BASE_URL}/api/agents/otlp/v1/traces;
  • every installed OpenInference instrumentor (instrument="auto"), each guarded so a broken package never breaks your app: OpenAI, Anthropic, LangChain/LangGraph, LlamaIndex, CrewAI, OpenAI Agents, Google ADK, DSPy, smolagents, LiteLLM, Bedrock, Mistral, Groq, AutoGen, Agno and Pydantic AI. Pass instrument=["openai", "langchain"] to pick, or instrument=False.

Which spans reach Graticor. Only agent traces: a trace is sent when one of its spans runs inside an agent's code (an entrypoint, a worker run, an evaluation item) or a gr.session(), or is an LLM, tool, agent or other GenAI span (Graticor, OpenTelemetry GenAI or OpenInference). The other traces of your application (an HTTP health check, a database query with no agent involved) stay out of Graticor and are not stamped with graticor.* attributes. gr.init(export_all_spans=True) (or GRATICOR_EXPORT_ALL_SPANS=1) sends every span of the process.

What Graticor accepts. The server caps each account at GRATICOR_AGENTS_DAILY_SPANS spans a day (default 200,000); past it the export answers 429 until the next UTC midnight. It also rejects the spans of an agent the key's person may not edit ("no edit access to agent "), and caps one request at 16 MB and 10,000 spans (apps/api/src/agents/traces/otlp.ts).

Several agents in one process. Each trace belongs to its outermost agent: when a supervisor's entrypoint calls a researcher's, the whole trace is the supervisor's (every span's resource says so, however the spans are batched), and the researcher's spans keep graticor.agent.name=researcher as a span attribute.

gr.init() may run more than once (the CLI inits, then your module calls gr.init() at import): the TracerProvider stays the same, with the new settings' processors in place of the old.

OpenAI Agents SDK. With the [openai-agents] extra, gr.init() bridges the SDK's own traces to Graticor; without it, only the model calls are traced, not the agent, handoff and tool spans. The SDK also sends its traces to OpenAI with its own exporter. disable_openai_tracing=True removes that exporter, with or without the extra, even when nothing goes to Graticor (no key, offline, instrument=False); other trace processors of the SDK stay (gr.instrument_openai_agents() does the same on demand). The default (None) removes it only when it has no OpenAI key to send with (no OPENAI_API_KEY, none set on the SDK, or your Graticor key, which set_default_openai_client(agent.async_openai()) hands it): such an exporter could only log "OPENAI_API_KEY is not set, skipping trace export". When gr.init() runs before the SDK is imported, the SDK is not imported for this: the check runs at the next agent.llm() (or its clients), agent.register(), entrypoint call or worker start, and after the CLI loads your module. The default also removes an exporter it kept once it is handed your Graticor key (set_default_openai_client(agent.async_openai()) after gr.init()), at the same moments; pass use_for_tracing=False to set_default_openai_client() to be sure OpenAI never gets that key. disable_openai_tracing=False leaves the exporter alone.

LangGraph and LangChain. A ChatOpenAI call is recorded twice, by the LangChain and by the OpenAI instrumentor; the OpenAI span nests under the ChatOpenAI span, so Graticor counts its tokens and cost once. Spans inside a node carry metadata.langgraph_node, which Graticor maps to the node of the registered graph.

Manual spans.

@gr.trace                                    # a "chain" span named after the function
def plan(question): ...

@gr.trace(name="research", kind="agent")     # an "invoke_agent research" span
def research(topic): ...

@gr.tool                                     # an "execute_tool lookup" span with arguments and result
def lookup(order_id: str) -> str: ...

with gr.span("rerank", kind="reranker", input=query) as s:
    s.set_output(ranked)
    s.set_attribute("rerank.model", "bge")

Kinds: agent, chain, tool, llm, retriever, embedding, reranker, guardrail, evaluator, memory, handoff, http, other. Node kinds (agent, chain, tool, retriever, memory, handoff) set graph.node.id, so they become nodes of the observed graph. Decorators work on sync and async functions and generators; exceptions are recorded and re-raised. A traced generator's span covers the whole iteration and works when each step runs in another context (Starlette's StreamingResponse, a thread pool); send(), throw() and close() reach your generator. Recording arguments and results is best-effort: a value that cannot be read (an unread streaming response, data nested thousands of levels deep) is recorded as its repr or a placeholder, and never stops your function or loses its result. @agent.entrypoint wraps its function in an invoke_agent <agent> span.

Sessions and users. Group the spans of a conversation and attribute them to an end user:

with gr.session(thread_id, user_id="u-42", metadata={"plan": "pro"}, tags=["beta"]):
    answer(message)

Logs and scores. gr.log("cache miss", level="warn") adds an event to the current span (and a log line in the playground during a worker run). gr.score(trace_id, "user-thumbs", value=1.0) attaches a score to a trace; gr.current_trace_id() gives the id.

Content capture. By default prompts, outputs and tool arguments are recorded (Graticor hides them from members without the agents.write permission). gr.init(capture_content=False) or GRATICOR_CAPTURE_CONTENT=0 keeps them out of traces: spans then carry timings, tokens, cost, models and errors only (error messages included). That covers the OpenInference instrumentors, Pydantic AI's own instrumentation (include_content=False; a Pydantic AI too old for it is not instrumented) and gr.log() lines, whose span events then keep only their level (the playground still shows the line during a worker run). The agent's console setting "Trace content: Metadata only" strips them on the server side too (agent › Settings › Data & advanced › Trace content). Authorization headers, cookies, API keys and tokens are always dropped.

Flushing. Spans are batched; gr.flush() sends them now, and they are flushed at exit. gr.shutdown() flushes, uninstruments and closes the client.

Registering the architecture

agent.register(obj) reads the structure of a framework object and sends it to Graticor, which draws it in the agent's Build › Graph and on Monitor › Charts (declared graph) next to the graph rebuilt from traces (observed graph). Node ids are the names spans carry (LangGraph node names, CrewAI roles, agent and tool names), so a trace can light up its path. graticor graph module:attr prints the graph without sending anything: it imports your module with GRATICOR_OFFLINE=1, so the module's own gr.init(), gr.agent() and agent.register() make no request (--push registers it).

graph = builder.compile()
agent.register(graph)
Framework Pass What becomes the graph
LangGraph a compiled graph (or the StateGraph builder) start/end, each node (id = node name), conditional edges with their route key, ToolNode tools as tool nodes, subgraphs (children carry parent), chat models used as nodes as llm nodes
CrewAI a Crew (or one Agent) tasks in order (start > task 1 > ... > end), each task's agent (id = role) with its model and slot, task context as data edges, tools, a manager for hierarchical crews, delegation, memory and knowledge
OpenAI Agents SDK the entry Agent every agent reachable through handoffs (cycles are fine), models and slots, function, hosted and MCP tools, agents used as tools
LlamaIndex a Workflow, an AgentWorkflow or a workflow agent steps linked by the events they emit and accept (labelled), StartEvent/StopEvent as start/end, human-in-the-loop events; agent workflows as agents with tools and handoffs
Google ADK the root agent the agent tree: LLM agents with models, Sequential/Parallel/Loop agents as subgraphs with their control flow, transfers, tools, AgentTools
Pydantic AI an Agent the agent, its model, function tools and toolsets (MCP servers)
smolagents a CodeAgent / ToolCallingAgent the agent, its model, tools and managed agents
anything else a dict an AgentGraph you write yourself (validated)

A hand-written graph:

agent.register({
    "schema": "graticor.agent_graph/v1",
    "framework": "custom",
    "nodes": [
        {"id": "router", "kind": "router", "name": "Router", "slot": "router"},
        {"id": "search", "kind": "tool", "name": "search"},
        {"id": "answer", "kind": "agent", "name": "Answer"},
    ],
    "edges": [
        {"source": "router", "target": "search", "kind": "tool"},
        {"source": "router", "target": "answer", "kind": "conditional", "label": "has context"},
    ],
})

Node kinds: agent, llm, tool, retriever, knowledge, memory, router, subgraph, chain, start, end, other. Edge kinds: control, conditional, handoff, delegation, data, tool. Graphs are capped at 500 nodes and 2000 edges.

The adapters only read attributes (no framework is imported to detect one). When one cannot read an object, it logs a warning and registers no graph: the observed graph still shows what runs. from graticor.architecture import build_graph gives the same dict without registering. agent.serve(obj) and graticor serve register the object they serve.

Serving: the worker

A code agent runs where your code runs. To let Graticor trigger it (playground, schedules, webhooks, evaluations started from the console), run a worker:

agent.serve()             # the @agent.entrypoint function
agent.serve(graph)        # or a LangGraph graph, a CrewAI crew, an OpenAI Agents agent, a callable
graticor serve my_app:agent            # an Agent with an entrypoint (module path)
graticor serve my_app.py:run           # its @agent.entrypoint function: the same worker
graticor serve my_app.py:graph         # a framework object in a file, served as the agent that owns it
graticor serve my_app:crew --name research-crew --concurrency 4

An object that is not an Agent is served (and evaluated, and pushed by graph --push) as the agent named, in order: --name; the agent that owns it, that is the one whose @agent.entrypoint it is (which then runs as usual), that serves it, or that was given it by agent.register(obj); the module's only Agent; GRATICOR_AGENT_NAME; the object's own name (unless a framework default such as agent); the module's name. An object several agents registered needs --name (or GRATICOR_AGENT_NAME naming one of them), else the command exits with code 2.

The worker long-polls Graticor, runs each job in a thread (2 at a time by default), streams tool calls and logs to the playground, and posts the answer with tools used and token counts. Its spans land in the trace Graticor opened for the run. Ctrl+C stops polling and lets running jobs finish (twice quits at once). While Graticor is down it backs off and reconnects.

How each target is called:

Target Call
entrypoint / callable fn(message, history=..., variables=..., end_user=..., thread_id=..., run_id=...), passing only the keyword arguments it declares; async functions are awaited on the SDK's event loop
LangGraph graph.invoke({"messages": history + [user]}, config={"configurable": {"thread_id": ...}}), or ainvoke on the SDK's event loop when a node (or a subgraph's node) is async only; the answer is the last AI message (with a checkpointer, only the new message is sent)
CrewAI crew.kickoff(inputs={"message": ..., **variables}); the answer is the crew's raw output
OpenAI Agents Runner.run(agent, message or history + [user]) on the SDK's event loop; the answer is final_output

Async code runs on one event loop the SDK keeps for the whole process (with the job's context), so async clients created once at import keep working from one run to the next. The clients of agent.async_openai() and agent.langchain() also work from any event loop (one connection pool per loop), for code that calls asyncio.run() or Runner.run_sync() itself.

The entrypoint returns a str (the answer) or a dict/list (JSON output); an exception fails the run with its message. JSON output is converted to plain JSON (dates as ISO text, pydantic models and dataclasses as objects, LangChain messages as {"type", "content"}, NaN as null). What the worker sends fits Graticor's limits: the text output is cut at 200 000 characters, the JSON output is left out when the result would pass about 900 KB (the text says the same), and at most 200 tool names are listed. Should Graticor refuse the result anyway, or the worker fail while reporting it, the run is still completed (with the text only, or with the error), so it never waits for its timeout. A run queued while no worker is connected fails after 60 seconds with "No worker is connected for "; the Playground and Build > Code show whether a worker is connected. Inside a run, agent.config(), agent.instructions, agent.param(), agent.version and agent.config_hash are those of the config Graticor assigned to that run (the draft for playground runs, else the version the run asked for). A run cancelled in the console stops being reported; your code is not interrupted.

Params

Typed values your code reads and the console edits (Build > Params), without a deploy:

temperature = agent.param("temperature", 0.2, description="Sampling temperature.")
tone = agent.param("tone", "friendly")
strict = agent.param("strict_mode", False)

The type is string, number, boolean or text (from the default, or type=). The console value is converted to it; a bad value falls back to the default with a warning. Params are declared at registration, so call agent.param at import time for them to show up before the first run.

Names are identifiers: letters, digits and _, starting with a letter or _ (64 at most; ValueError otherwise). Graticor shows up to 64 params per agent (the first declared); a default longer than 8 000 characters stays in your code (the console shows no default for it) and a description is cut at 500 characters, so one oversized declaration never makes Graticor refuse the registration.

Knowledge bases

kb = gr.knowledge("handbook")              # a name or an id ("kb_8Qx...")
hits = kb.search("vacation policy", top_k=5)
for h in hits:
    print(h["citation"], h["score"], h["text"][:80])

kb.add_text("FAQ", "Refunds take 5 days.")
kb.add_file("handbook.pdf")                 # md, txt, html, csv, json, pdf (≤ 20 MB)
kb.add_url("https://example.com/docs")
retriever = kb.as_langchain_retriever(top_k=4)

Search is Graticor's hybrid search (BM25 and vectors, fused) with citations ("[1] Title › Heading"). A query is cut at 4 000 characters and top_k kept between 1 and 50, Graticor's limits. Each call is a retrieval <kb> span with the returned documents, which feeds the groundedness evaluator. Indexing runs in the background after add_* (the document comes back pending). Adding content the knowledge base already has raises gr.GraticorApiError with code == "duplicate_document"; e.body["documentId"] is the document that has it, so a seeding script can carry on.

A setup script can create the knowledge base it seeds:

kb = gr.knowledge("handbook", create=True, description="Policies")
print("created" if kb.created else "already there", kb.id)
kb.add_text("Refunds", "Refunds take 5 days.")

With create=True the name is looked up at once, and the base is created when no base has that name (kb.created is then True); running the script again reuses it. Creating needs a personal token with full scope (GRATICOR_API_KEY from Settings > API tokens): an Agents SDK key can search and add documents only, and gets a gr.GraticorError that says so. create=True takes a name, not an id. Without it, gr.knowledge() sends nothing until first use. The console's New knowledge base (Agents › Library › Knowledge, /knowledge) does the same by hand.

Memory

Long-term memory per end user, or shared by the agent:

mem = agent.memory(user="u-42")                    # scope "user"; agent.memory() is scope "agent"
mem.add("Prefers short answers", kind="preference") # fact | preference | episode | instruction
for m in mem.search("how should I answer?", limit=3):
    print(m["content"], m["score"])
mem.list()
mem.forget(memory_id)                               # one memory
mem.forget()                                        # everything about u-42 (audited hard delete)

Calls are create_memory / search_memory / delete_memory spans. Treat recalled memories as data in your prompts, not instructions.

Guardrail checks

Graticor does not run your agent's loop, so your code asks it to check what the loop is about to read or send. The check runs the company floor, the agent's policy (or the one you name) and its own checks on Graticor (POST /api/agents/:id/guardrails/check). Policies live under Agents › Library › Guardrails (/agents?tab=guardrails); the agent's Monitor › Guardrails shows the call to make:

result = agent.check(user_text, stage="input")       # or stage="output" (prompt=the user message)
if result.blocked:
    return result.message                            # what the user should see
user_text = result.text                              # masked when a check masked it
  • Monitor first: the agent's checks only report what they would do (result.would) until you pass enforce=True. Checks of the company floor keep the floor's mode.
  • policy="Support strict" (a policy name or id) applies that policy in place of the agent's; the floor still applies.
  • result.decision is "allow", "mask" or "block". Each call is a guardrail <stage> span with Graticor's verdicts; Graticor keeps the verdicts (never the text), so Monitor › Guardrails counts them.
  • Graticor down (or no GRATICOR_API_KEY, or a page that is not Graticor's at GRATICOR_BASE_URL): with enforce=False the text is allowed with one warning (result.error says why); with enforce=True the error is raised. A refusal (unknown policy, no access) is always raised.

Evaluations and CI gates

Run your agent locally over a Graticor dataset; Graticor scores the outputs and keeps the experiment next to the ones started from the console:

report = gr.evaluate(
    agent,
    dataset="faq-smoke",                                 # id or name (Evaluations > Datasets)
    evaluators=["builtin:exact-match", "builtin:latency-under-10s"],
    repetitions=1,
    gate={"builtin:exact-match": 0.8},                   # mean score thresholds
)                                                        # raises gr.GateFailed when a gate is missed
print(report.summary())                                  # the experiment is in Evaluations > Experiments

task= evaluates another function or framework object than the entrypoint. With no evaluators (and no --evaluator or --gate on the command line) the evaluator is builtin:correctness. Built-in evaluators (apps/api/src/agents/evals/evaluators.ts): builtin:correctness, builtin:helpfulness, builtin:groundedness (LLM judges, which need a judge model such as a provider connection), builtin:exact-match, builtin:contains-expected, builtin:valid-json, builtin:tools-used, builtin:retrieved-documents, builtin:latency-under-10s, builtin:cost-under-1c, plus your own evaluators by id (Evaluations › Evaluators). builtin:cost-under-1c scores only results that carry a cost. builtin:goal-achieved and builtin:user-experience judge simulated users, so they score only platform runs (Gate on a platform experiment). LLM judges count against the account's daily judge budget on the server (GRATICOR_AGENTS_JUDGE_DAILY_USD, default $1).

From the command line (exit code 1 when a gate fails):

graticor eval my_app.py:agent --dataset faq-smoke \
  --evaluator builtin:latency-under-10s --gate builtin:exact-match=0.8

A --gate evaluator is added to the evaluators when it is not listed.

A GitHub Actions job:

- run: pip install "graticor[openai]"
- run: graticor eval my_app:agent --dataset faq-smoke --evaluator builtin:correctness --gate builtin:correctness=0.8
  env:
    GRATICOR_BASE_URL: https://graticor.example.com
    GRATICOR_API_KEY: ${{ secrets.GRATICOR_API_KEY }}
    GRATICOR_ENV: ci
    GRATICOR_AGENT_VERSION: draft     # evaluate the draft before publishing it

Datasets with simulated users (scenario items: Graticor plays a persona over several turns) run on the platform only: gr.evaluate and graticor eval module:attr refuse them before anything is posted ("This dataset has 2 simulated users: Graticor plays those conversations itself, so run it on the platform: graticor eval --on-graticor AGENT --dataset ...").

Gate on a platform experiment

--on-graticor AGENT lets Graticor run the experiment itself (the same as the agent's Evaluate tab): it works for hosted and workflow agents, agents kept in git as config, Python code agents with a worker running, and datasets with simulated users. A TypeScript code agent cannot run there yet: there is no TypeScript worker, so Graticor cannot start it (apps/api/src/agents/runtime/run.ts noWorkerMessage). The command waits, prints the summary, and exits 1 when a gate is missed, 3 when the experiment is still running at --timeout (default 1800 s; it goes on in Graticor):

- run: pip install graticor
- run: graticor eval --on-graticor support-bot --dataset faq-smoke --gate builtin:correctness=0.8
  env:
    GRATICOR_BASE_URL: https://graticor.example.com
    GRATICOR_API_KEY: ${{ secrets.GRATICOR_API_KEY }}   # an Agents SDK key or a full-scope token

--version draft (the default), published, staging or a number picks the version Graticor runs. Progress goes to stderr (Running: 3 of 12), the summary to stdout. A code agent needs its worker running (graticor serve) while Graticor runs it. From Python: gr.evaluate_on_graticor("support-bot", "faq-smoke", gate={"builtin:correctness": 0.8}) returns the same Report (raises gr.GateFailed, or gr.EvaluationTimeout past timeout_s).

Config as code

Hosted and workflow agents can live in your repository as code. gr.define writes the same graticor.agent/v1 file as the console's Export and the code view's JSON tab; pushing it creates the agent, or replaces the draft of the agent with that name (published versions do not change until you publish).

# support-bot.agent.py
import graticor as gr
from graticor import models, ref

support_bot = gr.define(
    "support-bot",
    kind="hosted",                                       # or "workflow"
    description="Answers billing questions for customers.",
    tags=["support"],
    instructions="""\
# Role
You answer billing questions. Never promise refunds.
""",
    model={"ref": models.provider("openai", "gpt-5-mini"), "params": {"temperature": 0.2}},
    tools=[
        {"type": "builtin", "name": "knowledge_search"},
        {"type": "agent", "agentId": ref.agent("billing-expert")},
    ],
    knowledge=[{"kbId": ref.knowledge_base("help-center"), "mode": "auto", "topK": 5}],
    history_messages=20,
    secrets=[{"name": "ZENDESK_TOKEN", "hosts": ["api.zendesk.com"]}],
)

if __name__ == "__main__":
    gr.init()
    print(support_bot.push())            # Created support-bot (agt_...): draft 3f2a9c1.
graticor push support-bot.agent.py       # the same, from the command line or CI
graticor pull support-bot --format python     # the console's agent as this code (support-bot.agent.py)
  • Keywords are the agent config's top-level keys in snake_case (history_messages -> historyMessages); nested values are written as in the .agent.json file (camelCase JSON: {"topK": 5}). description and tags are the agent's; config_description= sets the config's own description when it differs. Keys this SDK does not know yet pass through (Graticor lists what it leaves out). Values must be JSON data or refs: anything else (a set, an object, NaN) raises GraticorConfigError naming the field.
  • Ids never travel. Name what the agent uses and Graticor resolves each name in the account you push to: ref.agent, ref.knowledge_base, ref.deployment, ref.connection, ref.environment, ref.policy (guardrail policy), ref.skill, ref.connector (a connected app); models with models.provider(connection, model), models.deployment(name), models.sim(), models.platform_claude(). A name that is not in the account fails the push with that account's closest names (gr.UnresolvedRefs, exit 1 on the command line); drop_unresolved=True (--drop-unresolved) leaves those places empty instead (an attached knowledge base is left out, a model becomes "not set"; readiness reminds you).
  • Secrets are listed by name with their hosts, never with a value; add missing ones under Agents › Connections › Secrets (publishing waits for them, as in the console). Pinned step outputs (debug data) and MCP tool pins are never part of a file: Graticor lists and pins each server's tools again on save.
  • Workflow agents load their steps from the pulled workflow file: gr.define("ticket-triage", kind="workflow", workflow=gr.load_workflow("ticket-triage.workflow.json"), ...).
  • definition.preview() (--dry-run) answers what a push would do without storing anything: the names found and missing, the secrets, the hosts the agent may send data to, what is left out, the problems that would refuse it, the workflow checklist and the changes against the current draft.
  • definition.push(publish="note") (--publish NOTE) publishes the draft afterwards: readiness blockers and the workflow check refuse it as in the console (exit 1), nothing new to publish is not an error.
  • Staging. push(publish="note", stage="staging") (--publish NOTE --stage staging, also on workflow push) publishes to Staging and prints "Published support-bot v4 to Staging. Promote it to production: graticor promote support-bot". An agent with "Require staging before production" refuses a production publish (exit 1) with Graticor's sentence and "Publish to Staging with --publish --stage staging, then run graticor promote support-bot." graticor promote AGENT [--version N] [--note NOTE] (graticor.define.promote_agent) moves the staging version, or version N, to production at once ("Promoted support-bot v4 to production."; nothing to promote is exit 0). It needs a personal token with full scope; a gradual promotion (a canary) is the console's (the agent's Settings › Notifications & releases).
  • The base of a Python file. graticor pull --format python and the code view write the draft the file was made from: gr.define(..., base="3f2a9c1d..."), with a comment line that says so (no base while the console has unsaved edits). graticor push x.agent.py and .push() send it as the draft check: when someone changed the draft in the console since, the push is refused (exit 1) with "The draft of support-bot changed since this file was made. Pull it again (graticor pull support-bot --format python), or push with --force to replace the draft." --force (push(force=True)) sends no check; --dry-run and --name for another agent send none either. After a CLI push the file's base="…" is the new draft's hash, so the next push works (when the literal is not in the file, a Note says to pull again or use --force); after .push() the definition's .base is.
  • Keys. Pushing and publishing write drafts: they need a config token (Settings > API tokens, access Agent configs: pull, push, workflow push, readiness and publish, nothing else, so CI never holds a key that can do everything) or a personal token with full scope. An Agents SDK key reads configs, files and workflows and answers 403 token_scope on a push ("Pushing changes needs a config token or a personal token with full scope.").
  • Who runs it and who may use it are owner settings in the console (Settings > Access): a file never sets them, and a push into an existing agent that carries them is refused.

graticor pull AGENT writes AGENT.agent.json byte for byte as the console's Export downloads it (--version published or a number for another version, -o - to print it). graticor push FILE.json sends the file back; when the file was pulled from the agent it replaces, the push refuses (exit 1) if someone changed the draft since, so console edits are never overwritten silently: pull again, or push with --force.

A CI recipe

Keep the agent files in agents/ and add .github/workflows/graticor.yml (the code view's "How to use it" shows this file for your agent, with your address and install line). If your repository has .github/workflows/pac-agents.yml from before, delete it.

name: Graticor agents
on:
  pull_request:
    paths: ["agents/**"]
  push:
    branches: [main]
    paths: ["agents/**"]
jobs:
  agents:
    runs-on: ubuntu-latest
    env:
      GRATICOR_BASE_URL: "https://graticor.example.com"
      GRATICOR_ACCOUNT: "<account id>"
      # A config token (Agent configs) or a personal token with full scope: pushing and publishing need one. Add it as a repository secret.
      GRATICOR_API_KEY: ${{ secrets.GRATICOR_API_KEY }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - name: Install the Graticor SDK
        run: |
          pip install graticor
      - name: Check
        if: github.event_name == 'pull_request'
        run: |
          graticor push agents/support-bot.agent.json --dry-run
      - name: Publish
        if: github.event_name == 'push'
        # the repository is the source of truth: --force replaces console edits to the draft (the pull request's dry run lists every change)
        run: |
          graticor push agents/support-bot.agent.json --force --publish "${{ github.sha }}"

Three choices:

  • Pull requests check, nothing changes. push --dry-run lists the names found and missing, the secrets, the hosts and every change against the draft (exit 1 when the push would be refused). For a workflow agent kept as Python, check its steps too: graticor workflow validate ticket-triage agents/ticket-triage.workflow.json before the dry run.
  • A merge pushes with --force. The repository is the source of truth: the base in a committed file is stale after the first push, and the pull request's dry run already showed what the push replaces. Without --force, a console edit since the last pull stops the job (exit 1).
  • Staging first. For an agent with staging, add --stage staging to the publish line, then promote it: graticor promote support-bot (or the agent's Settings › Notifications & releases).

Workflow files

A workflow agent's steps can be edited as a file next to your code:

graticor workflow pull ticket-triage                    # ticket-triage.workflow.json
graticor workflow diff ticket-triage ticket-triage.workflow.json        # what a push would change
graticor workflow validate ticket-triage ticket-triage.workflow.json    # the checklist (exit 1 on errors)
graticor workflow push ticket-triage ticket-triage.workflow.json        # replace the draft's steps
  • The file (graticor.workflow-file/v1) is what the console's code view shows (Build › Code, the <name>.workflow.json tab) and what its Download saves: $graticor (the agent, its id, the version pulled and baseHash), the steps, connections, groups and state, and the run's input variables. The console's JSON view shows the spec only; its "Load a file…" reads this file too. A pull writes it byte for byte as the console does.
  • push replaces the draft's steps and variables only (everything else of the draft stays) and sends baseHash: when the draft's workflow changed since your pull it stops with exit 1, "The draft of ticket-triage changed since you pulled it (14:02 UTC). See the changes with graticor workflow diff ticket-triage FILE, then pull again or push with --force." Once saved, the new base is written into the file, so the next push works. Validation errors never block saving a draft; the checklist is printed by step name (runs and publishing wait for the errors).
  • Pinned step outputs are debug data: pull --with-pins keeps them (people who may edit only), and a push keeps the draft's pins unless --keep-pins sends the file's.
  • diff lists steps added, removed, changed (field by field, text line by line) or moved, connections, groups, state and variables (exit 0 when there is nothing, 1 when they differ).
  • From Python: graticor.workflows.pull_workflow, push_workflow (raises gr.WorkflowConflict), diff_workflows, validate_workflow, and gr.load_workflow(path) (.spec, .variables, .base_hash).

Runs and outcomes

Start a run of any agent (hosted, workflow or code) with your own key; the run acts as you:

import graticor as gr

gr.init()
run = gr.runs.create("support-bot", message="Where is my invoice?",
                      variables={"team": "billing"}, end_user="customer-42", wait=True)
print(run["status"], run["output"])          # a Run is the API's AgentInvocation (a dict)
gr.runs.get(run.id); gr.runs.wait(run.id, timeout_s=300)
gr.outcome(run.id, success=True, value_usd=12.5, minutes_saved=4)    # the Value report
  • An agent name is looked up once (and cached until the next gr.init()); an agt_ id is used as it is. Runs use the published version (the draft until the first publish); version="draft", a number, or "staging" (the staging version: edit level) picks another.
  • wait=True returns once the run ended or waits for a person (an approval: it shows in the console's Inbox, /approvals), at most timeout_s (120 s). A run start is never sent twice after an error that may come after it started; only 429 and 503 are retried.
  • gr.outcome(run_id, success=..., value_usd=..., minutes_saved=..., note=...) reports what a run achieved (root runs that finished; the last report wins); the Value report counts it (Agents › Connections › Value, and the agent's Value card on Monitor › Charts).
  • From the command line: graticor runs start support-bot "Where is my invoice?" --var team=billing --wait (exit 0 succeeded, 1 failed or cancelled, 3 not finished), runs get, runs wait, runs outcome RUN_ID --success --value-usd 12.5. runs start also takes --end-user, --thread, --version, --timeout and --json, and - as the message reads it from stdin.

Start runs with an agent API key

Your customers' traffic should not run as you. Give each agent its own API key (the agent's Settings › Access › API keys, gr_ak_...): it reaches only that agent's runs, runs the published version as the agent, within the key's limits (requests per minute, runs and dollars a day, allowed addresses, expiry).

from graticor import AgentApi

api = AgentApi()                                   # GRATICOR_AGENT_KEY, GRATICOR_BASE_URL
run = api.runs.create(message="Where is my invoice?", end_user="customer-42", wait=True)
print(run["status"], run["output"])
for event in api.runs.stream("And the one before?", end_user="customer-42", thread_id=run["threadId"]):
    print(event["type"])                           # run.started, llm.delta, tool.started...
api.outcome(run["id"], success=True)               # a key with the outcomes scope
print(api.agent()["key"])                          # the key's name, prefix, expiry and limits

api.run(message, wait=True), api.runs.get/wait/cancel(run_id), api.runs.stream(message, ...) (the TypeScript SDK's spelling; api.stream(...) works too). The key comes from the argument or GRATICOR_AGENT_KEY (never from a URL), never shows in repr() or an error, and only goes to /api/agent-api/v1. A personal token there answers "Use an agent API key (gr_ak_…) here." Errors come back as GraticorApiError with Graticor's code: invalid_agent_key, agent_key_expired, agent_key_disabled, ip_not_allowed, not_published, agent_paused, run_as_unconfirmed, rate_limited, key_daily_limit, key_busy. Starting a run (and the stream) is retried only on 429 and 503, reads also on 5xx, up to retries times (AgentApi(retries=3) by default, as the TypeScript agentApi), after the wait Retry-After asks for; an answer that asks for more than 30 s (a key's daily cap lasts until midnight UTC) raises its GraticorApiError at once instead of waiting. Keys are server-side secrets: never ship one in a browser or an app.

Keys from the command line

graticor keys manages an agent's keys on the same routes as Settings › Access › API keys (a personal token with full scope: an Agents SDK key or a config token can't):

graticor keys list support-bot                      # NAME, PREFIX, STATUS, LAST USED, EXPIRES (in 9 days)
KEY=$(graticor keys create support-bot --name prod-server --expires 90)     # the key alone on stdout
graticor keys create support-bot --name ci --scope runs --rpm 120 -o key.txt
graticor keys rotate support-bot prod-server --grace 24 -o key.txt
graticor keys revoke support-bot gr_ak_AbCdE --yes
  • A new key is shown once: alone on stdout, or written to -o FILE (readable by you only on Linux and macOS; on Windows the file keeps its folder's permissions); the note goes to stderr, and the key never appears in an error. --json prints Graticor's answer, the key included.
  • create sends only the flags you give (--expires 30|90|365|never or --expires-in-days N, --scope runs|a2a|outcomes|mcp, --rpm, --runs-a-day, --usd-a-day, --allow-ip); Graticor's defaults apply to the rest. A key that never expires needs owner level on the agent.
  • rotate and revoke take the key's id, its prefix or its name among the live keys. rotate keeps the old key working for --grace hours (default 24, 0 to 720). revoke asks first on a terminal ("Requests with it fail at once."); in a script it needs --yes.
  • Exit codes: 0 ok, 1 refused (a key that does not resolve, or Graticor's refusal: revoked, expired, already rotated), 2 bad usage or a Graticor error.

Rotation in a deploy script: the old key keeps working during the grace, so nothing fails while the new one rolls out.

graticor keys rotate support-bot prod-server --grace 24 -o key.txt
deploy --set GRATICOR_AGENT_KEY="$(cat key.txt)" && rm key.txt   # your deploy step

Reviewing memories

With memory review on ("Check first" in the agent's Memory settings), memories the model writes wait until one of the agent's reviewers accepts, edits or rejects them. In the console they wait in the agent's Monitor › Memory and in the Inbox (/approvals):

mem = gr.memories("support-bot")                   # or definition.memories, agent.memories
queue = mem.review_queue()                         # {"summary", "items", "next"}, oldest first
for m in mem.pending():                            # every pending memory, page by page
    if "refund" in m["content"]:
        mem.reject(m["id"], note="We never promise refunds.")
    else:
        mem.accept(m["id"], kind="preference")     # edit then accept: content, kind, importance...
mem.history(memory_id)                             # every change, with before/after snapshots
gr.runs.get(run_id).memory_diff()                  # what one run recalled and changed

These need agents.write and edit level on the agent. Bulk changes and restores stay in the console.

Configuration reference

gr.init() arguments win over environment variables, which win over defaults. Each variable is read as GRATICOR_<X> first; when that is unset (or blank), the SDK reads its name before Graticor, so existing setups keep working.

Environment init() argument Default Meaning
GRATICOR_API_KEY api_key none personal token (Agents SDK scope recommended), sent as a Bearer token
GRATICOR_BASE_URL base_url http://localhost:8787 Graticor API origin
GRATICOR_ACCOUNT account the token's account account id for an organization (x-graticor-account)
GRATICOR_AGENT_NAME agent none default agent name for gr.agent() and the CLI
GRATICOR_ENV environment dev environment on traces; dev reads the draft, staging the staging version (the published one while the agent has none), anything else the published version
GRATICOR_AGENT_VERSION agent_version from the environment draft, published, staging or a version number
GRATICOR_AGENT_KEY AgentApi(key) none an agent's own API key (gr_ak_...) for gr.AgentApi
GRATICOR_CAPTURE_CONTENT capture_content 1 0 keeps prompts and outputs out of traces
GRATICOR_ALLOW_INSECURE allow_insecure 0 allow plain http:// to a host other than localhost
GRATICOR_EXPORT_ALL_SPANS export_all_spans 0 1 sends every span of the process, not only agent traces
GRATICOR_OFFLINE offline 0 1 sends nothing to Graticor (no registration, config pull or span export)
instrument "auto" instrumentors to enable: "auto", a list of names, or False
disable_openai_tracing None OpenAI Agents SDK: True traces to Graticor only; None also when its exporter has no OpenAI key; False leaves it alone
tracer_provider the global one attach to this TracerProvider
span_exporter Graticor OTLP replace the exporter (tests, debugging)
timeout, export_timeout 30 s, 10 s API request and OTLP export timeouts

The SDK sets OTEL_SEMCONV_STABILITY_OPT_IN=gen_ai_latest_experimental and OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_ONLY when content capture is on and you did not set them yourself. Agent names use lowercase letters, digits, - and _ (max 63).

Waits on Graticor stay short where your code is waiting: the registration gr.agent() makes at import waits at most 5 seconds, a config pull from agent.instructions / agent.param() at most 5 seconds without retry (other threads get the copy they have meanwhile, and a failed pull is not retried for a few seconds), and gr.flush(timeout) keeps to its timeout. agent.config(refresh=True) uses the full timeout with a retry.

Command line

graticor whoami                         who the key belongs to, the account, the key's scope (Key line), what it may do
graticor serve module:attr [--name NAME] [--concurrency N] [--poll-wait S]
                                        run a worker (Agent, LangGraph graph, crew, OpenAI agent, function)
graticor eval module:attr --dataset D [--evaluator ID]... [--gate ID=0.8]... [--repetitions N]
              [--concurrency N] [--experiment NAME] [--name NAME]
graticor eval --on-graticor AGENT --dataset D [--gate ID=0.8]... [--version V] [--timeout S]
                                        Graticor runs the experiment; this waits and gates (exit 3: still running)
graticor graph module:attr [--push]     print the architecture graph, or register it
graticor pull AGENT [-o FILE] [--version draft|published|staging|N] [--format json|python]
                                        the agent as AGENT.agent.json (or AGENT.agent.py)
graticor push FILE [--name NAME] [--force] [--dry-run] [--drop-unresolved] [--publish [NOTE]]
                   [--stage staging|production]
                                        create or update agents from an .agent.json or a .py
graticor promote AGENT [--version N] [--note NOTE]
                                        the staging version (or N) to production
graticor workflow pull|push|diff|validate AGENT [FILE]
                                        a workflow agent's steps as a file
graticor keys list|create|rotate|revoke AGENT ...
                                        an agent's API keys (a new key is shown once)
graticor runs start AGENT MESSAGE [--var NAME=VALUE]... [--wait] | get RUN | wait RUN | outcome RUN
                                        runs with your key
graticor skills from-run TRACE_ID [-o FOLDER] [--import]
                                        a skill drafted from a successful run
graticor sandbox ...                    the sandbox daemon (Linux or WSL)
graticor --version                      the package version (graticor 0.4.0)

graticor skills from-run TRACE_ID [-o FOLDER] [--import] drafts a skill from a successful run (the files, the scan and notes; --import adds it to the account's skills): it needs a personal token with full scope. It also takes --skill SKILL_ID (a new version of that skill), --focus TEXT (300 characters at most), --include-scripts, --include-example and --changelog. python -m graticor.cli_config skills from-run TRACE_ID does the same.

Exit codes of the config and run commands: 0 ok; 1 refused (names not in the account, a draft changed since the pull, validation errors, readiness or staging blocks a publish, a promotion Graticor refuses, a failed run, differences found by workflow diff); 2 bad usage or a Graticor error (for example an Agents SDK key on a push); 3 a run that has not finished (it waits for a person, or the timeout passed).

module is a module path (my_app.agent) or a file (agent.py, imported with its own directory first on sys.path, as python agent.py would, so its sibling imports work); without :attr the module's first Agent is used. Global options, given before the command: --base-url, --account, --env, --config-version, --allow-insecure, -v, --version. The key is read from GRATICOR_API_KEY only, never from the command line. The agent of a target that is not an Agent: see Serving. Exit codes: 0 ok, 1 gate failed or command failed (no graph found), 2 bad usage (a bad option such as --repetitions 11, a module that fails to import: the message names the error, -v shows the traceback, an object several agents own without --name) or Graticor error, 130 interrupted.

The sandbox daemon (Linux or WSL)

graticor sandbox runs Graticor agents' sandboxes on a machine of yours: a Your infrastructure runtime (Agents › Connections › Runtimes › the runtime › Connect a machine shows the exact command), a Graticor sandbox host (--platform, added by a platform operator in Operate › Sandbox hosts, /admin/sandbox-hosts), or the machine Graticor rents for a dedicated runtime (its bootstrap starts it). It connects out to Graticor over https and pulls work; Graticor never connects to it.

What the server needs (as of 2026-11-06). Each of the three is gated on the Graticor server:

  • every kind needs the wheel (GRATICOR_SANDBOX_DAEMON_WHEEL; unset, the commands answer 409 daemon_package_missing) and a GRATICOR_PUBLIC_API_URL on https (http only for localhost; else 409 public_url_missing);
  • sandbox hosts run agents' sandboxes only with GRATICOR_SANDBOX_DRIVER=sandbox_host, and a host must run the Docker backend with gVisor (409 platform_needs_isolation otherwise);
  • dedicated machines also need live rentals (GRATICOR_LIVE_RENTALS=1; else 403 live_rentals_off) and confirmed machine pins (GRATICOR_MACHINE_PYTHON_IMAGE and GRATICOR_MACHINE_RUNSC_SHA256; else 409 machine_pins_unconfirmed).

The production files in this repository (deploy/prod/) set the https public URL but no wheel and no sandbox driver, and keep live rentals off, so a server deployed from them runs no sandboxes and rents no machines. docs/AGENTS.md ("Before production") records the daemon's Linux tests (npm run test:daemon-linux: 29 passed on 2026-11-01) and one real daemon on the process backend against a local Graticor. A sandbox host with gVisor and a rented machine with a co-located model are listed there as not run on a real system yet.

Install. Graticor serves the daemon package itself: the command the console shows downloads the wheel from your Graticor (/api/agents/runtime/daemon/package/<file>), checks its sha256 with sha256sum -c, installs that file in a virtual environment and starts the daemon. It is never installed from PyPI by name. The operator builds the wheel with node scripts/build-daemon-wheel.mjs (this package, version 0.4.0) and points GRATICOR_SANDBOX_DAEMON_WHEEL at it; the machines list says "Update available" for daemons older than the configured wheel. Updating needs no new code: "Update it" shows a command that reads the machine's own token from its state directory (daemon.json) into curl's stdin (the package route accepts it), checks the sha256, reinstalls the package and restarts the daemon the way it runs (service, terminal or Docker). Nobody is emailed. A machine installed before Graticor (pac-sandbox.service, ~/.pac-sandbox or the pac-sandbox container, its state in /var/lib/pac-sandbox) keeps working, and its update moves it to the names below.

Enroll once. The one-use code Graticor shows (it starts with gre_) is read from a file (--enroll-file PATH, deleted after enrolling), stdin (--enroll-file -; the console's command types it at a read -rs prompt), GRATICOR_SANDBOX_ENROLL_FILE, or GRATICOR_SANDBOX_ENROLL_TOKEN (removed from the environment once read). It is never read from the command line (--enroll gre_... is refused). The daemon then keeps its token and instance key in its state directory (0700: --state-dir, else GRATICOR_SANDBOX_STATE_DIR, else /var/lib/graticor-sandbox as root and ~/.local/state/graticor/sandbox otherwise; daemon.json 0600), and later starts reuse it. A machine enrolled before Graticor keeps its enrollment: while /var/lib/graticor-sandbox does not exist, the daemon uses /var/lib/pac-sandbox where it is (as root's default, and when --state-dir names /var/lib/graticor-sandbox), and it moves a user's ~/.local/state/pac-agents/sandbox to ~/.local/state/graticor/sandbox on first use.

graticor sandbox --base-url https://api.example.com --enroll-file /etc/graticor/sandbox.enroll \
  --name build-01 --backend auto
Flag Meaning
--base-url URL the Graticor API (GRATICOR_BASE_URL); https only, http only for localhost with --insecure-localhost
--enroll-file PATH|- the one-use code (GRATICOR_SANDBOX_ENROLL_FILE)
--insecure-localhost allow http://localhost (development only)
--name NAME how the machine shows in the console (default: the host name)
--backend auto|docker|process the isolation (GRATICOR_SANDBOX_BACKEND; auto: Docker when it answers for this user)
--state-dir DIR where the token, sessions and idempotency records live (GRATICOR_SANDBOX_STATE_DIR)
--max-sessions N sandboxes at once (GRATICOR_SANDBOX_MAX_SESSIONS; default (memory − 2 GB) / 2 GB)
--allow-image KIND=IMAGE another image for a kind: python, node, python-node or browser (repeatable; GRATICOR_SANDBOX_ALLOW_IMAGES, a comma list), e.g. browser=<image@sha256:...>
--allow-same-user process backend without root: every sandbox runs as this user (shown as "Shared user"; Graticor then blocks agents that people outside the company reach)
--workspace-days N process backend only: at start, delete conversation workspaces untouched this many days (7); the Docker backend keeps them
--engine-container NAME the co-located model's container, which Graticor may restart ("Reload the model" on a dedicated machine; Docker backend). Graticor's machine bootstrap passes it; without it the daemon answers that it runs no model Graticor can reload
--platform enroll as a Graticor sandbox host (needs the Docker backend with gVisor runsc)
--check print what isolation and network enforcement this machine gives, and exit
--once one poll, then exit (diagnostics)

Backends.

  • docker: full isolation, with exactly the hardening of Graticor's own sandboxes (no capabilities, a non-root user, a read-only root, CPU, memory and process limits), gVisor (runsc) when installed, and network rules enforced through the egress proxy Graticor serves. Conversation workspaces stay on the machine's disk between sessions. It runs the browser image too (--shm-size 512m, with the verified helpers copied in).
  • process: basic isolation for machines without Docker. As root each session runs under its own system user (one per session slot) with its own 0700 workspace, rlimits, a scrubbed environment, its process group killed at the timeout, and network none / setup enforced with a network namespace; pip installs into a per-environment venv, npm into a prefix, apt is refused ("System packages need the Docker backend."), and the browser image is refused. Other network modes are advisory here.

Network. The daemon's egress proxies refuse private and metadata addresses, every address of this machine (its interfaces, the default route's source, its host names) and Graticor's, plus GRATICOR_SANDBOX_DENY_ADDRESSES (for a NAT's public address). A Your-infrastructure runtime's private systems are the exception you list in the console. A Graticor sandbox host never receives private systems.

Signing requests with a secret. No daemon ever holds a secret's value. When an environment signs requests with a secret, the daemon's egress proxy hands those requests to Graticor's signing relay (POST /api/agents/runtime/daemon/relay, a grr_ ticket), which adds the secret on the server. The daemon gets only the host and header names, the certificates and the ticket. Only the Docker backend can relay; such sandboxes start only on machines that can (apps/api/src/agents/environments/relay.ts, daemon/remote.ts).

Safe to repeat. Before it runs a keyed operation the daemon records {key, state, result} in its state directory, per environment, so a call Graticor sends again after its own restart gets the first result instead of running twice; a key started without a result answers outcome_unknown.

As a service. The console's "How should it run?" offers three ways, each with a command that checks the machine (--check) before it enrolls it and a restart command that needs no code. As a service (recommended) installs the package in /opt/graticor-sandbox, writes the code to /etc/graticor/sandbox.enroll (0600; the daemon deletes it once enrolled), keeps the state in /var/lib/graticor-sandbox and installs graticor-sandbox.service (the same unit name as the rented machines' bootstrap) with Restart=on-failure and RestartPreventExitStatus=2 3, so a refused code or a revoked machine does not loop; start it again with sudo systemctl restart graticor-sandbox. In this terminal runs ~/.graticor-sandbox/bin/graticor sandbox until the terminal closes; start it again with the same line without --enroll-file. In Docker (Docker backend only) runs the daemon in docker:27-cli with --network host, the host's Docker socket and the state directory at the same path inside and outside; start it again with docker start graticor-sandbox (the docker:27-cli image is not pinned by digest yet: a TODO in apps/api/src/agents/environments/daemon/package.ts). Without Docker the commands start --backend process with sudo, so each sandbox gets a user of its own. SIGTERM stops polling, finishes running operations for up to 30 s and says goodbye to Graticor. Exit codes: 0 stopped, 2 enrollment refused or bad usage, 3 revoked. Logs have one line per operation (kind, ids, duration, ok), never code, contents, outputs or tokens; HTTPS_PROXY is honoured, redirects are refused.

The daemon's backends need POSIX: on Windows the command stops with "Run the sandbox daemon on Linux (or WSL).", and every other command works there. See graticor sandbox --help.

On Windows. Run it in WSL (the console's "On Windows (WSL)" fold has the same steps): in PowerShell as administrator wsl --install -d Ubuntu, restart and open Ubuntu; in Ubuntu sudo apt update && sudo apt install -y python3-venv curl; for full isolation turn on WSL integration for Ubuntu in Docker Desktop (or sudo apt install -y docker.io && sudo usermod -aG docker $USER, then reopen Ubuntu); for the service, turn on systemd (grep -qs '^systemd=true' /etc/wsl.conf || printf '[boot]\nsystemd=true\n' | sudo tee -a /etc/wsl.conf, then wsl --shutdown in PowerShell). Run the console's command in Ubuntu, not in PowerShell; the laptop must stay on and awake for the agents' tools to run.

Examples

All examples read GRATICOR_* from the environment, run on the Simulated model until you assign another one, and print the agent's console page and the trace link. Against a local dev API they need no model key, except anthropic_tools.py (your own ANTHROPIC_API_KEY); install each example's framework first (pip install langgraph, crewai, openai-agents, llama-index-workflows...). llamaindex_rag.py reads the knowledge base named by GRATICOR_KB (default docs) and evaluate_ci.py the dataset named by GRATICOR_DATASET (default faq-smoke): create them in the console first.

File Shows
quickstart_openai.py the OpenAI client on the router, a session
langgraph_agent.py a StateGraph with a ToolNode, two slots, a param, register, --serve
crewai_crew.py a two-agent crew with a slot per agent
openai_agents_handoffs.py triage with handoffs, one slot per agent
llamaindex_rag.py a LlamaIndex Workflow over a Graticor knowledge base, with citations
anthropic_tools.py the Anthropic SDK with your own key and a tool loop, traced to Graticor
worker_serve.py a worker with memory, a tool, a param and logs
evaluate_ci.py gr.evaluate with gates and CI exit codes

Troubleshooting

"Could not reach Graticor at ... Is it running?" The API is not at GRATICOR_BASE_URL. Your app keeps running; spans are dropped and registration is retried on the next config pull or serve().

"Refusing to send the Graticor API key over plain http" GRATICOR_BASE_URL is http:// to another machine. Use https, or set GRATICOR_ALLOW_INSECURE=1 on a trusted network.

"Graticor answered with a non-JSON body (text/html)" GRATICOR_BASE_URL points at the web console (or a proxy page), not at the API. Use the API's origin (http://localhost:8787 in development).

401 / 403 token_scope. The key is wrong, revoked, or its scope does not cover the call (an Agents SDK key reaches only the routes the package calls). With an organization account, set GRATICOR_ACCOUNT. Check with graticor whoami: its Key line says what the key itself can do (Agents SDK, Agent configs, Read only or Full). graticor push, workflow push and --publish write drafts: they need a config token (Agent configs) or a personal token with full scope; skills from-run needs full scope.

"The draft of ... changed since you pulled it". Someone saved the agent (or its workflow) in the console after your pull. graticor workflow diff AGENT FILE shows what your push would change; pull again and redo your edit, or push with --force to replace what they saved.

A push fails with names that are "not in this account". The file names a knowledge base, agent, model connection... that this account does not have (files move between accounts by name). Create it, rename it to match, or push with --drop-unresolved and pick it in the console.

409 model_not_assigned. Neither the slot nor the agent's main model is set. Pick one in the console (Build > Models). A brand new code agent starts on the Simulated model.

The answers start with "[simulated]" (followed by lorem ipsum, or "Based on : …" after a tool call). The agent (or that slot) still uses the Simulated model, or a Graticor deployment that is a dry run (the server runs without GRATICOR_DEPLOY_EXECUTE=1).

Console edits do not apply. The code reads the published version: set GRATICOR_ENV=dev or GRATICOR_AGENT_VERSION=draft, or publish. Config is cached for 60 seconds (agent.config(refresh=True) forces a pull).

"GRATICOR_ENV is not set: this process reads the draft of ...; v3 is published." The code runs without GRATICOR_ENV, so it reads the draft, edits nobody published included. On a production server set GRATICOR_ENV=prod (it then reads the published version). On a dev machine set GRATICOR_ENV=dev to keep the draft and silence the warning.

"No worker is connected for ..." Start one: graticor serve module:attr. Check that the worker uses the same account and agent name as the console page (the Playground shows the connected workers; the worker logs the agent it serves, --name picks it).

"OPENAI_API_KEY is not set, skipping trace export" comes from the OpenAI Agents SDK's own exporter to OpenAI. gr.init(disable_openai_tracing=True) removes it; the default does so too once the SDK is imported, unless an OpenAI key is set for it.

No graph in Build › Graph or Monitor › Charts. The object was not recognised, or the adapter could not read it (see the warning). Run graticor graph module:attr to check, or register a dict. The observed graph appears after the first traces either way.

No LLM spans. The framework's instrumentor is not installed: add the matching extra (for example pip install "graticor[anthropic]"). gr.init(instrument=[...]) with an unknown name logs the known ones. Turn on -v (CLI) or logging.getLogger("graticor").setLevel("DEBUG").

Traces show "Content hidden for your role". Your role lacks agents.write; ask an admin. "Content hidden" with that permission: the agent keeps metadata only (agent › Settings › Data & advanced › Trace content), or the code ran with GRATICOR_CAPTURE_CONTENT=0.

Development

python3 -m venv .venv && . .venv/bin/activate          # Windows: py -3.13 -m venv .venv; .venv\Scripts\activate
pip install -e "sdks/python[dev]"
pytest sdks/python/tests

There are 44 test files in tests/. Tests never call a real network: the Graticor API is faked with httpx.MockTransport or a loopback server on 127.0.0.1 (which also plays the model router and decodes OTLP). Tests of a framework adapter use small fakes and, when the framework is installed, real objects too.

The publishing workflow (.github/workflows/publish-python.yml) runs these tests before each release; CI on pull requests does not (.github/workflows/ci.yml runs the TypeScript SDK's). Run them yourself before you change the package. The sandbox daemon's backend tests (test_sandbox_process, test_sandbox_docker) are Linux-only and skipped on Windows; its protocol tests (test_sandbox_daemon) run everywhere. npm run test:daemon-linux from the repository root runs all three files on Linux, or inside a local python:3.12-slim container elsewhere (it never pulls the image; scripts/daemon-linux-tests.mjs).

tests/test_live_api.py runs the same paths against a real Graticor API (router, LangGraph graph and traces, a worker serving a playground chat, knowledge, memory, evaluations and the CLI, params and slots). It is skipped unless you point it at one; a local dev API needs no model key, since new code agents use the Simulated model:

export GRATICOR_SDK_E2E_URL=http://127.0.0.1:8787   # the API (npm run dev:api from the repository root)
export GRATICOR_SDK_E2E_KEY=gr_...                   # a token with the Agents SDK scope
# GRATICOR_SDK_E2E_ADMIN_KEY=gr_...                  # a full-scope token for the checks, when dev auth is off
pytest sdks/python/tests/test_live_api.py

Metadata

Release files for graticor 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for graticor 0.4.0
File Size Uploaded Provenance Actions
graticor-0.4.0.tar.gz 391.7 kB With provenance Details for graticor-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for graticor 0.4.0
File Interpreter ABI Platform Actions
graticor-0.4.0-py3-none-any.whl Python 3 none any Details for graticor-0.4.0-py3-none-any.whl

Total release size: 658.4 kB

Release files / graticor-0.4.0.tar.gz

Download URL graticor-0.4.0.tar.gz
Size 391.7 kB
Tags Source
SHA-256 checksum
How to use checksums
848753a7d93f904f0b2e713d65cb8a9b5cc8eb3c97269bd0f2f7c655954b0bff
BLAKE2b-256 checksum
How to use checksums
48dc62048a2989566441d76293165dfff3bb7b3ce0dde2e81055c85d045f36ff
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Release files / graticor-0.4.0-py3-none-any.whl

Download URL graticor-0.4.0-py3-none-any.whl
Size 266.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
790e2a9294b5fc8818ec84f6f010a1280a10739bfba3643e4367cfed5e5586a1
BLAKE2b-256 checksum
How to use checksums
a418e1afcbc1d3c616c890b1c8c044008f21b450e0e7ce17468956779ab18d48
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Security for graticor 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for graticor-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page