Metadata-Version: 2.5
Name: logicgaze
Version: 1.10.0
Summary: LogicGaze SDK — AI-native observability for tracing, evaluating, and monitoring production LLM applications. Instrument OpenAI, Anthropic, and any LLM with one line of code.
Project-URL: Homepage, https://github.com/VikneeshVG/logicgaze
Project-URL: Repository, https://github.com/VikneeshVG/logicgaze
Project-URL: Issues, https://github.com/VikneeshVG/logicgaze/issues
Author-email: Vikneesh VG <vikneeshwaran.k@ventragate.com>
License: MIT
License-File: LICENSE
Keywords: ai,anthropic,cohere,evaluation,google,langchain,litellm,llm,logicgaze,observability,openai,tracing
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
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 :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Requires-Dist: httpx>=0.26.0
Provides-Extra: agents
Requires-Dist: openai-agents>=0.0.7; extra == 'agents'
Provides-Extra: all
Requires-Dist: click>=8.0.0; extra == 'all'
Requires-Dist: cohere>=5.0.0; extra == 'all'
Requires-Dist: docker>=6.0.0; extra == 'all'
Requires-Dist: google-genai>=1.0.0; extra == 'all'
Requires-Dist: groq>=0.9.0; extra == 'all'
Requires-Dist: langchain-core>=0.1.0; extra == 'all'
Requires-Dist: langchain>=0.1.0; extra == 'all'
Requires-Dist: litellm>=1.0.0; extra == 'all'
Requires-Dist: mistralai>=1.0.0; extra == 'all'
Requires-Dist: psutil>=5.9.0; extra == 'all'
Requires-Dist: pyyaml>=6.0; extra == 'all'
Requires-Dist: schedule>=1.2.0; extra == 'all'
Requires-Dist: tomli>=2.0.0; extra == 'all'
Provides-Extra: cohere
Requires-Dist: cohere>=5.0.0; extra == 'cohere'
Provides-Extra: dev
Requires-Dist: build>=1.0.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: respx>=0.20.0; extra == 'dev'
Requires-Dist: twine>=4.0.0; extra == 'dev'
Provides-Extra: google
Requires-Dist: google-genai>=1.0.0; extra == 'google'
Provides-Extra: groq
Requires-Dist: groq>=0.9.0; extra == 'groq'
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.1.0; extra == 'langchain'
Requires-Dist: langchain>=0.1.0; extra == 'langchain'
Provides-Extra: litellm
Requires-Dist: litellm>=1.0.0; extra == 'litellm'
Provides-Extra: mistral
Requires-Dist: mistralai>=1.0.0; extra == 'mistral'
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.25.0; extra == 'otel'
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.25.0; extra == 'otel'
Requires-Dist: opentelemetry-sdk>=1.25.0; extra == 'otel'
Provides-Extra: security
Requires-Dist: click>=8.0.0; extra == 'security'
Requires-Dist: psutil>=5.9.0; extra == 'security'
Requires-Dist: pyyaml>=6.0; extra == 'security'
Requires-Dist: schedule>=1.2.0; extra == 'security'
Requires-Dist: tomli>=2.0.0; extra == 'security'
Provides-Extra: security-containers
Requires-Dist: click>=8.0.0; extra == 'security-containers'
Requires-Dist: docker>=6.0.0; extra == 'security-containers'
Requires-Dist: psutil>=5.9.0; extra == 'security-containers'
Requires-Dist: pyyaml>=6.0; extra == 'security-containers'
Requires-Dist: schedule>=1.2.0; extra == 'security-containers'
Requires-Dist: tomli>=2.0.0; extra == 'security-containers'
Description-Content-Type: text/markdown

# logicgaze

