Reference
Python SDK API
Classes, methods, parameters, return values, configuration, and integrations for the Teml Python SDK.
This is the application-developer API for teml 0.1.x. The SDK supports Python 3.11+, synchronous
and asynchronous frameworks, OpenTelemetry signals, identity, diagnostic events, feature flags, and
LLM wrappers.
Use ingest:write for traces, metrics, logs, and errors. Add analytics:write for identity, groups,
events, and flag exposure events; add flags:read for flag decisions.
Create and run TemlClient
import os
import teml
client = teml.TemlClient(
api_key=os.environ['TEML_API_KEY'],
service_name='orders-api',
)
client.start()
try:
run_application()
finally:
client.stop()
| API | Parameters | Returns | Behavior |
|---|---|---|---|
TemlClient(...) |
core options below or config=TemlConfig(...) |
TemlClient |
Builds an unstarted client. A supplied config takes precedence over every other constructor argument. |
start() |
— | same TemlClient |
Validates configuration, starts transports, and installs the optional standard-library logging bridge. Repeated calls are safe. |
stop() |
— | None |
Removes the log bridge and flushes/stops telemetry providers. Repeated calls are safe. |
is_running |
property | bool |
Whether the client currently accepts telemetry. |
| context manager | with TemlClient(...) as client |
client | Starts on entry, captures an exception leaving the block, then stops. |
flush(timeout_ms=None) |
optional milliseconds | bool |
Forces all active signal providers to flush within the deadline. |
config |
property | TemlConfig |
Active configuration. Contains the API key; do not log or serialize it. |
stats |
property | dict[str,int] |
Counters for spans, metrics, logs, and captured errors. |
Keep one client per process. Framework middleware supplies request-scoped identity and spans; do not construct a client per request.
Constructor and TemlConfig
The constructor directly accepts the most common fields. TemlConfig exposes the complete set.
| Field | Type | Default/environment | Purpose |
|---|---|---|---|
api_key |
str |
TEML_API_KEY; required |
Project-scoped Teml API key. |
service_name |
str |
OTEL_SERVICE_NAME; required |
Logical service name. |
service_version |
str |
OTEL_SERVICE_VERSION; 0.0.0 |
Deployed version. |
environment |
str |
TEML_ENVIRONMENT; development |
Deployment environment. |
endpoint |
str |
TEML_ENDPOINT; https://api.teml.io |
Base API/OTLP URL. |
protocol |
http | grpc |
OTEL_EXPORTER_OTLP_PROTOCOL; http |
OTLP transport. |
insecure |
bool |
OTEL_EXPORTER_OTLP_INSECURE; False |
Disable TLS; local development only. |
enable_traces, enable_metrics, enable_logs |
bool |
corresponding TEML_ENABLE_*; True |
Enable each signal pipeline. |
trace_sample_rate |
float |
OTEL_TRACES_SAMPLER_ARG; 0.1 |
Trace sampling in the inclusive range 0–1. |
error_sample_rate |
float |
TEML_ERROR_SAMPLE_RATE; 1 |
Non-fatal captured-error sampling. |
batch_timeout_ms |
int |
OTEL_BSP_SCHEDULE_DELAY; 5000 |
Maximum batching delay. |
batch_size |
int |
OTEL_BSP_MAX_EXPORT_BATCH_SIZE; 512 |
Maximum export batch size. |
max_queue_size |
int |
OTEL_BSP_MAX_QUEUE_SIZE; 2048 |
Queue capacity; must be at least batch_size. |
export_timeout_ms |
int |
OTEL_BSP_EXPORT_TIMEOUT; 30000 |
Per-export timeout. |
shutdown_timeout_ms |
int |
OTEL_BSP_SHUTDOWN_TIMEOUT; 5000 |
Graceful shutdown deadline. |
metric_export_interval_ms |
int |
OTEL_METRIC_EXPORT_INTERVAL; 60000 |
Metric push interval. |
bridge_stdlib_logging |
bool |
TEML_BRIDGE_STDLIB_LOGGING; True |
Export normal logging records through this client. |
log_level |
str |
TEML_LOG_LEVEL; info |
Minimum bridged log level. |
attach_stack_trace |
bool |
TEML_ATTACH_STACK_TRACE; True |
Attach exception frames. |
max_stack_trace_frames |
int |
TEML_MAX_STACK_TRACE_FRAMES; 50 |
Maximum exception frames. |
instrument_http_clients |
bool |
TEML_INSTRUMENT_HTTP_CLIENTS; False |
Globally instrument requests/httpx. Opt in only for trusted traffic. |
propagate_trace_header_urls |
tuple[str,...] |
TEML_PROPAGATE_TRACE_HEADER_URLS; empty |
Absolute trusted prefixes allowed to receive trace/identity headers. |
trust_incoming_identity |
bool |
TEML_TRUST_INCOMING_IDENTITY; False |
Adopt inbound Teml identity baggage. Enable only behind a sanitizing authenticated gateway. |
resource_attributes |
dict[str,str] |
OTEL_RESOURCE_ATTRIBUTES; empty |
Extra resource attributes. |
headers |
dict[str,str] |
OTEL_EXPORTER_OTLP_HEADERS; empty |
Extra export headers. |
debug |
bool |
TEML_DEBUG; False |
SDK diagnostic logging. |
TemlConfig.from_env(**overrides) resolves environment variables and applies explicit overrides.
validate() raises on missing/invalid configuration. get_endpoint_for_signal(signal),
get_headers(), and get_log_level() support custom integrations.
Traces, metrics, logs, and AI operations
| Method/property | Parameters | Returns | Behavior |
|---|---|---|---|
tracer |
property | OTel Tracer |
Underlying tracer for advanced use. |
meter |
property | OTel Meter |
Underlying meter for advanced use. |
start_span(name, **kwargs) |
name; arguments forwarded to Tracer.start_span |
OTel Span |
Starts a span or returns a non-recording span before startup. Use it as a context manager or end it. |
record_metric(name, value, labels=None) |
name; float; string labels | None |
Creates a gauge and records one value. |
log_event(level, message, attrs=None) |
debug/info/warn/warning/error/fatal; body; attributes |
None |
Emits a structured OTLP log; no-op when logs are disabled. |
record_llm_call(model, **options) |
required model; options below | None |
Emits one completed gen_ai client span. |
record_tool_call(name, **options) |
required tool name; options below | None |
Emits one completed internal tool span. |
start_agent_run(agent, **options) |
agent; optional IDs | context manager yielding Span |
Creates an agent span and makes it current so nested LLM/tool calls become children. |
record_llm_call accepts response_model, provider, operation, token counts, cost_usd,
finish_reason, is_error, start_time, and end_time. messages and output opt into sensitive
content. record_tool_call accepts tool_type, call_id, conversation_id, agent_name,
is_error, arguments, and result; arguments/results are also opt-in content.
Starting the client bridges standard-library logging by default. Those records inherit active OTel
trace context; prefer ordinary logger.info(...) inside application code.
Errors, messages, users, and breadcrumbs
| Method | Parameters | Returns | Behavior |
|---|---|---|---|
capture_error(error, *, user=None, tags=None, extra=None, fingerprint=None, level='error') |
exception and optional context | str |
Captures the exception and returns its ID; '' before startup or when sampled out. fatal bypasses sampling. |
capture_message(message, level='error', *, user=None, tags=None, extra=None) |
message, severity, optional context | str |
Captures a message and returns its ID. |
add_breadcrumb(category, message, *, level='info', data=None) |
breadcrumb fields | None |
Adds to the 100-entry trail attached atomically to the next error. |
set_user(user) |
User |
None |
Sets global error user context. |
get_user() |
— | User | None |
Returns request-local user first, then global user. |
clear_user() |
— | None |
Clears global error user context. |
User fields are id, email, username, ip_address, segment, and data. Use
set_context_user(user)/get_context_user() for an async request-local error user. The cross-signal
person identity remains distinct_id, managed separately below.
Identity and groups
| API | Parameters | Returns | Behavior |
|---|---|---|---|
client.identify(distinct_id, properties=None) |
stable ID; person properties | None |
Switches shared identity and performs best-effort canonical-person sync. Raises ValueError for an empty ID. |
client.group(group_type, group_key, properties=None) |
type/key; group properties | None |
Associates the person with an account and sends a membership assertion. Empty type/key is ignored. |
client.reset() |
— | None |
Logout: creates a new anonymous identity and clears global user context. |
shared_identity() |
— | IdentityManager |
Returns the process-wide identity holder shared by signals and analytics. |
set_context_distinct_id(id) |
stable ID | DistinctIDScope |
Sets async-safe request identity; reset with the returned token. |
reset_context_distinct_id(token) |
scope token | None |
Restores the prior request identity. |
resolve_distinct_id_for(context=None, identity=None) |
optional OTel context/manager | str |
Resolves request scope, baggage, then shared identity. |
adopt_distinct_id_from_baggage(context=None) |
OTel context | DistinctIDScope | None |
Promotes trusted baggage into request scope. Never call directly on untrusted public input. |
IdentityManager exposes get_distinct_id, get_anon_id, is_identified, identify, group,
get_groups, and reset. Use the module-level helpers for request scope.
Diagnostic events: AnalyticsClient
events = teml.AnalyticsClient(
endpoint='https://api.teml.io',
api_key=os.environ['TEML_API_KEY'],
)
| API | Parameters | Returns | Behavior |
|---|---|---|---|
AnalyticsClient(endpoint, api_key, flush_at=20, flush_interval_s=5, sender=None) |
connection, batching, optional custom sender | client | Starts an optional daemon flush worker. |
capture(event, properties=None, *, distinct_id=None, session_id=None, timestamp=None) |
event and optional overrides | None |
Queues an event. Without an explicit ID it uses shared identity. |
identify(distinct_id, properties=None, *, anon_distinct_id=None) |
ID; properties; optional alias | None |
Queues identify, switches shared identity, and flushes. |
group(group_type, group_key, properties=None) |
group and properties | None |
Records shared membership and queues $groupidentify. |
flush() |
— | None |
Synchronously sends the current queue; transient failures are requeued. |
stop() |
— | None |
Stops the worker and flushes. Further calls raise a closed-client error. |
reset() |
— | None |
Rotates shared anonymous identity. |
Feature flags: teml.feature_flags.FeatureFlags
Construct with endpoint, api_key, a capture(event, properties, distinct_id) callback, and
optional bootstrap response. The key needs flags:read; the callback normally sends exposure events
using analytics:write.
| Method | Parameters | Returns | Behavior |
|---|---|---|---|
reload(distinct_id, person_properties=None, groups=None) |
person and targeting context | None |
Calls /api/v1/decide and replaces cached decisions. Network/API failures raise. |
get_feature_flag(key, distinct_id) |
key and ID | decision or None |
Returns a decision and emits one deduplicated exposure. |
is_feature_enabled(key, distinct_id) |
key and ID | bool |
True for True or a non-empty string variant. |
get_feature_flag_payload(key) |
key | any | Returns the cached payload. |
get_all_flags() |
— | dict |
Returns a copy of cached flags. |
had_evaluation_errors() |
— | bool |
Whether the latest evaluation used a fallback. |
reset() |
— | None |
Clears exposure dedup after identity changes. |
Framework and provider integrations
| Integration | Constructor/function | Behavior |
|---|---|---|
| FastAPI/Starlette | TemlFastAPIMiddleware(app, client=None, skip_paths=None, trust_incoming_identity=False) |
ASGI request spans, status/duration, errors, and optional trusted identity. |
| Flask | TemlFlaskMiddleware(app, client, skip_paths=None, trust_incoming_identity=False) |
Registers request hooks for spans, errors, and optional trusted identity. |
| Django | TemlDjangoMiddleware in MIDDLEWARE with a TEML settings mapping |
Creates request spans and uses config-level trust_incoming_identity. |
| Celery | TemlCeleryIntegration(app, client) |
Registers task lifecycle signals, traces tasks, and captures failures. |
| OpenAI | wrap_openai(client, teml_client, capture_content=False) |
Instruments sync/async non-streaming chat completions in place and returns the same client. |
| Anthropic | wrap_anthropic(client, teml_client, capture_content=False) |
Instruments sync/async non-streaming messages in place and returns the same client. |
Streaming provider calls pass through without automatic LLM spans. Telemetry errors never replace a provider exception. Content capture is disabled by default.
Authentication and lower-level utilities
These exports support custom middleware and integrations. Application code should generally use
TemlClient and AnalyticsClient.
| API/type | Parameters or fields | Returns/behavior |
|---|---|---|
validate_api_key(key) |
string | None; raises InvalidAPIKeyError for an unsupported key shape. |
teml.auth.is_api_key_format(value) |
string | Boolean shape check without throwing. |
mask_api_key(key) |
string | Log-safe prefix plus last four characters; never usable as a credential. |
User(...) |
id, email, username, ip_address, segment, data |
Error-user data class; to_otel_attributes() returns enduser.*/user.data.* attributes. |
set_context_user(user) |
User or None |
Sets async request-local error-user context; call with None when the scope ends. |
get_context_user() |
— | Request-local User or None. |
Breadcrumb(timestamp, category, message, level, data=None) |
canonical breadcrumb fields | to_dict() returns the JSON-compatible wire shape, omitting empty data. |
BreadcrumbBuffer() |
fixed capacity 100 | Thread-safe add, snapshot, serialize, drain, and clear; drain serializes and clears atomically. |
ErrorLevel |
DEBUG, INFO, WARNING, ERROR, FATAL |
String severity constants. |
ErrorOptions(...) |
user, tags, extra, level, fingerprint |
Data class for custom error-recording integrations. Normal capture calls accept these fields directly. |
IdentityManager() |
— | Thread-safe holder with get_distinct_id, get_anon_id, is_identified, observability_distinct_id, identify, group, get_groups, and reset. Use the module-level functions for request scope. |
shared_identity() |
— | Process-wide manager shared by signals and diagnostic events. |
BAGGAGE_DISTINCT_ID_KEY |
constant | The W3C baggage member name teml.distinct_id. |
DistinctIDScope |
opaque token | Returned by set_context_distinct_id; pass it to reset_context_distinct_id. |
teml.__version__ reports the installed package version. Lower-level stack/error serializer and
transport modules are implementation APIs and may change; use the public client methods above.