Metadata-Version: 2.4
Name: komodor-agentops
Version: 0.7.2
Summary: Python SDK for AgentOps observability.
Author: Komodor Ltd.
License-Expression: LicenseRef-Komodor-Proprietary
Project-URL: Homepage, https://agentops.komodor.com
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: agentops-otel~=0.7.2
Requires-Dist: agentops-rpc~=0.7.2
Requires-Dist: croniter>=2.0
Requires-Dist: httpx
Requires-Dist: pydantic>=2.7
Requires-Dist: pydantic-settings>=2.0
Requires-Dist: python-frontmatter>=1.2.0
Requires-Dist: pyyaml>=6.0.3
Requires-Dist: regex>=2024.11.6
Provides-Extra: server
Requires-Dist: agentops-otel[grpc]; extra == "server"
Provides-Extra: grpc
Requires-Dist: agentops-otel[grpc]; extra == "grpc"
Provides-Extra: langchain
Requires-Dist: agentops-otel[grpc]; extra == "langchain"
Requires-Dist: langchain-core; extra == "langchain"
Provides-Extra: claude-code
Requires-Dist: agentops-otel[grpc]; extra == "claude-code"
Requires-Dist: claude-agent-sdk>=0.2.163; extra == "claude-code"
Provides-Extra: adk
Requires-Dist: agentops-otel[grpc]; extra == "adk"
Requires-Dist: google-adk[mcp]<3,>=2.8; extra == "adk"
Requires-Dist: litellm>=1.84; extra == "adk"
Provides-Extra: agno
Requires-Dist: agentops-otel[grpc]; extra == "agno"
Requires-Dist: agno<3,>=2.6; extra == "agno"
Requires-Dist: anthropic<1,>=0.40; extra == "agno"
Provides-Extra: codex
Requires-Dist: agentops-otel[grpc]; extra == "codex"
Requires-Dist: openai-codex>=0.163.0; extra == "codex"
Provides-Extra: all
Requires-Dist: komodor-agentops[adk,agno,claude-code,codex,langchain]; extra == "all"
Dynamic: license-file

# komodor-agentops

Python SDK for AgentOps observability, including the worker runtime, with
optional extras for framework integrations (LangChain, Claude Agent SDK, ADK,
Agno, OpenAI Codex).

## Install

```bash
pip install komodor-agentops                # no gRPC OTLP exporter; the default HTTP/protobuf export works

# A worker (AgentOpsWorker): [server] or a framework extra, both of which include the gRPC exporter
pip install komodor-agentops[server]

# gRPC OTLP export on its own: [grpc], included in [server], every framework extra and [all]
pip install komodor-agentops[grpc]

# With framework adapters
pip install komodor-agentops[langchain]
pip install komodor-agentops[claude-code]
pip install komodor-agentops[adk]
pip install komodor-agentops[agno]
pip install komodor-agentops[codex]
pip install komodor-agentops[all]           # Everything
```

## Quick Start

### @observe() decorator

Wrap functions to emit span events automatically:

```python
from komodor_agentops import observe

@observe(name="summarize", as_type="llm")
async def summarize(text: str) -> str:
    ...
```

### AgentOps client (lightweight event buffer)

```python
from komodor_agentops import AgentOps

client = AgentOps(agent_id="my-agent", endpoint="http://localhost:8000")
await client.log("Processing started", run_id="run_1")
await client.flush()
```

### AgentOpsWorker — the whole of a worker's `main()`

A worker takes runs and returns results. It serves no HTTP and needs no inbound network access: it
connects out to the control plane, is told when work is available, and claims it.

```python
from pathlib import Path

from komodor_agentops import AgentOpsWorker, AgentSpec, Run

spec = AgentSpec.from_dir(
    Path(__file__).parent,
    agent_card={"skills": [{"id": "search", "name": "search"}]},
)

async def on_run(run: Run) -> dict:
    return {"answer": f"handled {run.input.get('prompt', '')}"}

def main() -> None:
    AgentOpsWorker(agent=spec, on_run=on_run).run()
```

`run.input` is the payload the run was created with; the dict you return becomes the run's output.
Raise to fail the run — that is `on_run`'s only failure channel, and the error is recorded on the run.

**No host or port.** Nothing dials your worker, so there is nothing to bind. A deployment needs egress
to the control plane and no Service, Ingress or open port; the customer namespace chart denies inbound
traffic by default.

