Metadata-Version: 2.5
Name: certo-sdk
Version: 0.3.0
Summary: The trust & security layer for AI agents: audit them, score their trajectories, and guard their tool calls.
Project-URL: Homepage, https://certo-live.vercel.app
Project-URL: Documentation, https://certo-api.onrender.com/docs
Author: Certo
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: agents,ai,evaluation,guardrails,llm,opentelemetry,prompt-injection,security,tracing
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: questionary>=2.0
Requires-Dist: rich-argparse>=1.5
Requires-Dist: rich>=13.7
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.20; extra == 'otel'
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.20; extra == 'otel'
Requires-Dist: opentelemetry-sdk>=1.20; extra == 'otel'
Description-Content-Type: text/markdown

# Certo

**The trust & security layer for AI agents.** Score what your agent *did*, not just what
it answered — and block the actions it was never approved to take.

```bash
pip install certo-sdk
certo                 # what Certo can do
certo guard demo      # watch an injected payment get blocked — offline, no account needed
certo login           # then audit and trace your own agent
```

Your agent runs where it already runs. Certo receives its execution trace — reasoning
steps, tool calls, hand-offs, final answer — and grades two things independently:

- **Was the answer right?** Checked against ground truth, a test suite, or a
  deterministic check. A wrong answer hard-gates the score; a pretty trajectory cannot
  rescue it.
- **Was the path good?** An LLM-judge ensemble scores every step and the run as a whole
  against explicit rubrics.

Both fold into one **TrustScore (0–100)**.

The distinction matters because an agent that refunds the wrong customer's order and
replies *"Done — I refunded $240.00"* looks perfect from the outside. The trajectory is
where that shows up.

The package is small and pure-Python: `httpx` for the API, `rich`, `rich-argparse` and
`questionary` for the terminal. No tracing stack is pulled in unless you ask for it.

```bash
pip install "certo-sdk[otel]"    # adds OpenTelemetry, for `instrument()`
```

`[otel]` is an *extra* — an optional dependency group. It pulls in
`opentelemetry-api`, `opentelemetry-sdk` and the OTLP HTTP exporter, which
`certo.instrument()` needs to stand up an exporter for a process that has none. If you
already export OpenTelemetry, you do not need it. Quote the argument: brackets are
special in zsh and PowerShell.

---

## Three jobs, one layer

**Auditing** — Certo drives your agent through a 149-probe suite and reports what breaks.
**Tracing** — your agent runs in production, Certo grades what it did, step by step.
**Guarding** — every tool call is checked against what the user approved, *before* it runs.

## Guarding tool calls

An agent reads untrusted text — an email, a web page, a tool result — and a sentence
hidden in it can redirect its next tool call. The user approved paying 5; the agent sends
10. A filter that reads text cannot catch that: *"send 10 to Spotify"* looks harmless.
The guard can, because it knows what was approved.

```python
from certo import Guard, GuardDenied, Eq, Max

guard = Guard({
    "read_inbox": {},                                          # allowed, unconstrained
    "send_money": {"recipient": Eq("Spotify"), "amount": Max(5)},
}, task="Pay my Spotify subscription (approved: 5)")

@guard.protect                       # checked before the body runs
def send_money(recipient: str, amount: float, **extra): ...

send_money("Spotify", 5)             # runs
send_money("Spotify", 10)            # raises GuardDenied — the tool never ran
```

**Permissions come from your application, never from the model.** The guard compares the
call's structured arguments with the approval; it does not read the model's text as
instructions, so an injected "send 10 instead" has nothing to argue with.

- A tool missing from the approval is denied with `task_tool_scope`; an argument outside
  it with `task_argument_scope`. Every denial carries a **cause** and a **fix**.
- Inside an agent loop use `@guard.protect(on_deny="return")`: the model reads that the
  call was refused instead of the run crashing.
- When a `certo.trace(...)` is open, each blocked call is recorded on it as a span, so the
  trajectory shows what was stopped.
