Skip to main content

samco-observe-sdk

Samco's OpenTelemetry distro for Python services. One install gives every app traces, metrics and (optionally) logs for its API calls and its AI work (agents, LLM calls, tool calls), sent to the Samco Collector.

It does not re-implement OpenTelemetry. All the work is done by standard OpenTelemetry packages; this package plugs into OTel's own extension points (opentelemetry_distro, opentelemetry_configurator, opentelemetry_traces_exporter) to add Samco defaults and a few Samco-only extras.

Need Done by (OpenTelemetry) Samco adds
Start-up, zero-code mode opentelemetry-instrument, auto_instrumentation.initialize() samco-observe run = the same launcher with the Samco distro selected
Settings standard OTEL_* variables default values (team values always win)
Finding libraries to instrument opentelemetry_instrumentor entry points, opentelemetry-bootstrap nothing
Tracer / meter / logger providers, OTLP export, batching, retry OTel SDK configurator + OTLP exporters redaction in front of the trace exporter
HTTP / DB / cache / queue spans and metrics opentelemetry-instrumentation-* packages FastAPI send/receive noise spans off by default
Trace ids on log records opentelemetry-instrumentation-logging (otelTraceID, otelSpanID) turned on without changing the log format
GenAI spans + metrics (agent, chat, tool, embeddings) opentelemetry-util-genai, openai-v2, OpenLLMetry instrumentations @agent / @tool decorators, LlmGatewayClient (Samco LLM gateway over raw httpx)
Samco log message_id ↔ trace response-header capture (OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_SERVER_RESPONSE) copies it to samco.message_id on every span
Secret removal Collector redaction processor (second line of defence) in-app redaction of PAN, JWT, bearer tokens, Aadhaar, card numbers, secret keys

Requires Python 3.10+ (the OpenTelemetry 1.45 line).


1. Install

pip install "samco-observe-sdk[fastapi,httpx,llm-gateway]"
# or let OpenTelemetry find what your app uses and install those instrumentations:
pip install samco-observe-sdk && opentelemetry-bootstrap -a install

Extras (each is just the official OpenTelemetry package): fastapi flask django requests httpx aiohttp sqlalchemy pymysql asyncpg redis kafka confluent-kafka celery system openai anthropic langchain mcp llm-gateway, bundles web, ai, all.

2. Run

Zero code (recommended) - put samco-observe run in front of the start command:

export OTEL_SERVICE_NAME=risk-engine
export SAMCO_OBSERVE_ENV=prod
export OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
samco-observe run uvicorn app.main:app --host 0.0.0.0 --port 8080

samco-observe run is exactly OpenTelemetry's opentelemetry-instrument with OTEL_PYTHON_DISTRO=samco. Using opentelemetry-instrument directly works the same.

One line of code - in a Samco FastAPI main.py:

from logs.logging_config import setup_logging
setup_logging()

import samco_observe
samco_observe.init()            # before FastAPI() is created; no-op when started by `samco-observe run`

from fastapi import FastAPI
app = FastAPI()

init() keyword shortcuts: service_name, environment, endpoint, protocol, sample_ratio, logs_exporter, disabled_instrumentations, capture_ai_content (True records prompts/answers on the AI spans), enabled.

3. AI

from samco_observe.ai import LlmGatewayClient, agent, tool, get_telemetry_handler

llm = LlmGatewayClient.from_config(config.llm_gateway)      # LlmGatewayConfig from the Samco standard
llm.chat_completion([{"role": "user", "content": "Hello"}])  # -> span "chat openai/gpt-4.1" + token metrics

@tool("get_holdings")
def get_holdings(client_id): ...                              # -> span "execute_tool get_holdings"

@agent("portfolio-advisor")
def advise(question): ...                                     # -> span "invoke_agent portfolio-advisor"

answer = llm.orchestrate(messages, TOOLS, tool_executor, agent_name="portfolio-advisor")

# anything else: util-genai's handler directly
with get_telemetry_handler().inference("openai", request_model="openai/gpt-4.1") as call:
    call.input_tokens, call.output_tokens = 120, 30

Calls through the OpenAI SDK (gateway Option A) are recorded by OTel's openai-v2 instrumentation ([openai] extra); Anthropic / LangChain / MCP by the OpenLLMetry instrumentations ([anthropic], [langchain], [mcp]).

An agent framework that runs the loop itself and reports through hooks (the Hermes worker) uses samco_observe.ai.turns from its hooks: turns.start(session, name, input=..., carrier=request_headers) when a turn starts, turns.llm(session, request) around each LLM request, turns.tool(session, name, args) around each tool, turns.finish(session, output=...) when it ends (see ai/turns.py).

An app with its own gateway client, tool runner and agent loop gets the same telemetry with one line each:

from samco_observe.ai import invoke_agent, llm_call, traced_tool_executor

@llm_call(server_url=lambda: cfg.base_url, default_model=lambda: cfg.default_model)
def chat_completion(messages, tools=None, model=None, temperature=None, max_tokens=None):
    ...                                   # returns the OpenAI-style response dict

tool_executor = traced_tool_executor(tool_executor)   # (name, arguments) -> result
with invoke_agent("support-agent", model="openai/gpt-4.1"):
    ...                                   # the turn: LLM calls + tool calls