**A worker built against `komodor-agentops` 0.1.x may instead be using `run_worker(agent, handler)` with a
handler taking an `A2AMessage` and returning an `A2ATask`, served on a port.** That runtime is gone: it
served an A2A app nothing dials any more. Move the handler to `on_run=` — it receives a `Run` and returns a
mapping — and construct `AgentOpsWorker` from the package root as above. `Run.input` is the whole payload
the message's parts used to carry, and the answer's human-readable half is the reserved `text` key rather
than an artifact.

The standard AgentOps agent layout is:

```text
my_agent/
  agent-spec.yaml
  agent.md
  worker.py
  skills/
    triage.md
    rca/SKILL.md
```

`AgentSpec.from_dir(Path(__file__).parent, ...)` requires `agent-spec.yaml`, then loads `agent.md` and `skills/` automatically. The worker registers loaded skills during heartbeat, and SDK-owned LLM adapters can prepend the agent context at invocation time.

```yaml
schema_version: 1
agent_id: my-agent
name: My Agent
description: Does useful work.
owner: AgentOps
repo: https://github.com/komodorio/agentops
source_path: packages/workers/my_agent
labels:
  category: example
```

`agent-spec.yaml` can also declare `triggers` — synced to the control plane on heartbeat and shown on the Fleet → Triggers surface. Supported types are `schedule` (cron), `webhook` (inbound HTTP endpoint), and `slack_channel` (subscribe the agent to Slack channels by NAME, not ID — the control plane materialises a routing rule per channel on heartbeat and dispatches matching messages; the agent is invoked when @mentioned in one of those channels):

```yaml
triggers:
  - id: incidents-sub
    type: slack_channel
    name: Incident channels
    channels:
      - "#incidents" # normalized to "incidents" — lowercase, no "#"
      - alerts
```

To make a worker available in the AgentOps Chat UI, advertise chat capability on its agent card:

```python
spec = AgentSpec(
    agent_id="my-chat-agent",
    agent_card={
        "name": "My Chat Agent",
        "capabilities": {"chat": True, "streaming": True},
    },
)
```

A chat run arrives like any other run: `run.input` carries `messages` (the conversation history), `model`,
and `prompt` (the latest user text). There are no A2A message parts to unpack — the control plane creates a
run and your worker claims it, so a chat handler reads the same `run.input` dict as every other handler.

To stream the answer as it is produced rather than returning it whole, emit it through the ambient client;
the control plane relays each new piece of the run's answer text to the browser as it appears.

## Report runs from your own code (observe-only agents)

An observe-only agent keeps running where it runs today. AgentOps never sends it work, configuration or
secrets; the agent reports each run it finishes, and AgentOps grades, reviews and costs it like any other.
(This is unrelated to the authorization "observe-only" shadow mode.)

```bash
pip install komodor-agentops   # plus the extra for your framework; no gRPC is needed
```

| Variable | Meaning |
|---|---|
| `AGENTOPS_URL` | The control plane. Unset means `http://localhost:8123`, and the client warns once. |
| `AGENTOPS_WORKER_TOKEN` | The agent's token. |
| `AGENTOPS_AGENT_ID` | The agent's slug. |
| `AGENTOPS_VERSION` | Optional. The agent version stored on each run. Falls back to `AGENTOPS_COMMIT_HASH`, then to no version. |
| `AGENTOPS_WORKER_ID` | Optional. Pin it in jobs and serverless so repeat invocations reuse one worker row instead of creating one each time. Each new process still registers once. |

The values can also be passed to `ObserveOnlyClient(url=, token=, agent_id=, version=)`. With a token or
slug missing, the client logs one warning and reports nothing; your code still runs.

```python
from komodor_agentops import ObserveOnlyClient, observe

client = ObserveOnlyClient()

@observe(name="answer")
def answer(question: str) -> str:
    ...

with client.run(input={"question": q}, name="support-answer") as run:   # or: async with
    run.set_output({"answer": answer(q)})

client.flush()   # at the end of each serverless handler
```

Each `client.run(...)` block is one run. `input` and `set_output` take a mapping; anything else is wrapped as
`{"input": value}` or `{"output": value}`, and a run that never calls `set_output` completes with `{}`. An
exception, `CancelledError` or `KeyboardInterrupt` inside the block reports the run as failed with the
message redacted, and is re-raised unchanged. `metadata=` is stored on the run.