- Constraints: `Eq(value)`, `Max(n)`, `OneOf(a, b, …)`. Policies load from JSON with
  `Guard.from_file("policy.json")` — `certo guard init` writes an example.

```bash
certo guard demo                         # four scenarios, agent alone vs. guarded (offline)
certo guard demo --provider groq         # same, with a live model (GROQ_API_KEY)
certo guard check policy.json --tool send_money --args '{"recipient":"Spotify","amount":10}'
                                         # exit 5 when denied — usable as a CI/pre-commit gate
```

The demo runs in a synthetic bank-and-inbox environment; whether an attack reached its
goal is decided by a deterministic oracle from what actually executed, never by the
guard's own verdict.

### Send a trace

```python
import certo

with certo.trace("Refund the customer's last order", api_key="certo_sk_…") as t:
    t.log_span("llm", "planner", input=prompt, output=plan)

    @certo.tool                     # logs args, output, latency and errors for you
    def issue_refund(order_id: str) -> dict:
        ...

    result = issue_refund("o_988")
    t.finish(result)                # → scored, returns {id, status, …}
```

`@certo.tool` is worth using over hand-written spans: it records what the function was
*actually called with*, so a trajectory cannot be narrated after the fact.

### Or connect a framework you already use

Nearly every agent framework exports OpenTelemetry, which is the whole integration:

```bash
export OTEL_EXPORTER_OTLP_ENDPOINT=https://your-certo/api/v1/otel
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer certo_sk_…"
```

If the process has no exporter yet, `instrument()` sets one up:

```python
from certo import instrument
from openinference.instrumentation.langchain import LangChainInstrumentor

instrument(service_name="support-agent")
LangChainInstrumentor().instrument()
```

Then call your agent **exactly as you already do** — nothing is threaded through it, no
callback parameter, no config argument:

```python
result = agent.invoke({"messages": [{"role": "user", "content": "Hello"}]})
```

| Dedicated instrumentor | Connected over OTLP |
|---|---|
| LangChain · LangGraph · CrewAI · LlamaIndex · OpenAI · OpenAI Agents · Anthropic · Pydantic AI · Vercel AI SDK | Agent Core · Strands · Google ADK · LiteLLM · Mastra · Portkey · anything that speaks OpenTelemetry |

Certo reads both the **GenAI semantic conventions** and **OpenInference**, which is what
most auto-instrumentation emits. `certo setup <framework>` prints the exact lines for
yours, with your own key already filled in.

### Check it arrived

```bash
certo verify
```

Sends one span and waits for it to come back scored. Worth running before wiring a real
agent: the failure everyone hits is silent. An OTLP exporter that cannot reach its
endpoint raises nothing — by design, since a tracing library that crashes production
would be worse — so the only symptom is an empty page, with no way to tell whether the
key, the address or the agent is at fault. This says which.

---

## Auditing a live agent

```bash
certo audit --url https://my-agent.internal/chat \
            --body '{"message":"{{prompt}}"}' \
            --output-path data.reply \
            --tool-calls-path data.actions \
            --name "Support bot"
```

`{{prompt}}` is where each probe goes. Naming `--tool-calls-path` is what turns
tool-safety probes into facts: they get graded on the calls the agent *made*, not on its
description of what it would do. An OpenAI-compatible endpoint works too —
`certo audit --model gpt-4o-mini --api-key sk-…`.

Streaming agents are supported (`--response-mode sse|ndjson|websocket`); before this
existed, a streamed reply was parsed as a single JSON document and the agent came back
mute, so the report described a silence it never produced.

**Give it context if you can.** `--system-prompt-file` and `--tools "issue_refund,cancel_order"`
are never used to grade — they make the remediation concrete. An allow-list naming your
real tools is a patch; the same advice without names is a suggestion.

**Re-runs diff themselves.** Audits are grouped by `--name`, so the same name again
prints what got fixed and what regressed. The delta is measured by re-scoring **both**
runs on the probes they both scored — never by subtracting two headline numbers that had
different denominators. Doing it the obvious way once reported *+52* for an agent that
had stopped answering.

