Skip to main content

Infrastructure for AI Decision-Making — record, replay, verify, and govern AI agent decisions

Project description

Blocklog Python SDK

Record, audit, and investigate every decision your AI agents make.

Python 3.10+ Version 0.2.0 License: MIT Documentation


Why Blocklog?

When AI agents execute actions in production, the context behind their decisions is often lost. Debugging failures, reproducing state, and maintaining compliance becomes nearly impossible without a structured audit trail. Blocklog solves this by capturing exactly what the model knew, what tools it used, and what it ultimately decided—all securely anchored and optionally requiring human approval.


What Blocklog Does

  • Trace AI agents and their execution duration automatically.
  • Trace tool calls, capturing inputs and outputs seamlessly.
  • Record decisions with detailed metadata, inputs, and outputs.
  • Request approvals via non-blocking human-in-the-loop workflows.
  • Verify records cryptographically against a blockchain anchor.
  • Generate compliance evidence (e.g., SOC2, GDPR).
  • Investigate failures with replay using forensic timelines and root-cause analysis.

Architecture Overview

    AI Agent
       ↓
@blocklog.agent
       ↓
 Tools + Decisions
       ↓
  Event Buffer
       ↓
  Blocklog API
       ↓
Replay / Verification / Compliance

Installation

Blocklog requires Python 3.10+. Install the SDK from PyPI:

pip install blocklog

For development installation or to install from source:

git clone https://github.com/blockloghq/blocklog-python.git
cd blocklog-python
pip install -e .

Quickstart

import os
import blocklog

# 1. Initialize the SDK
blocklog.init(api_key=os.environ.get("BLOCKLOG_API_KEY", "blk_demo_key"))

# 2. Record tool calls
@blocklog.tool
def check_price(ticker: str) -> float:
    return 412.50

# 3. Trace your agent
@blocklog.agent(name="simple-trader")
def run_agent():
    price = check_price("TSLA")
    
    # 4. Record the decision
    with blocklog.decision(type="BUY", asset="TSLA") as d:
        d.record_input(price=price)
        d.record_output(order_id="ord_123")
        
    print(f"Decision recorded: {d.id}")

if __name__ == "__main__":
    run_agent()

What Happens Under The Hood?

When you apply @blocklog.agent, Blocklog starts an internal session context that automatically propagates a trace_id to any subsequent operations. When @blocklog.tool is invoked, it captures the inputs and outputs, linking them to the active trace. Finally, blocklog.decision() bundles the agent's logic into a concrete, auditable event that is asynchronously buffered and flushed to the Blocklog backend without blocking your application.


Core Concepts

  • Decision: A structured record of an AI action, tracking the explicit inputs it considered and the outputs it generated.
  • Trace: The end-to-end execution path of an agent, automatically correlating all tool calls and decisions via a shared trace_id.
  • Event: A low-level building block representing a single state change (e.g., TOOL_CALL, DECISION_INPUT), securely buffered and dispatched.
  • Approval: A human-in-the-loop (HITL) gate that flags high-stakes decisions for manual review.
  • Replay: A forensic reconstruction of a trace allowing developers to understand the root cause of an agent's failure or action.

Common Use Cases

  • Trading Agents: Capturing the exact market data (inputs) that led an agent to execute a trade (output).
  • AI Copilots: Tracing user interactions and the tools invoked to fetch internal company data.
  • Compliance-Sensitive Workflows: Automatically generating SOC2 or GDPR reports for AI behavior.
  • Customer Support Agents: Recording decisions to escalate to human agents vs. resolving automatically.
  • Human-in-the-Loop Systems: Pausing execution of high-value actions (e.g., refunds > $500) until a human reviewer approves.

Integrations

Blocklog seamlessly auto-instruments popular AI frameworks:

  • LangChain: Trace chains, LLMs, and tools automatically via client.instrument_langchain().
  • LangGraph: Hook into graph states via client.instrument_langgraph().
  • OpenAI Agents: Track official SDK executions via client.instrument_openai_agents().

