Metadata-Version: 2.4
Name: komodor-agentops
Version: 0.6.5
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.6.5
Requires-Dist: agentops-rpc~=0.6.5
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. 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.

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

Per framework, inside the `run` block:

```python
# Claude Agent SDK
from komodor_agentops.adapters.claude_code import agent_ops_hooks_for_run, 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))
    async for message in query(prompt=prompt, options=options):
        if isinstance(message, ResultMessage):
            record_usage(usage_from_result_message(message))
            run.set_output({"answer": message.result})

# 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()

# Google ADK: one plugin per Runner is fine for sequential runs; use one plugin per run for 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):
        ...
```

## 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.

### Google ADK

`AgentOpsRecorderPlugin` records an ADK run's session, agent, model and tool spans. Pass it in the
`App` plugins; a plugin reused for a different run starts that run clean.

### 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.