**The wrapped call never waits on AgentOps and never sees its errors.** A background thread sends the
run's frames. If the control plane is unreachable the frames are buffered (up to 64 MiB, oldest events
dropped first) and sent when it answers, and a frame the control plane keeps rejecting is dropped with a
warning so it cannot block later runs. If the dropped frame is the run's result, the run is reported failed
instead. Bytes in an output are sent as base64, and a value no encoder can carry is sent as its `repr`. A run
reported after an outage shows the time it arrived as its start, so its duration reads short. In a long-lived process the client flushes when the interpreter exits;
in serverless, where it does not, call `client.flush()` (or `await asyncio.to_thread(client.flush)`) before
the handler returns. `client.close()` flushes and stops the thread. A `fork` gives the child a clean client.
Throughput is about 6 to 7 runs per second per process. A `410` from the control plane means the agent is
archived: the client logs one error, stops reporting and drops its queue, and `flush()` returns `False`.

Do not run an `AgentOpsWorker` in the same process: both read the same event buffer.

Per framework, inside the `run` block. For the Claude Agent SDK, drive the prompt with `run_agent_query`, not
`claude_agent_sdk.query`: it records each model turn (its text, the tools it chose, its tokens), reports cost
while the run is going, and waits for your MCP servers to connect before sending the prompt. The hooks alone
record tool calls only. With `resume=` the run's cost repeats the session's totals, so use a new session
per run for an exact cost.

With `mcp_servers` set, `run_agent_query` waits for them before it sends the prompt, then fails the run (`McpServersUnavailable`, prompt never sent) if none of them connects within 60 seconds; servers that settle as `failed` or `needs-auth` end the wait early. Set `AGENTOPS_MCP_CONNECT_TIMEOUT_SECONDS` to change the limit.

```python
# Claude Agent SDK
from claude_agent_sdk import ClaudeAgentOptions
from komodor_agentops.adapters.claude_code import agent_ops_hooks_for_run, run_agent_query, usage_from_result_message
from komodor_agentops.core.usage import record_usage

async with client.run(input={"prompt": prompt}) as run:
    options = ClaudeAgentOptions(hooks=agent_ops_hooks_for_run(run.run_id))  # plus your own options
    answer, result = await run_agent_query(prompt, options)
    record_usage(usage_from_result_message(result))
    run.set_output({"answer": answer})
```

```python
# LangChain
from komodor_agentops.adapters.langchain import ContextCallbackHandler

async with client.run(input={"q": q}) as run:
    run.set_output({"answer": await chain.ainvoke(q, config={"callbacks": [ContextCallbackHandler()]})})

# Agno
from komodor_agentops.adapters.agno import record_agno_run

with client.run(input={"q": q}) as run:
    result = agent.run(q)
    record_agno_run(result, model="gpt-4o")
    run.set_output({"answer": result.content})

# OpenAI Codex: a new recorder per run
from komodor_agentops.adapters.codex import CodexRecorder

async with client.run(input={"q": q}) as run:
    recorder = CodexRecorder(model="gpt-5-codex")
    async for notification in turn_notifications:
        recorder.observe(notification)
    await recorder.finish()
    if recorder.turn_error:
        raise RuntimeError(recorder.turn_error)
    run.set_output({"answer": final_text})

# Google ADK: one plugin per Runner, shared by sequential and concurrent runs
from komodor_agentops.adapters.adk import AgentOpsRecorderPlugin

runner = Runner(app=App(name="support", root_agent=agent, plugins=[AgentOpsRecorderPlugin()]), session_service=sessions)
async with client.run(input={"q": q}) as run:
    async for event in runner.run_async(user_id=user, session_id=session, new_message=message):
        ...
```

The Codex recipe raises the turn's error as a plain `RuntimeError`, so the failed run has no failure category;
call `run.set_failure(...)` for one.

### Run an experiment's saved inputs

When your coding agent drives an experiment on an observe-only agent, AgentOps never runs the dataset: it hands your
agent the saved inputs, and you run each one on the deployed version and report it as a tagged run.

```python
experiment_id, round = "exp_...", 1   # from the coding agent's next action

client.run_saved_inputs(experiment_id, round, my_agent)   # my_agent(saved.input) -> output
# call the coding agent's `next` here
```

`run_saved_inputs` fetches the earliest open pass, runs `handler(saved.input)` for each input inside
`client.run(saved_input=...)`, reports the handler's return value as the run's output, and fetches again until nothing
is left. It returns the number of inputs it ran, failed ones included. It never calls `next`. The handler is sync: an
async agent passes `lambda i: asyncio.run(my_agent(i))`. It needs SDK 0.7.2 or later.

