Metadata-Version: 2.4
Name: asrielnetworks-sdk
Version: 0.1.1
Summary: AsrielNetworks AI XDR SDK - monitor, replay, detect and benchmark any LLM-powered agent.
Author: AsrielNetworks
License: Apache-2.0
Project-URL: Homepage, https://asrielnetworks.vercel.app
Project-URL: Download, https://asrielnetworks.vercel.app/download
Keywords: ai,xdr,llm,observability,security,agents,monitoring
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Topic :: Security
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: httpx
Requires-Dist: httpx>=0.24; extra == "httpx"
Provides-Extra: requests
Requires-Dist: requests>=2.28; extra == "requests"
Provides-Extra: aiohttp
Requires-Dist: aiohttp>=3.8; extra == "aiohttp"
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.20; extra == "otel"
Requires-Dist: opentelemetry-sdk>=1.20; extra == "otel"
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.1; extra == "langchain"
Provides-Extra: all
Requires-Dist: httpx>=0.24; extra == "all"
Requires-Dist: requests>=2.28; extra == "all"
Requires-Dist: aiohttp>=3.8; extra == "all"
Requires-Dist: opentelemetry-api>=1.20; extra == "all"
Requires-Dist: opentelemetry-sdk>=1.20; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Dynamic: license-file

# asrielnetworks-sdk

Python SDK that connects **any AI agent** to the AsrielNetworks AI-XDR platform: session replay, AI incidents,
Connect AI (fleet control), Knowledge/RAG observability and benchmarking — for **any model provider**, including ones
nobody has heard of yet.

* **Zero runtime dependencies.** Pure standard library (urllib, gzip, hmac, threading, contextvars). Optional extras
  only for the HTTP libraries / frameworks you already use.
* **Provider-agnostic by construction.** A universal normaliser turns dicts, JSON, SSE/NDJSON bytes, pydantic models,
  dataclasses, protobufs and arbitrary SDK objects into one `llm.call` record. Known shapes (OpenAI chat/completions/
  responses, Anthropic, Gemini, Bedrock, Ollama, Cohere, HF TGI, Mistral/Groq/OpenRouter-style) are recognised; unknown
  shapes fall back to deep heuristics (text, token usage, tool calls, finish reason) — nothing is dropped.
* **Six ways to capture, no vendor lock-in:** explicit `record_llm`, spans, decorators, the `wrap()` proxy for any SDK
  object, zero-code HTTP interception (httpx / httpx2 / requests / aiohttp + SDK hooks), and a language-agnostic reverse-proxy
  sidecar. LangChain and OpenTelemetry bridges included.
* **Security first.** Secrets/PII are redacted before anything leaves the process; hash-only mode ships no content at
  all; requests can be HMAC-signed; local detectors map to OWASP LLM Top-10 + MITRE ATLAS; an incident engine dedups and
  escalates; policies from the SOC (pause / kill / block tool or model) are enforced in-process and at the network edge.
* **Never breaks the agent.** Bounded queue, background flush thread, batching, gzip, retries with jitter, disk spool
  for offline replay. Capture failures are swallowed (visible with `debug=True`).

```
pip install asrielnetworks-sdk            # core, no deps
pip install "asrielnetworks-sdk[all]"     # httpx, requests, aiohttp, otel (langchain: [langchain])
```

## 60-second start

```python
import asrielnetworks as siq

siq.init(api_key="siq_…", endpoint="https://<your AsrielNetworks API host>",
         agent_name="support-bot", environment="prod", auto_instrument=True)

with siq.session(user_id="u42") as s:
    s.message("user", question)
    answer = openai_client.chat.completions.create(model="gpt-4o-mini", messages=[...])  # captured, normalised, scanned
    s.message("assistant", answer.choices[0].message.content)
```

Environment variables work too (`ASRIELNETWORKS_API_KEY`, `ASRIELNETWORKS_ENDPOINT`, `ASRIELNETWORKS_AGENT_NAME`, … one per
`Config` field). The endpoint is required: without it the SDK warns once and keeps events in its local spool.
Check connectivity with `asrielnetworks check`.

## Any LLM, even an unknown one

```python
# 1. Explicit — hand over whatever your vendor returns
ev_id, findings = siq.record_llm(request_obj, response_obj, url="https://llm.acme.internal/v2/infer")

# 2. Stream of anything
with siq.llm(model="acme-7b", provider="acme") as span:
    span.set_request(payload)
    for chunk in vendor.stream(payload):
        span.feed(chunk)            # dicts, SSE lines, bytes, plain strings …

# 3. Decorators
@siq.llm_call(model="acme-7b")
def ask(**payload): return vendor.post(payload)

# 4. Proxy an entire SDK object you know nothing about
llm = siq.wrap(AcmeClient(api_key), provider="acme")
llm.chat.create(...)                # recorded; sync/async/streams/context-managers all handled

# 5. Zero code — every HTTP call that looks like a model call is captured
siq.auto_instrument()               # or siq.init(auto_instrument=True) / ASRIELNETWORKS_AUTO_INSTRUMENT=1
siq.init(llm_url_patterns=[r"llm\.acme\.internal"])   # teach it your private endpoint

# 6. No Python at all
#   $ asrielnetworks proxy --upstream https://llm.acme.internal --listen 127.0.0.1:8787
#   then point the agent (any language) at http://127.0.0.1:8787
```

