Official Python SDK for the Tracium telemetry and evaluation API. Automatic tracing for OpenAI, Anthropic, Google Gemini, LangChain, and LangGraph.
Project description
Tracium Python SDK - Developer Guide
This is the development guide for the Tracium Python SDK. For user documentation, see https://docs.tracium.ai.
Version: 0.1.0
Project Overview
The Tracium Python SDK provides automatic instrumentation and tracing for LLM applications. It supports OpenAI, Anthropic, Google Gemini, LangChain, and LangGraph with minimal configuration.
Development Setup
Prerequisites
- Python 3.9 or higher
- pip
- git
Initial Setup
# Clone the repository
git clone https://github.com/AntonijSimonovski/tracium-python.git
cd tracium-python/tracium
# Create a virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install the package in editable mode with dev dependencies
# This automatically handles PYTHONPATH for src/ directory
pip install -e ".[dev]"
Environment Variables
For local development and testing, you may need to set:
export TRACIUM_API_KEY="sk_test_..." # Required for integration tests only
export TRACIUM_BASE_URL="https://api.tracium.ai" # Optional: override API endpoint
Project Structure
tracium/
├── src/
│ └── tracium/
│ ├── __init__.py # Public API entrypoint
│ ├── api/ # HTTP client and API endpoints
│ │ ├── endpoints.py # API endpoint definitions
│ │ └── http_client.py # HTTP client implementation
│ ├── context/ # Context management
│ │ ├── context_propagation.py # Thread context propagation
│ │ ├── tenant_context.py # Multi-tenant context
│ │ └── trace_context.py # Trace context management
│ ├── core/ # Core SDK components
│ │ ├── client.py # Main TraciumClient class
│ │ ├── config.py # Configuration classes
│ │ └── version.py # Version information
│ ├── helpers/ # Utility modules
│ │ ├── call_hierarchy.py # Call hierarchy tracking
│ │ ├── embeddings.py # Embedding computation
│ │ ├── global_state.py # Global SDK state
│ │ ├── logging_config.py # Logging configuration
│ │ ├── parallel_tracker.py # Parallel execution tracking
│ │ ├── retry_async.py # Async retry logic
│ │ ├── retry.py # Sync retry logic
│ │ ├── security.py # Security utilities
│ │ ├── thread_helpers.py # Threading utilities
│ │ └── validation.py # Input validation
│ ├── instrumentation/ # Auto-instrumentation
│ │ ├── auto_detection.py # Library detection
│ │ ├── auto_instrumentation.py # Main instrumentation logic
│ │ ├── auto_trace_tracker.py # Automatic trace tracking
│ │ └── decorators.py # Decorator-based instrumentation
│ ├── integrations/ # Library-specific integrations
│ │ ├── anthropic.py # Anthropic/Claude integration
│ │ ├── google.py # Google Gemini integration
│ │ ├── langchain.py # LangChain integration
│ │ ├── langgraph.py # LangGraph integration
│ │ └── openai.py # OpenAI integration
│ ├── models/ # Data models
│ │ ├── span_handle.py # Span management
│ │ ├── trace_handle.py # Trace management
│ │ └── trace_state.py # Trace state management
│ └── utils/ # Additional utilities
│ ├── datetime_utils.py # Date/time utilities
│ ├── span_registry.py # Span registry
│ ├── tags.py # Tag utilities
│ └── validation.py # Additional validation
├── tests/ # Test suite (if exists)
├── pyproject.toml # Project configuration
├── LICENSE # MIT License
└── README.md # This file
Key Modules
Core Components
core/client.py: MainTraciumClientclass that handles all API communicationcore/config.py: Configuration classes (TraciumClientConfig,RetryConfig)__init__.py: Public API surface with convenience functions (init(),trace(),start_trace())
Instrumentation
instrumentation/auto_instrumentation.py: Main orchestration for auto-instrumentationinstrumentation/auto_detection.py: Detects which libraries are installedintegrations/*.py: Library-specific instrumentation hooks
Context Management
context/trace_context.py: Manages active trace context (thread-local)context/context_propagation.py: Propagates context across threads/async boundariescontext/tenant_context.py: Multi-tenant context management
Helpers
helpers/global_state.py: Global SDK state (client instance, default options)helpers/retry.py&helpers/retry_async.py: Retry logic with exponential backoffhelpers/validation.py: Input validation utilitieshelpers/parallel_tracker.py: Tracks parallel execution contexts
Development Workflow
Running Tests
If you installed with pip install -e ".[dev]", pytest will automatically find the src package.
# Run all tests
pytest
# Run with coverage
pytest --cov=tracium --cov-report=html
# Run specific test file
pytest tests/test_specific.py
# Run with verbose output
pytest -v
If you encounter ModuleNotFoundError: No module named 'tracium', ensure you are in the virtual environment and have installed the package in editable mode, or run:
PYTHONPATH=src pytest
Code Quality
# Run linter
ruff check tracium/
# Auto-fix linting issues
ruff check --fix tracium/
# Run type checker
mypy tracium/
# Format code
ruff format tracium/
Pre-commit Checks
Before committing, ensure:
- All tests pass:
pytest - Linting passes:
ruff check tracium/ - Type checking passes:
mypy tracium/ - Code is formatted:
ruff format tracium/
Architecture Notes
Thread Context Propagation
The SDK patches ThreadPoolExecutor and Thread classes at import time to automatically propagate trace context across threads. This happens in __init__.py before any user code runs.
Auto-Instrumentation
Auto-instrumentation works by:
- Detecting installed libraries (
auto_detection.py) - Monkey-patching library methods to intercept calls
- Creating traces/spans automatically
- Sending data to Tracium API
Global State
The SDK uses a global state pattern (helpers/global_state.py) to store:
- The initialized client instance
- Default options (agent name, version, tags, metadata)
- Instrumentation configuration
Retry Logic
Both sync and async retry logic are implemented:
- Exponential backoff with configurable parameters
- Max retry attempts
- Fail-open behavior (errors don't break user code)
Building and Releasing
Building the Package
# Build source distribution
python -m build
# Build wheel
python -m build --wheel
Version Management
Version is defined in src/tracium/core/version.py. Update this file when releasing a new version.
Release Checklist
- Update version in
src/tracium/core/version.py - Update version in
pyproject.toml - Update
CHANGELOG.md(if exists) - Run all tests:
pytest - Run linting:
ruff check tracium/ - Run type checking:
mypy tracium/ - Build package:
python -m build - Test installation:
pip install dist/tracium_sdk-*.whl - Tag release:
git tag v0.1.0 - Push tags:
git push --tags - Publish to PyPI:
twine upload dist/*
Testing Strategy
Unit Tests
Test individual functions and classes in isolation.
Integration Tests
Test interactions between components (e.g., client → API, instrumentation → client).
Library Integration Tests
Test auto-instrumentation with actual library calls (OpenAI, Anthropic, etc.). These may require API keys.
Mocking
Use mocks for:
- HTTP requests to Tracium API
- External library calls when testing instrumentation
- Time-dependent operations
Code Style
- Line length: 100 characters (configured in
pyproject.toml) - Formatter: Ruff (black-compatible)
- Linter: Ruff
- Type checker: mypy
- Python version: 3.9+
Type Hints
Use type hints throughout the codebase. The package includes py.typed marker for PEP 561 compliance.
Docstrings
Use Google-style docstrings for public APIs:
def my_function(param1: str, param2: int) -> bool:
"""
Brief description.
Args:
param1: Description of param1
param2: Description of param2
Returns:
Description of return value
Raises:
ValueError: When something goes wrong
"""
Common Development Tasks
Adding a New Integration
- Create a new file in
integrations/(e.g.,integrations/new_library.py) - Implement instrumentation hooks
- Register in
instrumentation/auto_instrumentation.py - Add detection logic in
instrumentation/auto_detection.py - Add tests
- Update documentation
Adding a New API Endpoint
- Define endpoint in
api/endpoints.py - Add method to
TraciumClientincore/client.py - Update HTTP client if needed (
api/http_client.py) - Add tests
- Update public API in
__init__.pyif needed
Debugging
Enable debug logging:
from tracium import configure_logging
import logging
configure_logging(level=logging.DEBUG)
This will show:
- API request/response details (with sensitive data redacted)
- Retry attempts
- Instrumentation activity
- Context propagation
Dependencies
Core Dependencies
httpx>=0.27,<0.29: HTTP clientpython-dotenv>=1.0.0: Environment variable management
Integration Dependencies
These are optional and only needed if you want to test specific integrations:
openai>=1.0.0: OpenAI integrationanthropic>=0.18.0: Anthropic integrationgoogle-generativeai>=0.3.0: Google Gemini integrationlangchain>=0.1.0: LangChain integrationlanggraph>=0.0.1: LangGraph integration
Dev Dependencies
pytest>=7.0: Testing frameworkpytest-cov>=4.0: Coverage reportingpytest-asyncio>=0.21.0: Async test supportruff>=0.1.0: Linting and formattingmypy>=1.0: Type checkingtypes-httpx: Type stubs for httpx
Troubleshooting
Import Errors
If you see import errors, ensure:
- Virtual environment is activated
- Package is installed in editable mode:
pip install -e ".[dev]" - Python path includes
src/directory
Type Checking Errors
Run mypy tracium/ to see specific type errors. Some may require type annotations or # type: ignore comments.
Test Failures
- Check that required environment variables are set
- Ensure all dependencies are installed
- Check for API key issues (use test keys for integration tests)
Contributing
- Create a feature branch:
git checkout -b feature/my-feature - Make your changes
- Run tests:
pytest - Run linting:
ruff check tracium/ - Run type checking:
mypy tracium/ - Format code:
ruff format tracium/ - Commit with descriptive messages
- Push and create a pull request
Resources
- Repository: https://github.com/AntonijSimonovski/tracium-python
- Issue Tracker: https://github.com/AntonijSimonovski/tracium-python/issues
- User Documentation: https://docs.tracium.ai
- PyPI Package: https://pypi.org/project/tracium-sdk/
License
MIT © Tracium
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tracium-0.1.0.tar.gz.
File metadata
- Download URL: tracium-0.1.0.tar.gz
- Upload date:
- Size: 64.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1c1d10dbbaa6cd34df540bb318a0a0ad4a24d66c65ea26068f5b75be6233d609
|
|
| MD5 |
2660140116d805b4b1b0b885204234f6
|
|
| BLAKE2b-256 |
bdd104697c448eec5910d83bb047015eee45ee2fc4681988ee6d46b287705e6b
|
File details
Details for the file tracium-0.1.0-py3-none-any.whl.
File metadata
- Download URL: tracium-0.1.0-py3-none-any.whl
- Upload date:
- Size: 67.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a22d24377fb8fc095b2c57f2ecd0d92c023a7b64f662bd4fe4321fa2dc10c314
|
|
| MD5 |
b608412a564a178780d41c929501c9cf
|
|
| BLAKE2b-256 |
ed5fbf615b32b4dcfff278772e65f0d9b6961bc39749b5e6fceffd6da7641f31
|