On 0.7.1 or earlier write the loop yourself:

```python
while batch := client.saved_inputs(experiment_id, round):
    for saved in batch:
        with client.run(saved_input=saved) as run:   # the input defaults to the saved input
            run.set_output(my_agent(saved.input))
```

- A handler that raises is reported as a failed run and the loop moves on to the next input; nothing is re-run by the
  helper. An input whose tag is refused is logged and skipped (it gets one more try if the control plane serves it again).
  When a fetch serves only inputs the helper already tried, it logs their ids and returns: call `next` and read the
  experiment's status.
- `saved_inputs` returns the earliest open pass, and an empty list once none is open (the round is paused, over, or
  fully taken). It raises `SavedInputsError` when the control plane has no saved inputs for this agent at that round: the
  answer is the same whether the experiment is another agent's, another account's, or unknown.
- `run(saved_input=...)` sends its tag to the control plane before your code runs. A refusal (a different agent's input,
  an input another run already took, a run that carries no version or another version than the round's, or a guardrail
  that refused the input) raises `SavedInputsError` with the control plane's reason, and your body does not run, so no
  tool has had its effect. Deploy the version the round measures, then run with it: `next` and the round's status name it. The tag is never dropped: a run that cannot be tagged is not reported.
- The tools run live, with their real effects. Close any path you do not want the saved inputs to take.
- Call the coding agent's `next` when the helper returns: a tagged run counts as the agent being there, and `next`
  tells the experiment what happened.
- A client that stops reporting mid-run leaves an input that AgentOps re-runs once. A provider error (auth, billing,
  rate limit) is reported with its category; pass `run.set_failure("provider_rate_limit")` for one the SDK does not
  recognise.
- Needs a control plane that serves the `saved_inputs_request` frame; an older one answers 404, and the call raises.

## Event Hooks — rewriting or withholding telemetry before it leaves

Subclass `AgentOpsHook` and pass instances to the worker. Each callback may return the event unchanged,
return a modified one, or return `None` to **drop it** — so a tool payload carrying customer data can be
rewritten or withheld, and nothing downstream sees the original. `before_flush` does the same for a whole
batch; `after_flush` reports what was sent.

Every event this worker records crosses one place on its way out, so a hook sees all of it — including the
spans the adapters record ambiently, which never pass through your code.

```python
from komodor_agentops import AgentOpsWorker
from komodor_agentops.core.events import AgentOpsEvent
from komodor_agentops.core.hooks import AgentOpsHook


class RedactToolInput(AgentOpsHook):
    async def before_tool(self, event):
        return AgentOpsEvent(**{**vars(event), "payload": {"input": "[redacted]"}})


AgentOpsWorker(agent=spec, on_run=on_run, hooks=[RedactToolInput()]).run()
```

A hook that raises is logged and its event passes through unchanged, so a buggy rule cannot cost a run its
whole transcript. Pass `strict_hooks=True` to invert that: for a hook whose job is to *withhold* data,
passing the event through on failure ships exactly what it existed to remove, so the failure should
propagate instead.

## Framework Adapters

### LangChain

Spans for each chain, model and tool call, nested under the run's own span. It needs no client: the
events go to the ambient buffer the worker's flush cycle already drains, so it only produces spans
inside a run scope.

```python
from komodor_agentops.adapters.langchain import ContextCallbackHandler

chain.invoke(input, config={"callbacks": [ContextCallbackHandler()]})
```

### Claude Code

SDK hooks for `claude-agent-sdk`:

```python
from komodor_agentops.adapters.claude_code.sdk_hooks import agent_ops_hooks_for_run

hooks = agent_ops_hooks_for_run("run_1")
```

### Agno

`record_agno_run(result, model=...)` records an Agno run's tool calls, member runs and token usage on
the current run, and works in a worker or inside an observe-only `client.run(...)` block. It records them after
the run, so there are no model turns and no cost while the run is going.

### Google ADK

`AgentOpsRecorderPlugin` records an ADK run's session, agent, model and tool spans. Pass it in the
`App` plugins; one plugin serves sequential and concurrent runs, each recorded under its own run.

### OpenAI Codex