## What gets detected locally

| detector | OWASP / ATLAS | example |
|---|---|---|
| prompt_injection | LLM01 / AML.T0051 | "ignore all previous instructions", role-tag smuggling, indirect injection in retrieved docs |
| system_prompt_leak | LLM07 / AML.T0056 | output repeats the system prompt |
| secret_leak | LLM02 / AML.T0057 | API keys, JWTs, private keys, cards (Luhn), emails, phones … in output or tool results |
| tool_abuse | LLM06 / AML.T0053 | `rm -rf`, `DROP TABLE`, path traversal, runaway tool loops |
| cost_anomaly | LLM10 / AML.T0034 | oversized prompts / outputs |
| groundedness | LLM09 / AML.T0062 | answer not supported by retrieved context |

Findings ride along on the event, are emitted as `finding` events, are promoted to `incident`s (deduplicated per
fingerprint, risk-scored), and can **block** the agent when the policy says so (`enforce=True`, `@tool_call`,
`siq.guard(...)`, or the proxy returning 403). Add your own with `asrielnetworks.Detector`.

## Connect AI (fleet control)

Agents register a learned manifest (models + tools seen), heartbeat, and long-poll operator commands:
`pause`, `resume`, `kill`, `block_tool`, `block_model`, `set_policy`, `set_sample_rate`, `capture_content`, `flush`,
`info`, `ping` — plus anything you register with `client.connect.on_command`. Policy changes take effect immediately.

## Knowledge (RAG) and Benchmarks

```python
c = siq.get_client()
retriever = c.knowledge.wrap_retriever(my_retriever, index="faiss")       # every lookup becomes a `retrieval` event
siq.record_retrieval(q, docs, answer=final_answer)                        # groundedness score + hallucination finding
c.knowledge.ingest(docs, collection="handbook"); c.knowledge.query("refunds")

c.benchmark.run(agent_fn, suite="security-basics", submit=True)          # injections, jailbreaks, refusals, sanity
```

## Wiring it to the platform

The SDK's HTTP contract is small and fully documented in **`docs/SERVER_CONTRACT.md`** (endpoints, headers, HMAC,
retry semantics, policy/command objects) and **`docs/EVENT_SCHEMA.md`** (every event type). `asrielnetworks mock` is a
stdlib reference server implementing the whole contract — run it, point `ASRIELNETWORKS_ENDPOINT` at it, and watch
events, registrations, acks and benchmark runs arrive while you build the real backend.

```
asrielnetworks mock --log --commands examples/operator_commands.jsonl      # terminal 1
ASRIELNETWORKS_ENDPOINT=http://127.0.0.1:8788 ASRIELNETWORKS_API_KEY=dev python examples/01_quickstart.py   # terminal 2
```

## CLI

```
asrielnetworks info | check | detect | redact | normalize | proxy | replay | mock | bench | schema
```

## Layout

```
src/asrielnetworks/
  __init__.py       init()/get_client() + module-level shortcuts
  client.py         Client, LLMSpan, record_* , decorators, wrap()
  normalize.py      universal request/response/stream normaliser + provider detection
  redact.py         secrets/PII scrubbing
  detectors/        detector framework + built-ins (OWASP/ATLAS mapped)
  incidents.py      finding → incident promotion, dedup, risk score
  policy.py         Policy, PolicyViolation, AgentKilled
  tracing.py        Session / Span (contextvars)
  transport.py      queue, batching, gzip, HMAC, retries, disk spool
  connect.py        Connect AI: register, heartbeat, commands, policy
  knowledge.py      RAG helpers + knowledge API
  benchmark.py      suites, scorers, runner
  costs.py          price table + cost estimation
  interceptors/     wrap() proxy, HTTP interception, auto_instrument + SDK hooks
  proxy.py          reverse-proxy sidecar
  integrations/     LangChain callback handler
  otel.py           OpenTelemetry bridge
  cli.py            `asrielnetworks` command (incl. mock backend)
docs/               SERVER_CONTRACT.md, EVENT_SCHEMA.md, API.md
examples/           runnable samples for every feature
tests/              pytest suite (no network; fake LLM server included)
```

## Development

```
pip install -e ".[dev,httpx,requests,aiohttp]"
pytest -q
```

Apache-2.0.