Read more in the Integrations Guide.


Documentation

Topic Guide
Getting Started InstallationQuickstartCore Concepts
Instrumentation TracingDecisionsDecorators
Frameworks Integrations
Operations Async UsageProductionPerformance
Reference API ReferenceError HandlingTroubleshooting
Misc ExamplesChangelog

Examples

We provide several runnable scripts in the examples/ directory to help you understand Blocklog in practice:

  • 01_quickstart.py: The bare minimum needed to trace an agent, run a tool, and record a decision.
  • 02_stock_trading_agent.py: A simulated trading agent demonstrating tool tagging, human-in-the-loop approvals, and cryptographic verification.
  • 03_multi_agent_workflow.py: A complex pipeline showing context passing across Analyst, Risk, and Executor agents, ending in a compliance report.

Production Features

  • Async Support: Native asyncio compatibility utilizing contextvars for seamless trace propagation across await boundaries.
  • Event Buffering: High-volume telemetry is safely batched in-memory and flushed asynchronously.
  • Retry Handling: Built-in exponential backoff for transient network issues.
  • Signing: Optional Ed25519 payload signing for tamper-evident, cryptographically verifiable logs.
  • Middleware Hooks: Add custom logic to redact PII or inject metadata before payloads leave your server.

Read our Production Best Practices for more details.


Contributing

We welcome contributions to the Blocklog Python SDK! Please read through our open issues or submit a Pull Request. Ensure you have installed the SDK in editable mode (pip install -e .) before running tests.


Configuration

Blocklog can be configured via environment variables:

Variable Description Default
BLOCKLOG_API_KEY Your Blocklog API key ""
BLOCKLOG_BASE_URL API base URL http://127.0.0.1:8000/api/v1
BLOCKLOG_SDK_SIGNING_KEY Optional seed key for hash signing ""
BLOCKLOG_TIMEOUT Request timeout in seconds 10
BLOCKLOG_MAX_RETRIES Number of retry attempts 3
BLOCKLOG_BATCH_SIZE Event batch size 100
BLOCKLOG_FLUSH_INTERVAL Batch flush interval in seconds 2

Troubleshooting

Installation Issues

If you encounter installation errors:

# Upgrade pip first
pip install --upgrade pip

# Install with verbose output
pip install blocklog -v

Import Errors

If you get import errors after installation:

# Verify installation
pip show blocklog

# Reinstall if needed
pip install --force-reinstall blocklog

Connection Issues

If the SDK cannot connect to the Blocklog API:

  1. Verify your API key is correct
  2. Check that BLOCKLOG_BASE_URL points to the correct endpoint
  3. Ensure network connectivity to the API server
  4. Check firewall settings

Links


License

MIT License. See the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

blocklog-0.2.0.tar.gz (62.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

blocklog-0.2.0-py3-none-any.whl (44.6 kB view details)

Uploaded Python 3

File details

Details for the file blocklog-0.2.0.tar.gz.

File metadata

  • Download URL: blocklog-0.2.0.tar.gz
  • Upload date:
  • Size: 62.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.11

File hashes

Hashes for blocklog-0.2.0.tar.gz
Algorithm Hash digest
SHA256 4f2d1e4eb6b53fbca8b4860c19e8dfd1b4ba4552353f3504cdb9dccf447ddb27
MD5 adb58cee0476e494a1af33a726b8201b
BLAKE2b-256 3e8b8599c7d85cf577739a77809b0aa543e1cce034f2e1d65c5b427ad8d63f4a

See more details on using hashes here.

File details

Details for the file blocklog-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: blocklog-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 44.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.11

File hashes

Hashes for blocklog-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2ee10b91c8038fa2303872702a13fdc0945a3c0ad2dd89d656283dcbd16accf6
MD5 74a1251907fb523704407a93b238526f
BLAKE2b-256 6c4df403d73a42b2726d52e9c7efcc73543580f3a078a77108e533cf9713d678

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page