Prompts, answers and tool arguments are not recorded unless init(capture_ai_content=True) or OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=SPAN_ONLY (util-genai's switch). The Samco redaction still masks PAN, Aadhaar, cards and tokens in them. Keep it off in prod unless agreed.

Business metrics use the plain OTel API: metrics.get_meter("risk-engine").create_counter("samco.orders.placed").add(1, {"segment": "FNO"}).

4. Settings

Everything is a standard OpenTelemetry variable. The Samco distro only fills in defaults:

Variable Samco default Meaning
OTEL_SERVICE_NAME (none, set it) name shown everywhere
SAMCO_OBSERVE_ENV (none) shortcut for OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=<env>
OTEL_EXPORTER_OTLP_ENDPOINT OTel default http://localhost:4317 Collector address
OTEL_EXPORTER_OTLP_PROTOCOL grpc use http/protobuf for pre-fork servers (gunicorn)
OTEL_EXPORTER_OTLP_COMPRESSION gzip
OTEL_TRACES_EXPORTER samco_otlp OTLP + Samco redaction
OTEL_METRICS_EXPORTER / OTEL_LOGS_EXPORTER otlp / otlp app logs go with the traces; OTEL_LOGS_EXPORTER=none turns them off
OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE delta counts per export; the portal just adds them up
OTEL_BSP_SCHEDULE_DELAY / _MAX_EXPORT_BATCH_SIZE / _MAX_QUEUE_SIZE 2000 / 512 / 2048 send every 2 s or 512 spans; full queue drops, never blocks
OTEL_METRIC_EXPORT_INTERVAL 15000
OTEL_TRACES_SAMPLER / _ARG parentbased_traceidratio / 1.0 e.g. 0.1 keeps 10 % of traces (metrics stay exact)
OTEL_SEMCONV_STABILITY_OPT_IN http stable HTTP names (http.server.request.duration, http.route)
OTEL_EXPERIMENTAL_RESOURCE_DETECTORS otel,host no process detector (its command line can hold secrets)
OTEL_PYTHON_DISABLED_INSTRUMENTATIONS e.g. redis,kafka; * = none
OTEL_SDK_DISABLED true = no telemetry at all
SAMCO_OBSERVE_ENABLED true false = sets the two switches above
SAMCO_OBSERVE_REDACT_FIELDS extra attribute keys to blank, comma separated
SAMCO_OBSERVE_REDACT_PATTERNS extra regexes, separated by ;;
SAMCO_OBSERVE_LINK_MESSAGE_ID true record the Samco message_id on spans
SAMCO_OBSERVE_ASGI_INTERNAL_SPANS false true keeps FastAPI http send/receive spans

Check what a running environment resolves to: samco-observe doctor --send-test-span.

5. Safety

  • Start-up failures log one warning; the app runs without telemetry.
  • Export runs on OTel's background thread with a bounded queue: never blocks a request, drops data rather than memory when the Collector is down.
  • Secrets are scrubbed in the app (keys like password, authorization, x-api-key; values that are PAN, JWT, bearer tokens, Luhn-valid card numbers, Verhoeff-valid Aadhaar) and again by the Collector's redaction processor.

6. Known limits

  • A request that ends in an unhandled exception (500 built by Starlette outside CorrelationIdMiddleware) has no X-Request-ID, so its trace has no message_id.
  • GenAI semantic conventions and util-genai are still "development" upstream; names may change between OTel releases. The pins in pyproject.toml keep a tested set.
  • gRPC export + pre-fork servers: prefer OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf with gunicorn.

7. Develop

uv venv && uv pip install -e ".[dev]"
pytest

Example service: examples/samco_fastapi_app/ (API + agent + tools + fake LLM gateway). Publishing: see PUBLISHING.md.

Metadata

Release files for samco-observe-sdk 0.1.1

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

Source distribution (sdist)

Source distribution for samco-observe-sdk 0.1.1
File Size Uploaded Provenance Actions
samco_observe_sdk-0.1.1.tar.gz 27.6 kB Without provenance Details for samco_observe_sdk-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for samco-observe-sdk 0.1.1
File Interpreter ABI Platform Actions
samco_observe_sdk-0.1.1-py3-none-any.whl Python 3 none any Details for samco_observe_sdk-0.1.1-py3-none-any.whl

Total release size: 60.7 kB

Release files / samco_observe_sdk-0.1.1.tar.gz

Download URL samco_observe_sdk-0.1.1.tar.gz
Size 27.6 kB
Tags Source
SHA-256 checksum
How to use checksums
485dcf7909068332de5c5fd3fda784a8a38d1bc08af445e85118bc9140133d1e
BLAKE2b-256 checksum
How to use checksums
70885b750cae82a2d2be92c0d6bda23768610687f4507f0cb30861a17742dad4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.3

Release files / samco_observe_sdk-0.1.1-py3-none-any.whl

Download URL samco_observe_sdk-0.1.1-py3-none-any.whl
Size 33.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
21ccfed52245bad054a118e6b121b908e2f3c23ad149a91de16a400c4cde3956
BLAKE2b-256 checksum
How to use checksums
260138d692ce8fea789e712d0f33daddb12abee80af6e7df8317bc5a19e034b8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.3

Security for samco-observe-sdk 0.1.1

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.1 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