# API Reference
## Environment Variables
| Variable | Required | Default | Description |
|---|---|---|---|
| `BLOCKLOG_API_KEY` | Yes | — | Your Blocklog API key |
| `BLOCKLOG_BASE_URL` | No | `https://blocklogsecurity.com/api/v1` | API endpoint |
| `BLOCKLOG_SDK_SIGNING_KEY` | No | `""` | HMAC-SHA256 signing key |
| `BLOCKLOG_TIMEOUT` | No | `10` | Request timeout in seconds |
| `BLOCKLOG_MAX_RETRIES` | No | `3` | Retry attempts on failure |
| `BLOCKLOG_BATCH_SIZE` | No | `100` | Events per batch flush |
| `BLOCKLOG_FLUSH_INTERVAL` | No | `2` | Seconds between auto-flushes |
---
## Initialization
### `blocklog.init`
```python
def init(
api_key: str | None = None,
*,
base_url: str | None = None,
signing_key: str | None = None,
timeout: float | None = None,
max_retries: int | None = None,
debug: bool = False,
) -> "BlocklogClient"Purpose: Initializes the Blocklog SDK. Call once at application startup.
Parameters:
api_key(str, optional): Your Blocklog API key. Falls back toBLOCKLOG_API_KEY.base_url(str, optional): Override the default API base URL. Falls back toBLOCKLOG_BASE_URL.signing_key(str, optional): HMAC-SHA256 key for tamper-evident log signatures. Falls back toBLOCKLOG_SDK_SIGNING_KEY. Note: this is not asymmetric Ed25519 signing.timeout(float, optional): Per-request timeout in seconds (default: 10). Falls back toBLOCKLOG_TIMEOUT.max_retries(int, optional): Number of automatic retries (default: 3). Falls back toBLOCKLOG_MAX_RETRIES.debug(bool, optional): IfTrue, logs every outbound request to stderr.
Returns: BlocklogClient
Example:
client = blocklog.init(api_key="blk_live_...")def agent(
func=None,
*,
name: str | None = None,
version: str = "1.0",
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
)Purpose: Traces an AI agent function, linking it to a Blocklog session. Automatically handles sync and async functions.
Warning: Class decoration only emits
AGENT_START. For full lifecycle tracing, decorate the specific method (e.g.run,execute) rather than the class itself.
Parameters:
name: Human-readable agent name. Defaults tofunc.__name__.version: Semver-style version string.tags: Optional list of string tags.metadata: Arbitrary extra data.
Returns: Decorated callable or class.
Example:
@blocklog.agent(name="analyst", version="1.0")
def run_analyst():
passdef tool(
func=None,
*,
name: str | None = None,
schema: dict[str, Any] | None = None,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
)Purpose: Records a tool call as a Blocklog event, capturing inputs, outputs, duration, and errors. Inherits trace context from the surrounding @agent.
Parameters:
name: Human-readable tool name. Defaults tofunc.__name__.schema: Optional dict describing the input schema.tags: Optional string tags.metadata: Arbitrary extra data.
Returns: Decorated callable.
Example:
@blocklog.tool(name="fetch-price")
def get_price(ticker: str) -> float:
return 100.0def decision(
*,
type: str,
asset: str | None = None,
confidence: float | None = None,
metadata: dict[str, Any] | None = None,
agent_id: str | None = None,
trace_id: str | None = None,
) -> Generator[DecisionContext, None, None]Purpose: Context manager for recording an AI decision.
Parameters:
type(str): Decision type identifier (e.g."BUY").asset(str, optional): Asset this decision is about.confidence(float, optional): Model confidence score (0 to 1).metadata(dict, optional): Extra fields.
Returns: Yields DecisionContext.
Example:
with blocklog.decision(type="BUY", asset="TSLA") as d:
d.record_input(price=412.50)
d.record_output(status="executed")Live handle to a decision being recorded.
record_input(**kwargs): Record structured inputs. Returnsself.record_output(**kwargs): Record structured outputs. Returnsself.tag(*tags): Attach string labels. Returnsself.request_approval(reason, reviewer=None): Non-blocking request for human approval. Returnsself.verify() -> dict: Verify the decision after thewithblock has exited. RaisesRuntimeErrorif called before the decision is committed.
Purpose: Synchronous core client. Usually instantiated via blocklog.init().
Methods:
from_env() -> BlocklogClient: Create a client from environment variables.add_hook(hook: Callable) -> BlocklogClient: Register a middleware hook applied to every outbound event.instrument_openai_agents() -> BlocklogClient: Auto-instrument the OpenAI Agents SDK.instrument_langchain() -> BlocklogClient: Auto-instrument LangChain.instrument_langgraph() -> BlocklogClient: Auto-instrument LangGraph.event(event_type, payload, **kwargs) -> IngestResponse: Emit a single event immediately.enqueue(event_type, payload, **kwargs): Enqueue an event for batched delivery.flush(batch=None): Flush the event buffer.
Purpose: Async client for use in async applications.
Methods: Same as BlocklogClient with async overrides:
async event(event_type, payload, **kwargs) -> IngestResponseasync flush(batch=None)
Purpose: Configuration Pydantic model.
Fields:
base_url: strapi_key: strsigning_key: str — HMAC-SHA256 key, not Ed25519timeout: floatmax_retries: intbatch_size: intflush_interval: float
Available via client.module.method() or imported directly from blocklog.api.*.
create(decision_type, asset, confidence, metadata, trace_id, session_id, agent_id) -> dictlist() -> list[dict]get(decision_id) -> dictverify(decision_id) -> dicttimeline(decision_id) -> list[dict]evidence(decision_id) -> dictreplay(decision_id) -> dict
Human-in-the-loop workflows.
request(decision_id, reason, reviewer, log_id, metadata) -> dictreject(reviewer, reason, decision_id) -> dictescalate(from_reviewer, to_reviewer, reason) -> dictlist_overrides() -> list[dict]audit_trail() -> list[dict]
Incident management. Not exported from the top-level blocklog namespace — import via from blocklog.api.incidents import IncidentsClient or access via client.incidents.
create(title, trace_id, severity, description, metadata) -> IncidentHandleget(incident_id) -> IncidentHandlelist_all() -> list[IncidentHandle]
Forensic replay sessions.
replay(trace_id, token_id, metadata) -> ReplaySession
Access via client.verify to avoid naming conflict with DecisionContext.verify().
log(log_id) -> dictbatch(batch_id) -> dictdecision(decision_id) -> dict
Compliance report generation.
generate(trace_id, framework, date_from, date_to, metadata) -> dictget(report_id) -> dictlist() -> list[dict]dashboard() -> dictshare(report_id, expires_in, recipient_email) -> dictexport(report_id, download) -> dict