Skip to main content

Scope Analytics - Backend SDK

AI-powered analytics for backend applications with zero-code LLM conversation tracking.

Features

  • Automatic LLM Tracking: Captures OpenAI, Anthropic, and Gemini calls automatically
  • Outbound Call Tracking: Records the calls your app makes to other services (httpx, httpx2, requests, aiohttp, urllib) — destination, status, latency and failures. Never the request or response bodies.
  • Session Correlation: Links backend events to frontend user sessions via X-Scope-Session-ID header
  • Conversation Intelligence: Classifies LLM calls as user-facing vs background jobs
  • Zero Code Changes: Drop-in integration with automatic monkey-patching
  • Async & Non-Blocking: Events shipped in background without affecting performance

Installation

pip install scope-analytics

Quick Start

Choose your installation method:

Zero code changes required - just change how you run your app.

Step 1: Set your API key

export SCOPE_API_KEY="sk_live_..."

Step 2: Run with scope-run

# Instead of:   python app.py
# Run:          scope-run python app.py

# Instead of:   uvicorn main:app --reload
# Run:          scope-run uvicorn main:app --reload

# Instead of:   gunicorn app:app -w 4                                   (Flask, Django)
# Run:          scope-run gunicorn app:app -w 4

# Instead of:   gunicorn main:app -w 4 -k uvicorn_worker.UvicornWorker  (FastAPI; pip install uvicorn-worker)
# Run:          scope-run gunicorn main:app -w 4 -k uvicorn_worker.UvicornWorker

# Instead of:   flask run --port 5000
# Run:          scope-run flask run --port 5000

That's it! Your LLM calls are now automatically tracked AND correlated with frontend sessions (for FastAPI, Flask, Django). Workers forked by gunicorn or Celery ship on their own timer (0.1.5). LangChain / LangGraph, LlamaIndex, PydanticAI, Instructor and the OpenAI Agents SDK are captured through the SDK they call (LangChain needs 0.1.5).

Serverless / notebooks — no start command to prefix: create scope = ScopeAnalytics() at module import and call scope.flush(timeout=2.0) before the handler returns (0.1.5).

Option B: Code-Based Installation

Add 2 lines to your app for more control.

from scope_analytics import ScopeAnalytics
scope = ScopeAnalytics(api_key="sk_live_...")

For session correlation with frontend, add middleware:

FastAPI:

from fastapi import FastAPI
from scope_analytics import ScopeAnalytics, ScopeSessionMiddleware

app = FastAPI()
app.add_middleware(ScopeSessionMiddleware)
scope = ScopeAnalytics(api_key="sk_live_...")

Flask:

from flask import Flask
from scope_analytics import ScopeAnalytics, init_flask_session_tracking

app = Flask(__name__)
init_flask_session_tracking(app)
scope = ScopeAnalytics(api_key="sk_live_...")

Django:

# settings.py
MIDDLEWARE = [
    'scope_analytics.middleware.DjangoScopeMiddleware',
    # ... other middleware
]

Installation Comparison

Feature No-Code (scope-run) Code-Based
Code changes required None 2 lines minimum
LLM tracking ✅ Automatic ✅ Automatic
Session correlation ✅ Automatic (FastAPI/Flask/Django) Manual middleware
Custom configuration Via env vars Full Python API
Best for Quick start, CI/CD, ops teams Developers wanting control

CLI Usage

# Show version
scope-run --version

# Show help
scope-run --help

# Run with debug logging
scope-run --debug python app.py

# Dry run (show what would be executed)
scope-run --dry-run uvicorn main:app

Environment Variables

Variable Required Description
SCOPE_API_KEY Yes Your Scope Analytics API key
SCOPE_ENDPOINT No Custom API endpoint
SCOPE_DEBUG No Set to 'true' for debug logging
SCOPE_ENVIRONMENT No Environment tag on every event (default: production). When it is unset or production, events sent with a key you created for Staging or Development (Setup → Keys) are tagged with that key's environment instead
SCOPE_CAPTURE_HTTP No Capture outbound calls to other services (default: on; false turns it off)
HTTPS_PROXY / NO_PROXY / SSL_CERT_FILE No Honoured for the SDK's own connection to Scope (read from the environment only)

Configuration (Code-Based)