A run handler for `openai-codex`, which bundles the `codex` CLI (about 320 MB of binaries in the
worker image). It runs each turn on a Codex thread in a `CODEX_HOME` the adapter owns, and maps Codex
tool calls to the Claude names (`Bash`, `Edit`, `Write`, `mcp__<server>__<tool>`), so the same action
rules, replay and trace views work. The model is `AGENTOPS_MODEL`; the key is `OPENAI_API_KEY`, or
set `AGENTOPS_CODEX_MODEL_PROVIDER=amazon-bedrock-runtime` for OpenAI models on Amazon Bedrock.

```python
from komodor_agentops import AgentOpsWorker, AgentSpec
from komodor_agentops.adapters.codex import create_codex_run_handler

spec = AgentSpec.from_dir(agent_dir)
on_run = create_codex_run_handler(spec, developer_instructions=instructions, mcp_servers=mcp_servers)
AgentOpsWorker(agent=spec, on_run=on_run).run()
```

The handler has the same seams as the Claude Code handler: `validate`, `build_prompt`,
`build_options` (returns a `CodexRunOptions` per run) and `finalize` (gets a `CodexRunResult`).
The adapter applies its hardening after `build_options`. `builtin_tools` limits the built-in tools
(`Bash`, `Edit`, `Write`, `view_image`); `allowed_tools` limits only the MCP tools.

The defaults, the parity with the Claude Code adapter and the known gaps:
[`docs/reference/codex-adapter.md`](../../docs/reference/codex-adapter.md).

## Architecture

```
komodor-agentops
  agentops-rpc, agentops-otel (wire types + OTel bootstrap, HTTP/protobuf exporter; no gRPC)
  httpx, pydantic, pydantic-settings, croniter, pyyaml, python-frontmatter
    |
    +-- [langchain]   -> langchain-core, [grpc]
    +-- [claude-code] -> claude-agent-sdk, [grpc]
    +-- [adk]         -> google-adk, [grpc]
    +-- [agno]        -> agno, anthropic, [grpc]
    +-- [codex]       -> openai-codex (pins openai-codex-cli-bin, the codex binary), [grpc]
    +-- [server]      -> [grpc] (gRPC OTLP exporter, for AgentOpsWorker)
    +-- [grpc]        -> agentops-otel[grpc] (opentelemetry-exporter-otlp-proto-grpc)
```

## Package Structure

```
src/komodor_agentops/
  __init__.py       # Public API — the root is the API; submodule paths are internal
  worker_runtime.py # AgentOpsWorker: connect, register, claim, run, report
  worker_client.py  # The worker protocol, and the run scope
  messaging.py      # The transport's composition root (downlink + uplink)
  client.py         # Event buffer + flush
  py.typed          # PEP 561 marker
  transport/        # The byte-level connection (SSE, reconnect)
  bus/              # Frames: the envelope, the router, the uplink
  machinery/        # Delivery: batching, retry, sequencing
  core/             # Context, events, secrets, types, @observe
  worker/           # Run contract, liveness, local runner, log forwarding
  adapters/         # Claude Code, Codex, ADK, Agno, LangChain, nanobot
```

## AWS credentials for a worker

An AWS-touching worker needs one variable on the process it runs the AWS CLI or an AWS SDK in:

```python
from komodor_agentops.worker.aws_credentials import serve_credentials

async def fetch():
    # `.model_dump()`: the responder serves AWS's own container-credentials JSON, so it takes that
    # dict rather than the reply model — the field names are already AWS's, so this is a shape
    # change and not a mapping.
    session = await client.aws_credentials()
    return session.model_dump() if session is not None else None

async with serve_credentials(fetch) as creds:
    env = {**scrubbed_env, "AWS_CONTAINER_CREDENTIALS_FULL_URI": creds.uri}
```

The SDK does the rest — fetch, cache, refresh — because that variable is AWS's own
container-credentials contract. Nothing else is needed: no keys in the environment, no per-worker
credential code, and no AWS identity on the pod.

`serve_credentials` asks lazily, on the first fetch rather than on entry, so a worker that never
touches AWS costs nothing. `client.aws_credentials()` returns `None` when the account has no AWS (IAM
role) connection or the worker has no run in flight; that becomes a 503 on the endpoint rather than an
exception, because both are ordinary configurations. A *retryable* failure — a throttled STS — raises
instead, and the responder answers 503 while keeping any session it still holds: `None` means "there is
nothing here", a raise means "ask again".

**The one thing that bites:** the variable starts with `AWS_`, so any env-blanking helper wipes it. If
a worker scrubs ambient AWS variables before launching its subprocess — `aws_investigator` does, via
`_scrub_aws_env` — set the URI *after* the scrub, not before.
