Metadata-Version: 2.5
Name: samco-observe-sdk
Version: 0.1.0
Summary: Samco OpenTelemetry distro: standard OpenTelemetry auto-instrumentation for API and AI (agents, LLM calls, tools) with Samco defaults, redaction and log correlation.
Project-URL: Documentation, https://claude.ai/artifact/SxLcLwdCkKnhTqarXrA5L7
Author: Samco Middleware Team
License: Proprietary
Keywords: genai,llm,metrics,observability,opentelemetry,samco,tracing
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.10
Requires-Dist: opentelemetry-api<1.46,>=1.45.0
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc<1.46,>=1.45.0
Requires-Dist: opentelemetry-exporter-otlp-proto-http<1.46,>=1.45.0
Requires-Dist: opentelemetry-instrumentation-logging<0.67,>=0.66b0
Requires-Dist: opentelemetry-instrumentation<0.67,>=0.66b0
Requires-Dist: opentelemetry-sdk<1.46,>=1.45.0
Requires-Dist: opentelemetry-semantic-conventions<0.67,>=0.66b0
Requires-Dist: opentelemetry-util-genai<1.4,>=1.3b0
Provides-Extra: ai
Requires-Dist: httpx>=0.27; extra == 'ai'
Requires-Dist: opentelemetry-instrumentation-anthropic<0.64,>=0.63; extra == 'ai'
Requires-Dist: opentelemetry-instrumentation-langchain<0.64,>=0.63; extra == 'ai'
Requires-Dist: opentelemetry-instrumentation-mcp<0.64,>=0.63; extra == 'ai'
Requires-Dist: opentelemetry-instrumentation-openai-v2<3,>=2.4b0; extra == 'ai'
Provides-Extra: aiohttp
Requires-Dist: opentelemetry-instrumentation-aiohttp-client<0.67,>=0.66b0; extra == 'aiohttp'
Provides-Extra: all
Requires-Dist: httpx>=0.27; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-aiohttp-client<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-anthropic<0.64,>=0.63; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-asyncpg<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-celery<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-confluent-kafka<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-django<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-fastapi<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-flask<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-httpx<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-kafka-python<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-langchain<0.64,>=0.63; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-mcp<0.64,>=0.63; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-openai-v2<3,>=2.4b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-pymysql<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-redis<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-requests<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-sqlalchemy<0.67,>=0.66b0; extra == 'all'
Requires-Dist: opentelemetry-instrumentation-system-metrics<0.67,>=0.66b0; extra == 'all'
Provides-Extra: anthropic
Requires-Dist: opentelemetry-instrumentation-anthropic<0.64,>=0.63; extra == 'anthropic'
Provides-Extra: asyncpg
Requires-Dist: opentelemetry-instrumentation-asyncpg<0.67,>=0.66b0; extra == 'asyncpg'
Provides-Extra: celery
Requires-Dist: opentelemetry-instrumentation-celery<0.67,>=0.66b0; extra == 'celery'
Provides-Extra: confluent-kafka
Requires-Dist: opentelemetry-instrumentation-confluent-kafka<0.67,>=0.66b0; extra == 'confluent-kafka'
Provides-Extra: dev
Requires-Dist: asgi-correlation-id>=4.3.0; extra == 'dev'
Requires-Dist: fastapi>=0.110; extra == 'dev'
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: opentelemetry-instrumentation-fastapi<0.67,>=0.66b0; extra == 'dev'
Requires-Dist: opentelemetry-instrumentation-httpx<0.67,>=0.66b0; extra == 'dev'
Requires-Dist: opentelemetry-instrumentation-requests<0.67,>=0.66b0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Provides-Extra: django
Requires-Dist: opentelemetry-instrumentation-django<0.67,>=0.66b0; extra == 'django'
Provides-Extra: fastapi
Requires-Dist: opentelemetry-instrumentation-fastapi<0.67,>=0.66b0; extra == 'fastapi'
Provides-Extra: flask
Requires-Dist: opentelemetry-instrumentation-flask<0.67,>=0.66b0; extra == 'flask'
Provides-Extra: httpx
Requires-Dist: opentelemetry-instrumentation-httpx<0.67,>=0.66b0; extra == 'httpx'
Provides-Extra: kafka
Requires-Dist: opentelemetry-instrumentation-kafka-python<0.67,>=0.66b0; extra == 'kafka'
Provides-Extra: langchain
Requires-Dist: opentelemetry-instrumentation-langchain<0.64,>=0.63; extra == 'langchain'
Provides-Extra: llm-gateway
Requires-Dist: httpx>=0.27; extra == 'llm-gateway'
Provides-Extra: mcp
Requires-Dist: opentelemetry-instrumentation-mcp<0.64,>=0.63; extra == 'mcp'
Provides-Extra: openai
Requires-Dist: opentelemetry-instrumentation-openai-v2<3,>=2.4b0; extra == 'openai'
Provides-Extra: pymysql
Requires-Dist: opentelemetry-instrumentation-pymysql<0.67,>=0.66b0; extra == 'pymysql'
Provides-Extra: redis
Requires-Dist: opentelemetry-instrumentation-redis<0.67,>=0.66b0; extra == 'redis'
Provides-Extra: requests
Requires-Dist: opentelemetry-instrumentation-requests<0.67,>=0.66b0; extra == 'requests'
Provides-Extra: sqlalchemy
Requires-Dist: opentelemetry-instrumentation-sqlalchemy<0.67,>=0.66b0; extra == 'sqlalchemy'
Provides-Extra: system
Requires-Dist: opentelemetry-instrumentation-system-metrics<0.67,>=0.66b0; extra == 'system'
Provides-Extra: web
Requires-Dist: opentelemetry-instrumentation-fastapi<0.67,>=0.66b0; extra == 'web'
Requires-Dist: opentelemetry-instrumentation-httpx<0.67,>=0.66b0; extra == 'web'
Requires-Dist: opentelemetry-instrumentation-redis<0.67,>=0.66b0; extra == 'web'
Requires-Dist: opentelemetry-instrumentation-requests<0.67,>=0.66b0; extra == 'web'
Requires-Dist: opentelemetry-instrumentation-sqlalchemy<0.67,>=0.66b0; extra == 'web'
Requires-Dist: opentelemetry-instrumentation-system-metrics<0.67,>=0.66b0; extra == 'web'
Description-Content-Type: text/markdown

# 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

```bash
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:

```bash
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`:

```python
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

```python
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 app with its **own** gateway client, tool runner and agent loop gets the same telemetry with one line each:

```python
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

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

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