Skip to main content

AgentLens Python SDK

Official Python SDK (agentlensx) for integrating AgentLens observability, deterministic anomaly detection, and AI root-cause investigation into AI agents.


Installation

From PyPI:

pip install agentlensx

From GitHub (Direct):

pip install git+https://github.com/Siva-2517/AgentLens.git#subdirectory=sdk

From Local Source:

cd sdk
pip install -e .

Development Installation:

pip install -e ".[dev]"

Quick Start

import os
from agentlensx import AgentLens, EventType

# Initialize the SDK (Live Cloud or Local)
lens = AgentLens(
    api_url="https://agentlens-backend-ofqg.onrender.com",  # Or http://localhost:8000
    api_key=os.getenv("AGENTLENS_API_KEY", "al_live_your_key_here"),
    project_name="my-ai-agent",
)

# Use context manager for automatic trace management
with lens.trace("customer-support-agent") as trace_id:
    # Your agent code here
    user_input = "How do I reset my password?"
    
    # Log LLM calls
    lens.create_event(
        EventType.LLM_CALL,
        data={
            "model": "gpt-4",
            "prompt": user_input,
        }
    )
    
    # Agent processes...
    response = "To reset your password, visit..."
    
    lens.create_event(
        EventType.LLM_RESPONSE,
        data={"response": response}
    )
    
    # Log tool calls
    lens.create_event(
        EventType.TOOL_CALL,
        data={
            "tool": "search_knowledge_base",
            "query": "password reset",
        }
    )
    
    lens.create_event(
        EventType.TOOL_RESPONSE,
        data={"results": ["article_1", "article_2"]}
    )

# Trace automatically ends and events are flushed

Features

Event Types

The SDK supports the following event types:

  • AGENT_START - Agent execution begins
  • LLM_CALL - LLM API call initiated
  • LLM_RESPONSE - LLM response received
  • TOOL_CALL - Tool/function call initiated
  • TOOL_RESPONSE - Tool response received
  • STATE_CHANGE - Agent state changed
  • RETRY - Operation retry attempted
  • ERROR - Error occurred
  • AGENT_END - Agent execution completed

Automatic Trace Management

Use the context manager for automatic trace lifecycle:

with lens.trace("agent-name") as trace_id:
    # AGENT_START event created automatically
    # Your code here
    pass
    # AGENT_END event created automatically
    # Events flushed automatically

Manual Trace Management

For more control:

trace = lens.create_trace("manual-trace")

lens.create_event(
    EventType.LLM_CALL,
    trace_id=trace.trace_id,
    data={"model": "gpt-4"}
)

lens.end_trace(trace.trace_id, status="completed")
lens.flush()

Error Handling

Errors are automatically captured:

with lens.trace("agent-with-error"):
    try:
        # Your code
        risky_operation()
    except Exception as e:
        lens.create_event(
            EventType.ERROR,
            data={
                "error_type": type(e).__name__,
                "error_message": str(e),
            }
        )
        raise
# Trace status automatically set to "failed"

Configuration

from agentlensx import AgentLens, AgentLensConfig

config = AgentLensConfig(
    api_url="http://localhost:8000",
    api_key="your_api_key",  # Optional
    project_name="my-project",
    enabled=True,  # Set to False to disable telemetry
    batch_size=100,  # Events before auto-flush
    timeout=5,  # HTTP timeout in seconds
)

lens = AgentLens(**config.model_dump())

Disable Telemetry

# Disable for testing or local development
lens = AgentLens(enabled=False)

Nested Events

Track parent-child relationships:

with lens.trace("main-agent"):
    parent_event = lens.create_event(
        EventType.TOOL_CALL,
        data={"tool": "orchestrator"}
    )
    
    # Child event
    lens.create_event(
        EventType.LLM_CALL,
        parent_event_id=parent_event.event_id,
        data={"model": "gpt-4"}
    )

API Reference

AgentLens

Main client class for the SDK.

Methods:

  • create_trace(name, trace_id=None, metadata=None) - Create a new trace
  • end_trace(trace_id, status="completed") - End a trace
  • create_event(event_type, data=None, trace_id=None, parent_event_id=None, metadata=None) - Create an event
  • trace(name, trace_id=None, metadata=None) - Context manager for tracing
  • flush() - Manually flush pending events
  • close() - Close client and flush events

Event Types

All available event types are in the EventType enum:

from agentlensx import EventType

EventType.AGENT_START
EventType.LLM_CALL
EventType.LLM_RESPONSE
EventType.TOOL_CALL
EventType.TOOL_RESPONSE
EventType.STATE_CHANGE
EventType.RETRY
EventType.ERROR
EventType.AGENT_END

Testing

Run tests:

pytest

Run with coverage:

pytest --cov=agentlensx --cov-report=html

Architecture

The SDK is designed to be lightweight and non-intrusive:

  1. Client (AgentLens) - Main interface for creating traces and events
  2. Types - Pydantic models for traces and events
  3. Context - Thread-safe context management for traces
  4. Exporter - HTTP client for sending data to AgentLens API
  5. Config - Configuration management

Requirements

  • Python 3.11+
  • httpx
  • pydantic

Development

Install development dependencies:

pip install -e ".[dev]"

Run tests:

pytest

Format code:

black agentlensx tests

Lint:

ruff check agentlensx tests

License

Distributed under the MIT License. Copyright (c) 2026 Siva.

Metadata

Release files for agentlensx 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for agentlensx 0.1.0
File Size Uploaded Provenance
agentlensx-0.1.0.tar.gz 14.3 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for agentlensx 0.1.0
File Interpreter ABI Platform
agentlensx-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 24.4 kB

Release files / agentlensx-0.1.0.tar.gz

Download URL agentlensx-0.1.0.tar.gz
Size 14.3 kB
Tags Source
SHA-256 checksum
How to use checksums
378cd1b939b46ec62b1646afec918bcaa92bf335d27213ae4e2fbb02aa6408d9
BLAKE2b-256 checksum
How to use checksums
0fd5e74fdfcb7ff35537ad72ce7d20c1163a483c3c39a451f09482dbddcfe3c8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Release files / agentlensx-0.1.0-py3-none-any.whl

Download URL agentlensx-0.1.0-py3-none-any.whl
Size 10.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ca23e0f96ed98dc8ab80e2cc69bee55f15388020672f04a5d23ad46a5909cee5
BLAKE2b-256 checksum
How to use checksums
0765be56f7b77eb2b7d7945c765d164d30ed525bfccf68529c7d3338b5e96850
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Security for agentlensx 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page