A Python package for Veris AI tools
Project description
Veris AI Python SDK
A Python package for Veris AI tools with simulation capabilities and FastAPI MCP (Model Context Protocol) integration.
Installation
You can install the package using uv:
# Install the package
uv add veris-ai
# Install with development dependencies
uv add "veris-ai[dev]"
# Install with FastAPI MCP integration
uv add "veris-ai[fastapi]"
# Install with tracing/instrumentation support
uv add "veris-ai[instrument]"
Import Options
The SDK supports flexible import patterns to minimize dependencies:
Default Imports (Base Dependencies Only)
# These imports only require base dependencies (httpx, pydantic, requests)
from veris_ai import veris, JaegerClient
Optional Imports (Require Extra Dependencies)
# The instrument function requires the 'instrument' extra
# Install with: pip install veris-ai[instrument] or uv add "veris-ai[instrument]"
from veris_ai import instrument # Lazy-loaded, will error if deps missing
Direct Submodule Imports
For maximum control over dependencies, you can import directly from submodules:
# Import only what you need
from veris_ai.tool_mock import veris
from veris_ai.jaeger_interface import JaegerClient
from veris_ai.braintrust_tracing import instrument # Requires [instrument] extra
Environment Setup
The package requires the following environment variables:
# Required: URL for the mock endpoint
VERIS_MOCK_ENDPOINT_URL=http://your-mock-endpoint.com
# Optional: Timeout in seconds (default: 30.0)
VERIS_MOCK_TIMEOUT=30.0
# Optional: Set to "simulation" to enable mock mode
ENV=simulation
Tracing Integration
The SDK provides seamless integration with Braintrust and Jaeger/OpenTelemetry for distributed tracing.
Setting up Tracing
from veris_ai import instrument
# Initialize tracing instrumentation
instrument(
service_name="my-service", # or via VERIS_SERVICE_NAME env var
otlp_endpoint="http://localhost:4317" # or via VERIS_OTLP_ENDPOINT env var
)
Session ID Tracking
When using the SDK with FastAPI MCP integration, session IDs are automatically embedded in all traces:
-
Automatic Session Extraction: When a request includes an Authorization header with a bearer token, the token is automatically used as the session ID.
-
Trace Attribution: All spans created during a request will include the
veris.session_idattribute, allowing you to:- Filter traces by session in Jaeger
- Correlate all operations within a single user session
- Debug issues specific to a particular session
-
Example:
# FastAPI app with MCP integration from fastapi import FastAPI from veris_ai import veris, instrument app = FastAPI() # Set up tracing instrument() # Set up FastAPI MCP with session handling veris.set_fastapi_mcp( fastapi=app, name="My API Server" ) # Now all traces will automatically include session IDs from bearer tokens
-
Manual Session Management: You can also manually set session IDs:
veris.set_session_id("custom-session-123") # All subsequent operations will be tagged with this session ID veris.clear_session_id() # Clear when done
The session ID tracking works seamlessly with both the mock decorators and the tracing system, providing end-to-end visibility of user sessions across your application.
Python Version
This project requires Python 3.11 or higher. We use pyenv for Python version management.
To set up the correct Python version:
# Install Python 3.11.0 using pyenv
pyenv install 3.11.0
# Set the local Python version for this project
pyenv local 3.11.0
Usage
from veris_ai import veris
@veris.mock()
async def your_function(param1: str, param2: int) -> dict:
"""
Your function documentation here.
Args:
param1: Description of param1
param2: Description of param2
Returns:
A dictionary containing the results
"""
# Your implementation here
return {"result": "actual implementation"}
When ENV=simulation is set, the decorator will:
- Capture the function signature, type hints, and docstring
- Send this information to the mock endpoint
- Convert the mock response to the expected return type
- Return the mock result
When not in simulation mode, the original function will be executed normally.
Stub Decorator
For simple test scenarios where you want to return a fixed value in simulation mode, use the @veris.stub() decorator:
from veris_ai import veris
@veris.stub(return_value={"status": "success", "data": [1, 2, 3]})
async def get_data() -> dict:
"""Get some data from external service."""
# This implementation is only called in production mode
return await fetch_from_api()
# In simulation mode: always returns {"status": "success", "data": [1, 2, 3]}
# In production mode: calls fetch_from_api()
The stub decorator is useful for:
- Quick prototyping with fixed responses
- Testing with predictable data
- Bypassing external dependencies in development
FastAPI MCP Integration
The SDK provides integration with FastAPI applications through the Model Context Protocol (MCP). This allows your FastAPI endpoints to be exposed as MCP tools that can be used by AI agents.
from fastapi import FastAPI
from veris_ai import veris
app = FastAPI()
# Set up FastAPI MCP with automatic session handling
veris.set_fastapi_mcp(
fastapi=app,
name="My API Server",
description="My FastAPI application exposed as MCP tools",
describe_all_responses=True,
include_operations=["get_users", "create_user"],
exclude_tags=["internal"]
)
# The MCP server is now available at veris.fastapi_mcp
mcp_server = veris.fastapi_mcp
Configuration Options
The set_fastapi_mcp() method accepts the following parameters:
- fastapi (required): Your FastAPI application instance
- name: Custom name for the MCP server (defaults to app.title)
- description: Custom description (defaults to app.description)
- describe_all_responses: Whether to include all response schemas in tool descriptions
- describe_full_response_schema: Whether to include full JSON schema for responses
- http_client: Optional custom httpx.AsyncClient instance
- include_operations: List of operation IDs to include as MCP tools
- exclude_operations: List of operation IDs to exclude (can't use with include_operations)
- include_tags: List of tags to include as MCP tools
- exclude_tags: List of tags to exclude (can't use with include_tags)
- auth_config: Optional FastAPI MCP AuthConfig for custom authentication
Session Management
The SDK automatically handles session management through OAuth2 authentication:
- Session IDs are extracted from bearer tokens
- Context is maintained across API calls
- Sessions can be managed programmatically:
# Get current session ID
session_id = veris.session_id
# Set a new session ID
veris.set_session_id("new-session-123")
# Clear the session
veris.clear_session_id()
Braintrust & Jaeger Tracing
The SDK includes a non-invasive instrumentation helper for sending traces to both Braintrust and a Jaeger-compatible OpenTelemetry (OTEL) collector simultaneously. This allows you to leverage Braintrust's powerful monitoring and evaluation tools while also storing and visualizing traces in your own Jaeger instance.
Usage
To enable parallel tracing, simply import the braintrust_tracing module and call the instrument() function at the beginning of your application's lifecycle.
from veris_ai import braintrust_tracing
# Enable Braintrust and Jaeger tracing
braintrust_tracing.instrument()
Configuration
The instrument() function is configured through environment variables:
VERIS_SERVICE_NAME(required): The name of your service as it will appear in Jaeger.VERIS_OTLP_ENDPOINT(required): The gRPC endpoint of your Jaeger OTLP collector (e.g.,http://host.docker.internal:4317).
When initialized, the SDK automatically patches the agents library to send traces to both systems without any further code changes required.
Utility Functions
extract_json_schema
The SDK provides a utility function to extract JSON schemas from Python types and Pydantic models:
from veris_ai.utils import extract_json_schema
from pydantic import BaseModel
from typing import List, Optional
# Extract schema from built-in types
int_schema = extract_json_schema(int)
# {"type": "integer"}
list_schema = extract_json_schema(List[str])
# {"type": "array", "items": {"type": "string"}}
# Extract schema from Pydantic models
class User(BaseModel):
name: str
age: int
email: Optional[str] = None
user_schema = extract_json_schema(User)
# Returns full JSON schema with properties, required fields, etc.
# Extract schema from TypedDict
from typing import TypedDict
class Config(TypedDict):
host: str
port: int
debug: bool
config_schema = extract_json_schema(Config)
# {"type": "object", "properties": {...}, "required": ["host", "port", "debug"]}
This function supports:
- Built-in types (str, int, float, bool, None)
- Generic types (List, Dict, Union, Optional, Literal)
- Pydantic models
- TypedDict classes
- Forward references and complex nested types
Project Structure
src/veris_ai/
├── __init__.py # Main entry point, exports the veris instance
├── tool_mock.py # VerisSDK class with @veris.mock() decorator
└── utils.py # Type conversion and JSON schema utilities
tests/
├── conftest.py # Pytest fixtures
├── test_tool_mock.py # Tests for VerisSDK functionality
└── test_utils.py # Tests for type conversion and schema extraction
Development
This project uses pyproject.toml for dependency management and uv for package installation.
Development Dependencies
To install the package with development dependencies:
uv add "veris-ai[dev]"
This will install the following development tools:
- Ruff: Fast Python linter
- pytest: Testing framework
- pytest-asyncio: Async support for pytest
- pytest-cov: Coverage reporting for pytest
- black: Code formatter
- mypy: Static type checker
- pre-commit: Git hooks for code quality
Code Quality
This project uses Ruff for linting and code quality checks. Ruff is a fast Python linter written in Rust.
To run Ruff:
# Lint code
ruff check .
# Auto-fix linting issues
ruff check --fix .
# Format code
ruff format .
# Check formatting only
ruff format --check .
The Ruff configuration is defined in pyproject.toml under the [tool.ruff] section.
Running Tests
# Run all tests with coverage
pytest tests/ --cov=veris_ai --cov-report=xml --cov-report=term-missing
# Run specific test file
pytest tests/test_tool_mock.py
# Run tests with verbose output
pytest -v tests/
Type Checking
# Run static type checking
mypy src/veris_ai tests
License
This project is licensed under the MIT License - see the LICENSE file for details.
Jaeger Trace Interface
A lightweight, fully-typed wrapper around the Jaeger Query Service HTTP API lives under veris_ai.jaeger_interface.
It allows you to search and retrieve traces from both Jaeger's default storage back-ends as well as OpenSearch, with additional client-side span filtering capabilities.
from veris_ai.jaeger_interface import JaegerClient
client = JaegerClient("http://localhost:16686")
# Search with trace-level filters (server-side)
traces = client.search(service="veris-agent", limit=2, tags={"error": "true"})
# Search with span-level filters (client-side, OR logic)
filtered = client.search(
service="veris-agent",
limit=10,
span_tags={"http.status_code": 500, "db.error": "timeout"}
)
first_trace = client.get_trace(traces.data[0].traceID)
See src/veris_ai/jaeger_interface/README.md for a complete walkthrough and API reference.
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 veris_ai-1.3.0.tar.gz.
File metadata
- Download URL: veris_ai-1.3.0.tar.gz
- Upload date:
- Size: 105.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4974b32e52bcce37cfdcac0886c27e71d900b524979c8da8d24c5bee5aa00204
|
|
| MD5 |
dff8cd4cec487815c91bc29d525c3341
|
|
| BLAKE2b-256 |
bbc5c41864c05c085496605ba540f206ac3fadfe3d535d833641262676ebf977
|
File details
Details for the file veris_ai-1.3.0-py3-none-any.whl.
File metadata
- Download URL: veris_ai-1.3.0-py3-none-any.whl
- Upload date:
- Size: 23.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cc527ddc07f7012f1f3d423058b5af0cfc279afd42a3bc938e5213850ae5889a
|
|
| MD5 |
e34769be9a130b8d37067b275b6e2fcc
|
|
| BLAKE2b-256 |
12e99c76f22cd0e476da1748ea3107813cbe6a870c167a18f99a1e524c15d636
|