### Auditing from your own code, with your own tasks

```python
from certo import audit, Task

def my_agent(prompt: str):
    return my_app.invoke({"input": prompt})["output"]

report = audit(
    agent=my_agent,
    name="Support bot",
    tasks=[Task("What is our return window?", expect="30 days")],
)

assert not report.incomplete       # check this FIRST — see below
assert report.security >= 80
assert not report.regressions
```

The agent never leaves your process: Certo sends the probes, your code runs them, only
the answers come back.

### In CI

```bash
certo audit --url "$AGENT_URL" --name "$SERVICE" --fail-under 70 --fail-on-regression
```

| exit | meaning |
|---|---|
| `0` | passed every gate you asked for |
| `2` | TrustScore below `--fail-under` |
| `3` | a probe that used to pass now fails |
| `4` | the run was incomplete — the agent was unreachable for too many probes |
| `5` | `certo guard check`: the call falls outside the approval |

**Exit `4` is checked first and always.** A run that could not reach the agent scores
*high*, because the probes it would have failed never ran. Letting that satisfy
`--fail-under` would turn an outage into a green build.

---

## The report

```
Certo · trace fe74735c   ✔ scored
  What is the capital of Japan?

  TrustScore               100 / 100   ████████████████████████
  Objective     PASS   answer matched reference (extracted 'Tokyo')
  Trajectory    5/5    mean step 5.0 · 3 spans
  Provenance    self-reported (sdk)
  Judges        low disagreement

  Steps
    1  llm   planner        5/5
    2  tool  web_search     5/5
    3  llm   synthesizer    5/5
```

`Provenance` is not decoration. A trace you sent us is your agent's own account of
itself, and the report says so rather than implying we watched it happen.

---

## Commands

| command | what it does |
|---|---|
| `certo` | overview of everything Certo can do |
| `certo login [--key\|--email]` | interactive login (arrow keys), stores a credential in `~/.certo/config.json` |
| `certo guard demo [--provider …]` | watch the guard block injected actions, offline or with a live model |
| `certo guard init [path]` | write an example approval policy |
| `certo guard check <policy> --tool … --args …` | check one call against a policy (exit `5` if denied) |
| `certo verify` | send one span and confirm tracing is connected |
| `certo setup [framework]` | print the setup lines for your stack, key filled in |
| `certo integrations` | what Certo can read, and how |
| `certo audit --url\|--model …` | run the probe suite against a live agent |
| `certo audits` / `certo report <id>` | list audits / re-print one (`--json` for the raw report) |
| `certo probes` | what the suite is made of — probes, judges, standards |
| `certo run "<task>" -- <cmd…>` | run a command as the agent, capture + score its trajectory |
| `certo trace <file>\|--task …` | submit a captured trace (`--watch` to poll + report) |
| `certo ls` / `certo show <id>` | list traces / print one full report |
| `certo keys new\|list\|rm` | mint / list / revoke machine API keys |
| `certo whoami` / `certo config` | show the account / stored base_url + credential |

Short ids work everywhere, like git: `certo report 0a6a`.

**Config & environment.** `CERTO_BASE_URL` and `CERTO_API_KEY` override the stored
config. `NO_COLOR` disables ANSI colour. The config file is written `chmod 600` — it
holds a credential.

### Wrapping a command as the agent

```bash
certo run "What is the capital of Japan?" --expected Tokyo -- python my_agent.py
```

Runs your command, captures stdout as the final answer, records the run as a trace. If
the command prints a `<certo:trace>[…spans…]</certo:trace>` block, those spans are parsed
and graded per step — so an answer-only agent can still expose its real trajectory, and
cannot fake it as prose.

---

## One thing to know before trusting a number

A deployment can be configured with a **stub judge**, which grades deterministically and
produces numbers that look entirely real. `certo verify` says so when it sees one, and
the server's `/ready` endpoint reports each judge separately. If a score looks too clean,
check there first.