scope = ScopeAnalytics(
    api_key="sk_live_...",              # Required: Your secret API key
    endpoint="https://api.scopeai.dev", # Optional: API endpoint
    auto_patch=True,                    # Optional: Auto-patch LLM libraries (default: True)
    batch_size=10,                      # Optional: Events per batch (default: 10)
    batch_timeout_seconds=5,            # Optional: Max wait time (default: 5)
    capture_http=True,                  # Optional: Capture outbound calls (default: True,
                                        #   independent of auto_patch)
    debug=False,                        # Optional: Enable debug logging
    environment="production",           # Optional: Environment name
)

Framework Support Matrix

Framework Auto-Injection Session Correlation How
FastAPI ✅ Automatic ✅ Full Patches FastAPI.__init__
Starlette ✅ Automatic ✅ Full Patches Starlette.__init__
Flask ✅ Automatic ✅ Full Patches Flask.__init__
Django ✅ Automatic ✅ Full Modifies settings.MIDDLEWARE
Other ASGI ⚠️ Manual ✅ With 1 line Add ScopeSessionMiddleware
Other WSGI ⚠️ Manual ✅ With 1 line Call ScopeContext.set_session_id()
No framework ⚠️ Manual ✅ With 1 line Call ScopeContext.set_session_id()

Manual Session Correlation (For Other Frameworks)

# Option A: ASGI middleware (for ASGI frameworks)
from scope_analytics import ScopeSessionMiddleware
app = ScopeSessionMiddleware(app)

# Option B: Manual context (for any framework)
from scope_analytics import ScopeContext

def my_request_handler(request):
    # Extract session from header and set context
    ScopeContext.set_session_id(request.headers.get('X-Scope-Session-ID'))

    # Your code - LLM calls will now have session_id attached
    response = openai.chat.completions.create(...)

Key Point: Even without middleware, LLM tracking STILL WORKS. The middleware is only needed for correlating backend events with frontend sessions via X-Scope-Session-ID.

Frontend SDK

Add the frontend SDK to link user interactions with backend LLM calls:

<script src="https://cdn.scopeai.dev/v1/sdk.js?token=pk_live_your_public_key" async></script>

The frontend SDK automatically:

  • Tracks clicks, page views, form submissions
  • Generates session IDs (stored in localStorage)
  • Sends X-Scope-Session-ID header with API requests

Comparison with Industry Tools

Feature Scope (scope-run) DataDog (ddtrace-run) New Relic
No code changes ✅ ✅ ✅
Env var config ✅ SCOPE_API_KEY ✅ DD_API_KEY ✅ NEW_RELIC_LICENSE_KEY
Works with uvicorn ✅ ✅ ✅
Works with gunicorn ✅ ✅ ✅
LLM call capture ✅ ❌ ❌
Session correlation ✅ ❌ ❌
Debug mode ✅ --debug ✅ --info ✅

Full Documentation

See SDK Installation Guide for complete documentation including:

  • Detailed configuration options
  • Troubleshooting guide
  • Complete example applications
  • Verification steps

License

MIT

Metadata

Release files for scope-analytics 0.1.6

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

Source distribution (sdist)

Source distribution for scope-analytics 0.1.6
File Size Uploaded Provenance Actions
scope_analytics-0.1.6.tar.gz 180.7 kB With provenance Details for scope_analytics-0.1.6.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for scope-analytics 0.1.6
File Interpreter ABI Platform Actions
scope_analytics-0.1.6-py3-none-any.whl Python 3 none any Details for scope_analytics-0.1.6-py3-none-any.whl

Total release size: 291.4 kB

Release files / scope_analytics-0.1.6.tar.gz

Download URL scope_analytics-0.1.6.tar.gz
Size 180.7 kB
Tags Source
SHA-256 checksum
How to use checksums
d2fb814e322550adee260e1340aaa6a332bc6c5841099d2c1f92221d26e1baff
BLAKE2b-256 checksum
How to use checksums
9713e97cb2994ed9d0910d431831d2276b177a6398d23903e09ef96570117ea6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.

Transparency log

Release files / scope_analytics-0.1.6-py3-none-any.whl

Download URL scope_analytics-0.1.6-py3-none-any.whl
Size 110.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
528dfc7381502d6cb2df73362bca4836598101059f14d291cba328eabc884534
BLAKE2b-256 checksum
How to use checksums
2b606292e75f4267835df2bec152dbe6b8ad92e420090f909f1cbcc07717cb4e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.

Transparency log

Security for scope-analytics 0.1.6

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.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for scope_analytics-0.1.6.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 3, 2026.

Transparency log

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.

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