[![PyPI version](https://img.shields.io/pypi/v/logicgaze.svg)](https://pypi.org/project/logicgaze/)
[![Python 3.9+](https://img.shields.io/pypi/pyversions/logicgaze.svg)](https://pypi.org/project/logicgaze/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**LogicGaze SDK** — AI-native observability for production LLM applications.

Instrument OpenAI, Anthropic, and any LLM with one line of code. Every call is automatically traced, cost-attributed, and visible in the [LogicGaze](https://logicgaze.com) dashboard.

## Features

- **Zero-config tracing** — wrap your existing client (or use `init(auto_instrument=True)`), get full observability instantly
- **Never in your request path** — wrapped clients call the provider directly with your own keys and return the native response; spans are sent in the background
- **Streaming instrumentation** — token usage and time-to-first-token captured even for `stream=True` calls
- **Cost tracking** — token-level cost attribution per model, provider, and session
- **Distributed traces** — full span trees across LLM calls, tool calls, agents, and retrievals
- **Scores & feedback** — `log_score()` / `log_feedback()` attach evals and user signals to traces
- **Datasets** — build eval datasets in code, or copy production traces into test cases
- **Prompt management** — versioned `{{variable}}` templates with a client-side TTL cache
- **Masking** — redact or transform what LogicGaze stores (`mask`, `hide_inputs`, `hide_outputs`)
- **OpenAI Agents SDK** — `instrument_openai_agents()` traces agent runs automatically
- **Guardrails** — PII detection, prompt injection detection, harmful content filtering
- **LLM-as-Judge** — async evaluation scoring (faithfulness, relevance, coherence, hallucination)
- **OpenTelemetry ingest** — the LogicGaze backend accepts OTLP/HTTP JSON at `/api/v1/otel/v1/traces` (server-side ingest; this SDK does not emit OTel itself)

## Installation

```bash
pip install logicgaze
```

## Quick Start

### 1. Initialize once at startup

```python
import logicgaze

logicgaze.init(
    api_key="lgz_...",               # LogicGaze API key
    base_url="https://your-logicgaze-backend.com",
)
```

Set `LOGICGAZE_API_KEY` in your environment to avoid passing `api_key` explicitly.

### 2. Wrap your AI client

**OpenAI**
```python
from openai import OpenAI
import logicgaze

logicgaze.init(api_key="lgz_...")
client = logicgaze.wrap_openai(OpenAI())

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}],
)
print(response.choices[0].message.content)
```

**Anthropic**
```python
from anthropic import Anthropic
import logicgaze

logicgaze.init(api_key="lgz_...")
client = logicgaze.wrap_anthropic(Anthropic())

response = client.messages.create(
    model="claude-opus-4-6",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello!"}],
)
print(response.content[0].text)
```

**Or patch constructors automatically (opt-in)**
```python
import logicgaze
logicgaze.init(api_key="lgz_...", auto_instrument=True)

import openai
client = openai.OpenAI()   # already wrapped — every new client is traced

logicgaze.uninstrument()   # restore the original constructors at any time
```

`auto_instrument=True` patches `openai.OpenAI` / `openai.AsyncOpenAI` and
`anthropic.Anthropic` / `anthropic.AsyncAnthropic`. It is idempotent, fully
try/except-guarded, and reversible with `logicgaze.uninstrument()`. Clients
keep their own `base_url` and key, so OpenAI-compatible servers (vLLM,
Together, Azure) keep working.

### Routing: direct (default) or gateway

By default every wrapped call goes **directly** to the provider using your
client, key, `base_url` and parameters, and you get the provider's own
response object back. LogicGaze records the span in a background queue, so an
outage or slowdown on the LogicGaze side never affects your LLM calls.

Choose `gateway` routing when you want LogicGaze's gateway in the path
(server-side guardrails that can block a request, semantic caching, routing
policies, centrally managed provider keys):

```python
logicgaze.init(api_key="lgz_...", routing="gateway")   # all wrapped clients
client = logicgaze.wrap_openai(OpenAI(), mode="gateway")  # or per client
```

Also settable with `LOGICGAZE_ROUTING=gateway`. Groq and Mistral are always
traced directly. Gateway LLM calls are never retried after a timeout or 5xx
(the provider may already have run and billed the request); only HTTP 429 is
retried.

### 3. Group calls with `TraceContext`

```python
from logicgaze import TraceContext, wrap_openai
from openai import OpenAI

client = wrap_openai(OpenAI())

with TraceContext(session_id="sess-abc", user_id="user-42", service_name="chat-api"):
    # All calls inside share the same trace in the dashboard
    client.chat.completions.create(model="gpt-4o", messages=[...])
    client.chat.completions.create(model="gpt-4o", messages=[...])
```

### 4. Use `@traceable` on functions

```python
from logicgaze import traceable, wrap_openai
from openai import OpenAI

client = wrap_openai(OpenAI())

@traceable(session_id="sess-1", service_name="recommendation-engine")
def recommend(user_query: str):
    return client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": user_query}],
    )

# Async functions are fully supported
@traceable(service_name="summarizer")
async def summarize(text: str):
    return await client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": f"Summarize: {text}"}],
    )
```

### 5. Query traces programmatically

```python
from logicgaze import get_client

lg = get_client()

# List recent traces
traces = lg.list_traces(service_name="chat-api", page_size=20)

# Get a specific trace with all spans
trace = lg.get_trace("trace-uuid-here", include_spans=True)

# Dashboard overview (last 24 h)
overview = lg.get_dashboard(window_hours=24)
print(overview["total_requests"], overview["total_cost_usd"])

# Estimate cost before a call
estimate = lg.estimate_cost("openai", "gpt-4o", prompt_tokens=500, completion_tokens=200)
```

## Zero-code capture and sessions

One line traces every LLM call your app makes and groups each conversation into a session:

```python
import logicgaze; logicgaze.init(auto_instrument=True)
```

What it captures, with no other code changes:

- **LLM calls**: OpenAI and Anthropic SDK clients, and raw REST calls (`httpx` / `httpx2`) to Azure OpenAI, `api.openai.com` and `api.anthropic.com`, streamed or not. Add OpenAI-compatible hosts with `LOGICGAZE_CAPTURE_HOSTS=host1,host2`. Requests sent by the official SDKs are not double-counted.
- **Turns**: each incoming request to a FastAPI/Starlette, Flask or Django app that makes LLM calls becomes one trace. A `workflow` span holds the user's message and your app's reply, with the model calls nested under it. For any other WSGI app wrap it with `logicgaze.LogicGazeWSGIMiddleware(app)`.
- **Sessions**: the session id is taken, in this order, from `logicgaze.set_session(...)`, the `X-Session-Id` header, the request JSON (`session_id`), then the response (JSON or an SSE event carrying `session_id`). The user id follows the same rules with `user_id` / `X-User-Id`. IDs over 200 characters or with control characters are ignored.
- **Distributed traces**: an incoming W3C `traceparent` header puts the request in the caller's trace.
- **Reasoning**: provider reasoning fields (`reasoning_content`, Anthropic thinking blocks) and `thinking` / `reasoning` events in your app's own SSE stream are kept separately from the reply.
- **Guardrails**: in-process guardrail decisions are recorded as `guardrail` spans under the model call.

Set things explicitly when your app knows better:

```python
logicgaze.set_session(conversation.id, user_id=user.id, input=clean_question, output=final_answer)
```

### Settings

| Variable | Default | Effect |
|---|---|---|
| `LOGICGAZE_SESSION_SOURCES` | `explicit,header,body,response` | Where to look for the session id, in priority order |
| `LOGICGAZE_SESSION_FIELD` / `LOGICGAZE_USER_FIELD` | `session_id` / `user_id` | JSON keys to read |
| `LOGICGAZE_SESSION_HEADER` / `LOGICGAZE_USER_HEADER` | `x-session-id` / `x-user-id` | Headers to read |
| `LOGICGAZE_CAPTURE_BODY_LIMIT` | `262144` | Bytes of each request/response body to inspect |
| `LOGICGAZE_CAPTURE_IO` | `1` | `0` keeps sessions but records no request/response text |
| `LOGICGAZE_CAPTURE_CONTENT` | `1` | `0` records no prompts or replies anywhere |
| `LOGICGAZE_CAPTURE_REQUESTS` | `1` | `0` turns off request (turn) capture |
| `LOGICGAZE_CAPTURE_HTTP` | `1` | `0` turns off raw REST capture |
| `LOGICGAZE_INSTRUMENTS` / `LOGICGAZE_DISABLE_INSTRUMENTS` | all | Comma list of `openai`, `anthropic`, `httpx`, `asgi`, `wsgi` |

`init(instruments=[...], block_instruments=[...])` does the same in code. Capture never changes what your app receives, and is skipped while OpenTelemetry instrumentation is suppressed.

## OpenTelemetry mode

`logicgaze.init(auto_instrument=True, otel=True)` (or `LOGICGAZE_EXPORTER=otlp`, or passing `tracer_provider=`) emits every span as an OpenTelemetry span that follows the GenAI semantic conventions (`gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`, `gen_ai.conversation.id`, usage and reasoning parts) and exports it over OTLP to LogicGaze. LogicGaze spans then nest under your existing OTel spans and propagate W3C context. If you pass your own `tracer_provider`, LogicGaze adds its exporter to it. Install with `pip install "logicgaze[otel]"`.

## Streaming

Streamed calls are traced too — no code changes:

```python
stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write a haiku"}],
    stream=True,
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
```

- For OpenAI-protocol providers the SDK injects `stream_options={"include_usage": true}`
  automatically so the final chunk carries token usage (retried once without it if
  a provider rejects the parameter)
- For Anthropic, usage is aggregated from `message_start` / `message_delta` stream events
- The span records the full aggregated output, token usage, latency, and
  `time_to_first_token_ms` in metadata — submitted via the non-blocking background queue

## Scores & Feedback

```python
lg = logicgaze.get_client()

# data_type inferred: NUMERIC / CATEGORICAL / BOOLEAN
lg.log_score(trace_id, "relevance", 0.92)
lg.log_score(trace_id, "tone", string_value="formal")
lg.log_score(trace_id, "is_correct", True)
lg.log_score(trace_id, "faithfulness", 0.8, span_id=span_id, comment="one unsupported claim")

# End-user feedback
lg.log_feedback(trace_id, feedback_type="thumbs_up", score=1)
lg.log_feedback(trace_id, comment="Answer was outdated")

scores = lg.list_scores(trace_id=trace_id)
```

Async variants: `alog_score`, `alog_feedback`, `alist_scores`.

## Datasets

Turn production traces into test cases:

```python
dataset = lg.create_dataset("qa-regression", description="Golden QA test cases")

lg.add_dataset_item(dataset["id"], input={"question": "What is RAG?"},
                    expected_output={"answer": "..."})

lg.add_dataset_items(dataset["id"], [
    {"input": {"question": "q1"}, "expected_output": {"answer": "a1"}},
    {"input": {"question": "q2"}},
])  # per-item errors collected — one failure never aborts the rest

# Copy production traces into the dataset (input/output from each trace's first LLM span)
lg.add_traces_to_dataset(dataset["id"], trace_ids=["trace-uuid-1", "trace-uuid-2"])

items = lg.get_dataset_items(dataset["id"], page=1, page_size=50)
datasets = lg.list_datasets()
```

## Experiments

Run your code on every dataset item, score each answer, and compare with the dataset's baseline:

```python
from logicgaze import run_experiment, assert_experiment

def answer(item_input):
    return support_bot(item_input["question"])

def cites_a_source(item_input, output, expected):
    return "http" in output

run = run_experiment(
    "qa-regression",                      # dataset name or id
    answer,                               # sync or async; exceptions become failed items
    name="shorter system prompt",
    evaluators=[
        "exact_match",                    # also: contains_expected, similarity, json_match
        {"type": "judge", "template": "correctness", "threshold": 0.8},
        {"type": "evaluator", "id": "<saved evaluator id>"},
    ],
    scorers=[cites_a_source],             # local functions -> float, bool or {name: score}
    concurrency=8,
)
print(run.scores, run.url)

outcome = run.gate(max_regression=0.05)   # thresholds default to the evaluators' own
print(outcome.markdown)
```

Each item runs inside a `TraceContext`, so wrapped LLM calls show up as traces linked from the experiment. Judges run in LogicGaze with the provider keys saved in your workspace.

`assert_experiment(run, {"correctness": 0.8}, max_regression=0.05)` raises `ExperimentGateFailed` (an `AssertionError`) with the report as its message, so it fails a pytest test cleanly.

To have LogicGaze call a model or a saved prompt for every item instead of your code:

```python
from logicgaze import run_server_experiment

run = run_server_experiment("qa-regression", name="gpt-4o-mini, v7 prompt",
                            model="openai/gpt-4o-mini", system_prompt=open("prompts/qa.txt").read(),
                            evaluators=["correctness"])
```

### In CI

`logicgaze-experiment` runs a server experiment, waits, gates and exits `0` (passed), `1` (gate failed) or `2` (could not run):

```bash
logicgaze-experiment run --dataset qa-regression --model openai/gpt-4o-mini \
  --system-prompt-file prompts/qa.txt --evaluator correctness \
  --threshold correctness=0.8 --max-regression 0.05 --markdown-file report.md
```

The [GitHub Action](../../github-action/README.md) wraps this and comments the report on the pull request.

## Command line

```bash
logicgaze login --api-key lgz_...
logicgaze traces list --status error
logicgaze prompts promote support 7
logicgaze datasets push support-golden cases.jsonl
logicgaze experiment run --dataset support-golden --model openai/gpt-4o-mini --evaluator correctness
logicgaze mcp --client cursor          # MCP config (sign in with OAuth)
logicgaze otel claude-code             # send Claude Code sessions to LogicGaze; also: codex
logicgaze skill install                # skill for Claude Code and other agents
logicgaze skill push .claude/skills/release-notes   # submit your skill for scanning and approval
logicgaze skill pull release-notes                  # write the approved version to .claude/skills
logicgaze skill verify .claude/skills               # CI: exit 1 unless every skill is an approved version
logicgaze hook install claude-code --write          # enforce tool-call rules in Claude Code (also: cursor)
```

`logicgaze hook claude-code|cursor` is what the agent runs before each tool call. It sends the event to LogicGaze,
which applies your tool-call rules (scope a rule to an agent by listing `claude-code` or `cursor` under
`servers`). Denied and steered calls are refused with the rule's message, calls that need approval wait up to
`LOGICGAZE_HOOK_APPROVAL_WAIT` seconds (default 120), and every action is recorded with risk flags, the engineer
(git email), repository and `LOGICGAZE_TEAM`. If LogicGaze cannot be reached the hook stays out of the way; pass
`--fail-closed` to refuse instead.

## Prompt Management

```python
# Every create makes a new, immutable version; labels move to it
lg.create_prompt("welcome-email", "Hi {{name}}, welcome to {{product}}!",
                 labels=["staging"], commit_message="friendlier", config={"model": "gpt-4o"})

# Chat prompts are message lists; a placeholder message is filled from a list variable
lg.create_prompt("support", [
    {"role": "system", "content": "You help {{company}} customers."},
    {"role": "placeholder", "name": "history"},
    {"role": "user", "content": "{{question}}"},
], type="chat")

# Fetch with a client-side TTL cache (default 60s, stale-while-revalidate)
prompt = lg.get_prompt("welcome-email")                   # the "production" version, else the newest
prompt = lg.get_prompt("welcome-email", label="staging")  # by label ("latest" = newest)
prompt = lg.get_prompt("welcome-email", version=2)        # pinned
text = prompt.compile(name="Ada", product="LogicGaze")    # str for text prompts, message list for chat

# Promote or roll back: a label leaves the version that had it
lg.set_prompt_labels("welcome-email", 3, ["production"])

# Link calls to the version so they show under the prompt's Metrics tab
client = logicgaze.wrap_openai(OpenAI())
client.chat.completions.create(model="gpt-4o", messages=prompt.compile(question="Hi"), logicgaze_prompt=prompt)
```

Cache semantics: fresh entries are served with no network call; stale entries are
served immediately and refreshed in a background thread; if the refresh fails, the
stale prompt keeps being served — network errors never reach your code once a
prompt has been fetched at least once. Async: `aget_prompt`, `acreate_prompt`.

## Guardrails (in-process enforcement)

Turn on `guardrails=True` and the SDK enforces your workspace's guardrail
rules inside your process, on every wrapped client call (direct routing):

```python
import logicgaze
from logicgaze import GuardrailBlocked

logicgaze.init(api_key="lgz_...", guardrails=True)   # or LOGICGAZE_GUARDRAILS=1
client = logicgaze.wrap_openai(OpenAI())

try:
    client.chat.completions.create(model="gpt-4o-mini", messages=[...])
except GuardrailBlocked as exc:
    print(exc.rule_name, exc.direction)   # "input" → the provider was never called
```

- **Keyword and regex rules** check prompts and responses.
- **Promoted evaluator guardrails** check responses once the evaluator has been
  distilled (Evaluators → Promote to guardrail → Distill for real-time).
- `block` raises `GuardrailBlocked`; `redact` rewrites the text in the request
  or in the native response object; `warn`/`log` only record the outcome on
  the span.
- The policy is fetched once and refreshed every 30 seconds. Checks add well
  under 1 ms per call (p99 ≈ 0.4 ms for a 2,000-character response with four
  rules including a distilled judge). If the policy can't be fetched, the SDK
  keeps the last one it had and never fails your call because of LogicGaze.
- Streaming responses: prompts are checked before the call; streamed output is
  recorded but not blocked mid-stream.

The same rules run in the LogicGaze gateway when you use `routing="gateway"`,
and both paths make identical decisions.

## Build agents (LogicGaze Agents SDK)

`create_agent` builds an agent that is traced and governed by LogicGaze on every step, with no extra wiring:
each run is one trace with an `agent` span and a child span for every model call, tool call and subagent, and
your workspace's tool-call rules (block, steer, require approval) apply to every tool call.

```python
import logicgaze
from logicgaze import create_agent, tool, SubAgent

logicgaze.init()   # or set LOGICGAZE_API_KEY; without it the agent runs untraced

@tool
def get_order(order_id: str) -> dict:
    """Look up an order.

    Args:
        order_id: The order number, e.g. O-1042.
    """
    return orders.get(order_id)

agent = create_agent(
    "openai:gpt-4.1",                     # or "anthropic:claude-sonnet-5-5", "azure:<deployment>",
    [get_order],                          # "logicgaze:openai/gpt-4o" (via the LogicGaze gateway), or a ChatModel
    instructions="You help customers with their orders.",
    subagents=[SubAgent(name="researcher", description="Looks up order history.", tools=[get_order])],
    skills="registry",                    # only skills an admin approved in LogicGaze → Skills
    filesystem=True,                      # scratch files: ls, read_file, write_file, edit_file, glob, grep
    interrupt_on={"issue_refund": True},  # ask a person in your app before these tools run
    approver=lambda call: call.arguments.get("amount", 0) <= 100,
)

result = agent.run("Where is order O-1042?", session_id="chat-17", user_id="cust-9")
print(result.output, result.todos, result.usage, result.trace_id)
```

- **Models:** `openai:`, `anthropic:`, `azure:` and `logicgaze:` specs, an OpenAI/Anthropic client with `model=`, or
  any subclass of `ChatModel` with an async `generate(messages, tools, **settings)`.
- **Tools:** `@tool` builds the JSON schema from type hints and the docstring (`Args:` section). Sync tools run in a
  worker thread. Errors and bad arguments go back to the model as tool results instead of ending the run.
- **Planning:** on by default; the agent gets `write_todos` and the plan is returned in `result.todos`.
- **Subagents:** the `task` tool hands a subtask to a subagent with a fresh context (a `general-purpose` subagent
  with the parent's tools is always available). Subagent runs nest under the `task` span in the same trace.
- **Skills:** `skills="registry"` loads approved skills; a directory path loads local `*/SKILL.md` files and, by
  default, only those that match an approved version in the registry.
- **Guardrails:** blocked or rejected calls return an error to the model; steered calls return the rule's guidance
  so the agent can take the safer path; `require_approval` waits for an approval in LogicGaze. `guardrails=False`
  turns this off.
- **Middleware:** subclass `AgentMiddleware` and override `tools`, `system_prompt`, `before_model`,
  `after_model` or `wrap_tool_call`, then pass `middleware=[...]`.
- **Running:** `agent.run(...)`, `await agent.arun(...)`, or `async for event in agent.astream(...)` for model,
  tool_call, tool_result, tool_refused, todos, file_written, skill_loaded, subagent_started, subagent_finished,
  approval and final events.
- **Tracing:** if your model client is already wrapped by `logicgaze.init(auto_instrument=True)` or `wrap_openai`,
  model calls are recorded once, by the wrapper.

## Agent tool-call guardrails

Create **Agent Tool Call** rules under Protect → Guardrails (for example "no email outside
acme.com", "refunds above $100 are blocked", "only `search_*` tools are allowed", or "no deletes on
the `github` MCP server"). The SDK enforces them in-process against the cached policy, with no extra
network call per check:

```python
from logicgaze import ToolCallBlocked, check_tool_call, guard_tool, wrap_mcp

# 1. Tool calls requested by the model are checked automatically when guardrails=True
lg.init(api_key="lgz_...", guardrails=True)
client = wrap_openai(OpenAI())          # a blocked tool call raises ToolCallBlocked before your app sees it

# 2. Guard your own tool functions (checked before they run, traced as tool spans)
@guard_tool
def send_email(to: str, subject: str, body: str): ...

# 3. Guard and trace an MCP session; rules can be scoped to an MCP server
async with Client("https://mcp.example.com/mcp") as session:
    session = wrap_mcp(session)
    await session.call_tool("create_issue", {"repo": "acme/app", "title": "Bug"})

# 4. Or check explicitly from any agent framework
check_tool_call("issue_refund", {"order_id": "O-1", "amount": 950})   # raises ToolCallBlocked
```

`ToolCallBlocked` is a subclass of `GuardrailBlocked` and exposes `.tool`, `.rule_name` and `.detail["reason"]`.
Checks fail open if the policy cannot be loaded. Other languages can call
`POST /api/v1/guardrails/tool-calls/check`.

### Approval and steering

A rule's action can also be **Require approval** or **Steer**:

- **Require approval** holds the call. `guard_tool`, `check_tool_call` and `wrap_mcp` ask LogicGaze for approval,
  then wait (default 300 s, `LOGICGAZE_APPROVAL_TIMEOUT` or `approval_timeout=`) while someone approves it under
  Guardrails → Approvals. An approval lets that exact call (same tool, server and arguments) run once. A rejection,
  expiry or timeout raises `ToolCallNotApproved`; so does LogicGaze being unreachable, because approval checks fail
  closed. Pass `wait_for_approval=False` to `check_tool_call` to raise straight away and retry later.
- **Steer** refuses the call and raises `ToolCallSteered`. Its message carries the rule's guidance (for example
  "Save the email as a draft and ask the user to send it"), so an agent that shows tool errors to the model can take
  the safer path.

Both are subclasses of `ToolCallBlocked`, so existing handlers keep working. API keys cannot approve calls; only a
person signed in to LogicGaze can.

## Masking

Control what LogicGaze **stores** (the LLM provider still receives the real
messages — masking only affects persisted observability data):

```python
logicgaze.init(
    api_key="lgz_...",
    hide_inputs=True,          # stored input_messages become [REDACTED]
    hide_outputs=True,         # stored output content becomes [REDACTED]
    mask=my_scrubber,          # or a custom callable applied before storage
)
```

Also available as env vars: `LOGICGAZE_HIDE_INPUTS`, `LOGICGAZE_HIDE_OUTPUTS`.
If `mask` raises, `[MASKING_ERROR]` is stored instead of raw data.

## OpenAI Agents SDK

```bash
pip install logicgaze[agents]
```

```python
import logicgaze
from logicgaze import instrument_openai_agents

logicgaze.init(api_key="lgz_...")
instrument_openai_agents()
# every Agent run is now traced — agent, generation (llm), tool,
# handoff, and guardrail spans land in LogicGaze automatically
```

Equivalent to `agents.add_trace_processor(LogicGazeTracingProcessor())`. All
callbacks are non-blocking and error-guarded — tracing can never crash the agent.

## Configuration

| Parameter | Environment variable | Default |
|-----------|---------------------|---------|
| `api_key` | `LOGICGAZE_API_KEY` | — |
| `base_url` | `LOGICGAZE_BASE_URL` | `http://localhost:8000` |
| `timeout` | `LOGICGAZE_TIMEOUT` | `30.0` s |
| `sample_rate` | `LOGICGAZE_SAMPLE_RATE` | `1.0` |
| `max_retries` | `LOGICGAZE_MAX_RETRIES` | `3` |
| `batch_size` | `LOGICGAZE_BATCH_SIZE` | `50` |
| `flush_interval` | `LOGICGAZE_FLUSH_INTERVAL` | `5.0` s |
| `debug` | `LOGICGAZE_DEBUG` | `False` |
| `hide_inputs` | `LOGICGAZE_HIDE_INPUTS` | `False` |
| `hide_outputs` | `LOGICGAZE_HIDE_OUTPUTS` | `False` |
| `mask` | — | `None` |
| `auto_instrument` | — | `False` |
| `routing` | `LOGICGAZE_ROUTING` | `"direct"` |
| `environment` | `LOGICGAZE_ENVIRONMENT` | — (traces count as `production`) |
| `release` | `LOGICGAZE_RELEASE` | — |

`environment` and `release` are attached to every trace and span, so the dashboard can filter by environment and the Releases page can compare one release with the next. Use a version number or commit SHA for `release`.

## API Reference

### `logicgaze.init(api_key, base_url, timeout, *, sample_rate, max_retries, batch_size, flush_interval, debug, mask, hide_inputs, hide_outputs, auto_instrument, routing, guardrails, environment, release)`
Initialize the global client. Call once at application startup.

### `logicgaze.uninstrument()`
Reverse `auto_instrument` — restores the patched OpenAI/Anthropic constructors.

### `wrap_openai(client, *, service_name=None, mode=None)`
Patches `client.chat.completions.create` (sync & async, streaming included). Returns the same client object.

### `wrap_anthropic(client, *, service_name=None, mode=None)`
Patches `client.messages.create` (sync & async, streaming included). Returns the same client object.

### `TraceContext(*, project, trace_id, session_id, user_id, service_name, tags)`
Context manager (sync & async). Starts a trace (unless one is already active) and groups every wrapped call made within the block into it.

### `@traceable(*, name, project, session_id, user_id, service_name, tags, run_type)`
Decorator that wraps the function body in a `TraceContext`. Works with sync and async functions.

### `instrument_openai_agents(client=None)`
Registers a `LogicGazeTracingProcessor` with the OpenAI Agents SDK. Returns the processor.

### `LogicGazeClient` methods

| Method | Description |
|--------|-------------|
| `chat_completion(provider, model, messages, **kwargs)` | Proxied LLM call via gateway |
| `achat_completion(...)` | Async version |
| `log_score(trace_id, name, value, ...)` | Attach an evaluation score (NUMERIC/CATEGORICAL/BOOLEAN) |
| `log_feedback(trace_id, feedback_type=..., ...)` | Attach end-user feedback |
| `list_scores(...)` | List scores with trace/name filters |
| `create_dataset(name, ...)` / `list_datasets()` | Manage datasets |
| `add_dataset_item(s)(...)` / `get_dataset_items(...)` | Manage dataset items |
| `add_traces_to_dataset(dataset_id, trace_ids)` | Copy production traces into a dataset |
| `get_prompt(name, version=None, cache_ttl_seconds=60)` | Fetch a cached `Prompt` (`.compile(**vars)`) |
| `create_prompt(name, prompt, ...)` / `list_prompt_versions(name)` | Manage prompt versions |
| `list_traces(**filters)` | List traces with optional filters |
| `get_trace(trace_id, include_spans)` | Fetch a trace and its spans |
| `get_spans(trace_id)` | Fetch all spans for a trace |
| `get_agent_graph(trace_id)` | Fetch the visual agent execution graph |
| `get_dashboard(window_hours)` | Aggregated dashboard metrics |
| `get_model_distribution(window_hours)` | Token & cost breakdown by model |
| `get_provider_breakdown(window_hours)` | Breakdown by AI provider |
| `estimate_cost(provider, model, prompt_tokens, completion_tokens)` | Pre-call cost estimate |
| `list_model_costs(provider)` | Pricing table for a provider |
| `get_guardrails_summary(window_hours)` | Guardrail event summary |

Most read/write methods have `a`-prefixed async variants (e.g. `alog_score`, `aget_prompt`, `acreate_span`).

## Requirements

- Python 3.9+
- `httpx >= 0.26.0`

Optional extras: `logicgaze[agents]` (OpenAI Agents SDK), `logicgaze[litellm]`,
`logicgaze[langchain]`, `logicgaze[google]`, `logicgaze[cohere]`, `logicgaze[groq]`,
`logicgaze[mistral]`, `logicgaze[all]`.

## Links

- **Dashboard**: [logicgaze.com](https://logicgaze.com)
- **Documentation**: [docs.logicgaze.com](https://docs.logicgaze.com)
- **GitHub**: [github.com/VikneeshVG/logicgaze](https://github.com/VikneeshVG/logicgaze)
- **PyPI**: [pypi.org/project/logicgaze](https://pypi.org/project/logicgaze/)

## License

MIT
