SDK reference
Configuration and privacy
Every init() option and environment variable of both SDKs with its default, the kill switches, keeping routes, outgoing calls, functions and blocks out of traces, sampling, memory and size limits, shutdown and serverless flushing, health counters, what content, function and HTTP capture record, how secrets are masked, mask hooks, recipes, and the upgrade notes for 0.3.7 and 0.3.6.
Both SDKs are configured by one init() call and a few environment variables. This page lists every option with its default, how to turn the SDK off and keep part of your app out of its traces, how sampling, the size limits and the export pipeline keep the SDK small inside your app, and how spans are sent at shutdown and in serverless functions. It then says what each capture switch records and what it leaves out, explains how secrets are masked and how to edit or drop spans yourself, and ends with recipes, the upgrade notes and fixes. How errors are recorded is on Errors and stack traces. The libraries each SDK traces, and how streamed calls are timed and counted, are on What is traced automatically.
Options of init()
Python takes keyword arguments and TypeScript one options object. Each row names the Python option first and the TypeScript one second; an option of one SDK only says which.
| Option | Default | What it does |
|---|---|---|
subscription_key, subscriptionKey | required | The environment key (tk_live_…) of the Environment the spans belong to. Neither SDK reads it from the environment, so pass it from a variable of your own. |
base_url, baseUrl | hosted | The trace receiver, https://api.syntropylabs.ai by default. Spans are posted to <base_url>/v1/ingest. Change it only for a self-hosted or local receiver. |
api_url, apiUrl | hosted | The platform API, https://api.syntropylabs.ai by default, that Eval(), feedback, prompts, scenario generation and simulation call. EVALKIT_API_URL overrides it. |
service_name, serviceName | "unknown" | The name Traces and Services show for this process. In TypeScript, when another OpenTelemetry provider is already installed, that provider's service.name wins and this is the fallback. |
environment | none | Recorded on every span as evalkit.environment, such as production. Match it to the kind of the Environment the key belongs to. |
app_version, appVersion | none | Your release, recorded on every span as evalkit.app_version. |
device_id, deviceId | none | A default device id for every span. |
debug | off | Python logs each export at DEBUG on the evalkit logger, which shows after logging.basicConfig() with that logger at DEBUG. TypeScript prints each export to the console. Export and key failures are warnings either way. |
max_export_batch_size, maxExportBatchSize | 512 | The most spans in one export request. A request also stays under 4 MiB of JSON before compression, and a larger batch is split. |
scheduled_delay_ms, scheduledDelayMillis | 5000 | How often, in milliseconds, queued spans are sent. A full batch is sent at once. |
max_queue_size, maxQueueSize | 4096 (Python), 2048 (TypeScript) | The most spans waiting to be sent. See Limits and memory for which spans a full queue drops. In TypeScript, OTEL_BSP_MAX_QUEUE_SIZE sets it too. |
max_queue_bytes, maxQueueBytes | 32 MiB | About how much memory the spans waiting to be sent may hold. Past it, the oldest spans that are not model calls are dropped first. |
max_body_bytes, maxBodyBytes | 64 KiB | The most of one HTTP request or response body that is recorded. In Python it also caps streamed response bodies and SQL text. On 0.3.5 and earlier the default is 10 MiB. |
max_value_bytes, maxValueBytes | 16 MiB | The most one value keeps, such as a prompt, a completion, a body or an attribute, in UTF-8 bytes. A longer value keeps its start and its end; see Limits and memory. OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT or OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT lowers it. |
sample_rate, sampleRate | every trace | The share of traces kept, from 0 to 1. Model calls, tool calls and failed spans are always kept. See Sampling. |
function_rate_limit (Python) | 100 | The most spans a second each traced function records; 0 records every call. The calls past it run as usual, untraced, and are counted. |
log_level (Python) | WARNING | The lowest level a log record needs to become a log span, as a level or its name, such as "INFO". EVALKIT_LOG_LEVEL sets it too. See Logs and console output. |
log_rate_limit (Python) | 50 | The most log spans a second. |
captureConsole (TypeScript) | true | Records console.log, console.warn and console.error. See Logs and console output. |
consoleSpanLevel (TypeScript) | "warn" | The lowest console level that becomes a span of its own when no span is active: "info", "warn", "error" or "none". EVALKIT_CONSOLE_SPAN_LEVEL sets it too. |
exitHooks (TypeScript) | true | Sends what is queued on beforeExit, and on SIGTERM and SIGINT when your app has no listener of its own. EVALKIT_EXIT_HOOKS=false turns it off. See Workers and shutdown. |
capture_content, captureContent | on | Records prompts, completions, bodies, headers, tool and function arguments and results, SQL and log text. See Content capture. |
capture_secrets, captureSecrets | off | Turns the secret scrubber off, so credentials are recorded as sent. See Secrets. Python also accepts the older name capture_sensitive_headers. |
capture_stream_bodies (Python) | on | Records the body of a streamed HTTP response read through requests, httpx or aiohttp. See Streaming. |
mask | none | A function that edits or drops each span before it is sent. See Mask hooks. |
export_gzip, exportGzip | on | Gzips each export request. A receiver that refuses compressed requests is sent plain JSON from then on. |
function_tracing (Python) | True | Traces the public module-level functions of your source tree. See Automatic function tracing. |
trace_packages (Python) | none | More top-level packages whose functions are traced, such as ["orders", "billing"], wherever they are installed. |
capture_unhandled (Python) | False | Records uncaught exceptions of the main thread, of other threads and of asyncio tasks and callbacks, then hands each to the hook installed before. See Errors and stack traces. |
captureGlobalErrors (TypeScript) | false | Records uncaught exceptions and unhandled promise rejections as error spans. The process ends as it would without the SDK. See Errors and stack traces. |
in_app_include, inAppInclude | none | What counts as your own code in an exception's frames although its path says otherwise: module prefixes in Python, file substrings or RegExps in TypeScript. |
in_app_exclude, inAppExclude | none | What does not count as your own code in an exception's frames. |
stackTraceLimit (TypeScript) | unset | Raises Error.stackTraceLimit from V8's default of 10, for deeper stacks. It is process-wide, and a limit your app set itself is left alone. |
sourceMaps (TypeScript) | false | Maps stack frames to your TypeScript sources through process.setSourceMapsEnabled(true). |
tracerProvider (TypeScript) | none | An OpenTelemetry tracer provider to add EvalKit's exporter to, instead of the global one. See OpenTelemetry and distributed tracing. |
ignore_routes, ignoreRoutes | none | From 0.3.6, incoming requests answered untraced, with everything their handler records. See Keeping things out of traces. |
ignore_urls, ignoreUrls | none | From 0.3.6, outgoing calls made with no span and no traceparent. See Keeping things out of traces. |
ignore_functions, ignoreFunctions | none | From 0.3.6, functions that function tracing, and an explicit wrapper, leave unwrapped, by qualified name. See Keeping things out of traces. |
trace_health_checks, traceHealthChecks | False | From 0.3.6, traces health and readiness probes like any request. They are left out by default. |
- Call
init()once per process, as early as possible. In Python a second call returns the first client, keeps the first call's options and, from 0.3.6, logs one warning naming the options that do not apply. In TypeScript a second call applies its options, such as a new service name, environment or app version, to every span that starts after it, patches no library twice and, from 0.3.6, warns naming the options that changed. init()never raises or throws. From 0.3.6 it checks its options: an empty key, abase_url(baseUrl) that is not anhttp://orhttps://URL, or a size or rate that is negative or not a number leaves the SDK off, with one warning that names each problem and never the key. TypeScript also accepts a number given as numeric text, such as a value read from the environment.flush()sends what is queued now. Python'sevalkit.flush(timeout=5.0)waits at mosttimeoutseconds and returnsTruewhen the receiver took everything; TypeScript'sawait evalkit.flush(timeoutMs), 5000 by default, resolves totrueorfalsethe same way. Neither raises or rejects, and beforeinit()both answerFalse(false). On 0.3.4 and earlier, Python's raisesRuntimeErrorbeforeinit()and TypeScript's rejects on a failed export; add.catch(() => {})there.- Both SDKs send what is queued as the process ends; see Workers and shutdown. A serverless function is frozen when it returns, so it flushes before; see Serverless and edge runtimes.
- An export that gets no answer, a
429or a5xxis retried 3 times, waiting at most 20 seconds in all, and each request times out after 10 seconds. After 3401or403answers in a row, the SDK stops exporting until the process restarts. Repeated failures open a circuit breaker; see Export failures and health. - Tracing never breaks the call it records: an error inside the SDK is logged at debug level and the call runs as if untraced, an exception from the provider reaches your code unchanged, and the request your code sends is never changed beyond the
traceparentheader.
Turning the SDK off
From 0.3.6, EVALKIT_DISABLED=true, or OpenTelemetry's OTEL_SDK_DISABLED=true, makes init() a no-op without a code change: nothing is recorded, patched or sent. Use it to switch tracing off in one deployment of a shared image, or in tests.
- Python reads
1,true,yesoronin either variable, in any case. TypeScript reads those forEVALKIT_DISABLED, and onlytrueforOTEL_SDK_DISABLED, as OpenTelemetry defines it. - The SDK is off in the same way when
init()finds an option that cannot work, with one warning that names it. Python's decorators then return your function unchanged; TypeScript'sclient.tracingModeis"disabled". evalkit.stats()(TypeScript:getStats()) reportscircuit_state: "disabled"for an SDK that is off, and Python alsoenabled: False.- On 0.3.5 and earlier nothing turns an initialized SDK off: guard
init()on the key variable instead, and the wrappers with it.
Keeping things out of traces
From 0.3.6, four options keep part of your app out of its traces, with the same patterns in both SDKs. What they leave out is left out at every layer: no span, no child span, and no traceparent header on an outgoing call.
| Option | What it leaves out |
|---|---|
ignore_routes, ignoreRoutes | Incoming requests, the way a health probe is: no request span, no x-trace-id or traceparent response header, and nothing the handler records while it answers, model calls, function spans, database queries, logs and outgoing calls included. Every framework middleware applies it, and in TypeScript the Node.js server span too. |
ignore_urls, ignoreUrls | Outgoing calls: no span and no traceparent. Python: requests, httpx, aiohttp, and urllib3 through the OpenTelemetry instrumentation the SDK registers. TypeScript: fetch, node:http and https, and axios. The HTTP client spans of an OpenTelemetry setup of your own are left out of what EvalKit exports too. |
ignore_functions, ignoreFunctions | Functions, by qualified name: module.qualname in Python, such as myapp.cache.get, and the span name in TypeScript, such as OrdersService.findAll. Function tracing leaves them unwrapped, and so does an explicit trace_function or traceFunction: the ignore wins. |
trace_health_checks, traceHealthChecks | Off by default, so health and readiness probes are left out, incoming and outgoing. On, they are traced like any request. |
| Pattern | Matches |
|---|---|
"/metrics" | That path, with or without a trailing slash or a query string. |
"/internal/*", "/static/**" | * is one path segment and ** any number of them, none included. A * inside a segment, as in "/assets/*.map", matches part of it. |
"GET /v1/orders/:id" | A route template: :id, {id} and <int:id> are one segment each. It is matched against the path, and against the framework's route when that is known. A leading method, in any case, restricts the match to that method. |
re.compile(r"^/admin/"), /^\/admin\// | A compiled regex, searched in the path; in ignore_urls, in the full URL. |
lambda info: ..., (info) => ... | A function given the request's method, path and route, or the call's method, url, host and path; a true result leaves it out. One that raises or throws counts as no match, with one warning. |
"api.stripe.com", "*.internal.example.com", "localhost:9000", "https://s3.amazonaws.com/bucket/**" | In ignore_urls: a host, with any scheme, port and path; a host and port; a host and path; or a full URL. In a host, * is one label and ** any number. "/v1/telemetry/**" is a path on any host. |
"myapp.cache.*", "myapp.cache.**" | In ignore_functions: * is one dotted part, so the module's functions, and ** any number, so its classes and submodules too. |
import os
import re
import evalkit
evalkit.init(
subscription_key=os.environ["EVALKIT_SUBSCRIPTION_KEY"],
ignore_routes=["/metrics", "GET /internal/*", "POST /v1/webhooks/:provider", re.compile(r"^/admin/")],
ignore_urls=["metadata.google.internal", "*.internal.example.com"],
ignore_functions=["myapp.cache.*", "myapp.utils.slugify"],
)
@evalkit.untraced
async def refresh_embeddings():
... # nothing inside is recorded
with evalkit.untraced():
run_migrations()- Matching ignores a trailing slash, repeated slashes and the query string. Paths are case-sensitive and methods are not; schemes and hosts are matched in any case, and a URL pattern without a port matches any port.
- An untraced block records nothing: model calls, HTTP calls and their
traceparent, database queries, function spans and log spans are all left out. Python'sevalkit.untracedis a decorator, for sync and async functions and generators, and awithorasync withblock. TypeScript'suntraced(fn)returns a wrapped function andwithoutTracing(() => ...)runs a callback. The scope belongs to the asyncio task or thread in Python, and to the async context in TypeScript, so a request served at the same time is traced as usual, and work started inside stays untraced. Both work beforeinit()and never throw. EVALKIT_IGNORE_ROUTES,EVALKIT_IGNORE_URLSandEVALKIT_IGNORE_FUNCTIONStake comma-separated patterns, added to the ones passed toinit().- A pattern that cannot be read, such as a route without a leading
/or a port that is not a number, is skipped with one warning that names it, and the SDK stays on. Patterns are compiled once, byinit(), and each request, call or function is checked against the list once. - Work an ignored request starts that runs on after its response, such as a background task: Python traces it as usual, as for a health probe; TypeScript keeps it in the request's context, untraced.
- Python's Flask and Litestar middleware decide after the framework has matched the route, so a pattern can use their template syntax, such as
/reports/<int:report_id>. FastAPI, Starlette and Django match it later; a function pattern that readsinfo.routehas it matched then. TypeScript passes the route when the framework has matched it already, as Fastify and NestJS have; elsewhere the raw path decides.
Sampling
Every trace is recorded and sent by default. From 0.3.6, sample_rate (TypeScript: sampleRate) keeps a share of traces, from 0 to 1. The decision is made from the trace id, by the arithmetic of OpenTelemetry's TraceIdRatioBased sampler, so a trace is kept or left out whole, and other services sampling at the same ratio agree. Model calls, tool calls and failed spans are always kept, whatever their trace, because they are what a trace is read for and what an evaluation scores.
evalkit.init(subscription_key=os.environ["EVALKIT_SUBSCRIPTION_KEY"], sample_rate=0.1) # about one trace in ten- Python reads OpenTelemetry's
OTEL_TRACES_SAMPLERandOTEL_TRACES_SAMPLER_ARGwhensample_rateis not passed:traceidratioandparentbased_traceidratiowith their ratio,always_onandalways_off. Any other sampler keeps every trace. - TypeScript reads
EVALKIT_SAMPLE_RATEwhensampleRateis not passed. A trace that arrives sampled from the service that called this one stays sampled. - TypeScript also follows
OTEL_TRACES_SAMPLERandOTEL_TRACES_SAMPLER_ARGwhen it creates the tracer provider itself, as OpenTelemetry does; with a provider of your own, your sampler decides. That sampler decides before a span is recorded and knows nothing of model calls, so it can drop them too; prefersampleRate. - Spans left out are counted:
dropped_sampledin Python'sstats(),sampled_outin TypeScript'sgetStats(). - On 0.3.5 and earlier, Python has no sampling, and TypeScript has only OpenTelemetry's sampler.
Workers and shutdown
In Python:
- A process forked after
init()sends its own spans: gunicorn with--preload,multiprocessingwith theforkstart method, and Celery's prefork pool. The child starts its own export thread with an empty queue; what the parent had queued is the parent's to send. On 0.3.4 and earlier a forked child sends nothing; run gunicorn without--preloadthere. - Workers that import the app themselves, such as uvicorn
--workersand thespawnandforkserverstart methods, callinit()on their own. - As the process ends, what is queued is sent within 3 seconds in all, so an unreachable trace service never holds up a deploy.
evalkit.flush()called by your code keeps the full retry budget. - uvicorn stops a worker on
--workers,--reloador a deploy without running exit handlers.EvalKitMiddlewareflushes on the ASGI lifespan shutdown, before the app reports it complete, and the Litestar and Django (ASGI) middleware do the same. On 0.3.4 and earlier, passon_shutdown=[evalkit.flush]to Litestar.init()also chains SIGTERM and SIGINT: a handler your app installed is called as before, and where the signal's default action would end the process without exit handlers, the queue is sent first. - A Celery prefork child ends through billiard's own exit path, so send its last batch from a
worker_process_shutdownhandler:
from celery.signals import worker_process_shutdown
import evalkit
@worker_process_shutdown.connect
def flush_traces(**_):
evalkit.flush() # the child's last batch, before billiard ends the processIn TypeScript, from 0.3.6:
init()sends what is queued onbeforeExit, when the event loop runs dry, within 5 seconds. A script that ends on its own therefore sends its last spans.process.exit()skipsbeforeExit, so callawait evalkit.flush()before it.- On
SIGTERMandSIGINT, when your app has no listener of its own for the signal, the queue is sent within 3 seconds and the signal then takes its default action, exactly as without the SDK. When your app listens for the signal itself, aoncelistener or a library such as signal-exit included, your handler decides and the SDK steps aside; callawait evalkit.flush()in it. - A flush on the way out abandons at once an export whose receiver already failed to answer, so an unreachable receiver never holds the exit up for long, and the waits between retries never keep a finished process alive.
exitHooks: false, orEVALKIT_EXIT_HOOKS=false, installs none of this. The hooks are installed in the main thread only, not in worker threads.- On 0.3.5 and earlier a Node.js process sends nothing as it ends; call
await evalkit.flush()where it stops.
Serverless and edge runtimes
A serverless function is frozen as soon as it returns, and nothing queued is sent while it is frozen. Each invocation must therefore flush before it returns. In Python, call evalkit.flush() at the end of the handler, with a timeout that fits the invocation. TypeScript has two helpers from 0.3.6:
import evalkit from "syntropylabs-evalkit";
// AWS Lambda: flushes for at most 2 s, and never past the invocation's remaining time
export const handler = evalkit.withLambda(async (event) => {
return { statusCode: 200, body: await answer(event) };
});
// Next.js route handlers and server actions: the flush runs after the response
import { after } from "next/server";
evalkit.flushAfter(after);
// Vercel functions and Cloudflare Workers: hand the flush to waitUntil
evalkit.flushAfter((task) => ctx.waitUntil(task));withLambda(handler, { flushTimeoutMs })works for async and callback-style handlers, and returns the handler's own result or error.flushTimeoutMsis 2000 by default.flushAfter(schedule, timeoutMs)starts a flush, hands it to the scheduler you pass and resolves to whether it succeeded, withintimeoutMs, 5000 by default. It never throws: outside a request, where Next.js'after()throws, the flush runs in the background.- On runtimes without Node's APIs, the Vercel Edge runtime, Cloudflare Workers and browsers, the package's
edge-light,workerdandbrowserexport conditions select a stub with the same API that traces nothing, so importing the SDK there never fails. On 0.3.5 and earlier the import throws there.
In Next.js, start tracing in the Node.js runtime only:
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
const { init } = await import("syntropylabs-evalkit");
init({ subscriptionKey: process.env.EVALKIT_SUBSCRIPTION_KEY!, serviceName: "web" });
}
}Limits and memory
The SDK runs inside your app, so from 0.3.6 everything it holds is bounded, whatever your app hands it and whatever the receiver does. All sizes are UTF-8 bytes, what the receiver counts, so text that is not ASCII is measured at its real size.
| Limit | Default | What happens past it |
|---|---|---|
Spans waiting to be sent: max_queue_size, maxQueueSize | 4096 (Python), 2048 (TypeScript) | Python drops the oldest span that is not a model call. TypeScript drops the new span, unless it is a model call, which takes the place of the oldest span that is not one. Counted as dropped_queue_full. |
Memory of those spans: max_queue_bytes, maxQueueBytes | 32 MiB | The same rule, counted as dropped_bytes_budget. |
One HTTP body: max_body_bytes, maxBodyBytes | 64 KiB | The body is recorded up to the limit. Python's framework middleware keeps no uploads (multipart, octet-stream, media), and its ASGI middleware no server-sent event streams or compressed responses. |
One value: max_value_bytes, maxValueBytes | 16 MiB | The value keeps its start and its end around a …[cut N bytes]… marker, and evalkit.truncated.<field> records its original size in bytes. |
| Function and tool arguments and results | 4096 characters each | Written by a serializer that stops at the cap and ends the value with …, so a huge argument costs no more than a small one. |
| One span | 8 MiB (Python), 16 MiB (TypeScript) | The longest values (in TypeScript, the bodies) are cut the same way, start and end kept, until the span fits. |
- A value is cut in the middle because a conversation's instructions and oldest messages are at the start of a request and its newest messages at the end: a long conversation keeps both. The marker names how many bytes were cut, and
evalkit.truncated.gen_ai.request.bodyholds the size of a cut request body, for example. OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMITorOTEL_ATTRIBUTE_VALUE_LENGTH_LIMITlowers the per-value limit when it is smaller.- Model calls are dropped last, because a trace is read and an evaluation scored for them.
- The serializer that writes arguments, results and bodies never throws: TypeScript writes a BigInt as its digits, a cycle as
"[Circular]"and a getter that throws as"[Unserializable]", and both mask secrets as they write. - On 0.3.5 and earlier, a request body keeps only its first 2 MiB, and Python cuts prompts and completions to 32 KiB, so a long conversation loses its newest messages.
Export failures and health
- Circuit breaker. After 3 export cycles in a row that the receiver did not take (no answer, a
5xxor a429; Python also counts a refused key), the SDK stops sending for 30 seconds and drops spans as they end, which only counts them. Then one small batch, at most 16 spans, tests the receiver: if it is taken, exporting resumes, and if not, the wait doubles, up to 5 minutes. - One export at a time. TypeScript runs one export at a time; spans that end meanwhile wait in the queue.
- Warnings that do not flood your log. The first export failure logs one warning. After it, at most one warning every 5 minutes gives the number of failed exports and dropped spans since the last one. TypeScript cuts each to 200 characters, with no response body or stack; Python cuts a response body in it to 200 characters. A refused subscription key is reported clearly the first time. TypeScript also prints OpenTelemetry's own warnings, at most ten a minute, unless your app registered a
diaglogger of its own. - On 0.3.5 and earlier, every failed export logs its own line, and a receiver that accepts the connection and never answers can hold the TypeScript export queue.
evalkit.stats() in Python and evalkit.getStats() in TypeScript say how recording and exporting are going, for a health check or a debug page. Neither raises or throws, before init() included.
evalkit.stats()
# {"queued": 12, "queued_bytes": 48211, "exported": 5120,
# "dropped_queue_full": 0, "dropped_bytes_budget": 0, "dropped_export_failed": 0,
# "dropped_circuit_open": 0, "dropped_rate_limited": 0, "dropped_sampled": 0,
# "export_failures": 0, "last_error": None, "circuit_state": "closed", "enabled": True}circuit_stateisclosed,open,half_open(a test batch is due) ordisabled(the SDK is off, or stopped after the key was refused).last_erroris the latest failure, at most 200 characters in TypeScript and 400 in Python.- Python counts spans dropped while the circuit was open as
dropped_circuit_open, and calls pastfunction_rate_limitand log records pastlog_rate_limitasdropped_rate_limited. TypeScript counts the first indropped_export_failed.
Environment variables
An option passed to init() wins over its variable, except the EVALKIT_IGNORE_* lists, which are added to it. Boolean variables take 1, true, yes or on, and 0, false, no or off, in any case; any other value logs a warning and is ignored. EVALKIT_FUNCTION_TRACE is the exception: only the exact value false turns function tracing off, and either it or function_tracing=False is enough.
EVALKIT_CAPTURE_CONTENT(both SDKs, on by default): same ascapture_content/captureContent.OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT(both, unset): read whenEVALKIT_CAPTURE_CONTENTis unset. EvalKit applies it to all content, wider than its OpenTelemetry meaning of model messages only.EVALKIT_CAPTURE_SECRETS(both, off): same ascapture_secrets/captureSecrets. Python also readsEVALKIT_CAPTURE_SENSITIVE_HEADERS.EVALKIT_CAPTURE_STREAM_BODIES(Python, on): same ascapture_stream_bodies.EVALKIT_EXPORT_GZIP(both, on): same asexport_gzip/exportGzip.EVALKIT_FUNCTION_TRACE(Python, on):falseturns automatic function tracing off. Functions you wrap yourself are still traced.EVALKIT_API_URL(both, unset): overridesapi_url/apiUrlforEval(), feedback, prompts, scenarios and simulation. Anapi_urlpassed to one call still wins.EVALKIT_QUIET(both, unset): a true value stopsEval()printing the link to its run.EVALKIT_DISABLEDandOTEL_SDK_DISABLED(both, unset, from 0.3.6): a true value turns the SDK off. See Turning the SDK off.EVALKIT_LOG_LEVEL(Python,WARNING, from 0.3.6): same aslog_level, such asINFO.EVALKIT_SAMPLE_RATE(TypeScript, 1, from 0.3.6): same assampleRate.EVALKIT_CONSOLE_SPAN_LEVEL(TypeScript,warn, from 0.3.6): same asconsoleSpanLevel.EVALKIT_EXIT_HOOKS(TypeScript, on, from 0.3.6): same asexitHooks.OTEL_TRACES_SAMPLERandOTEL_TRACES_SAMPLER_ARG(both, every trace kept): in Python, the sample rate whensample_rateis not passed; in TypeScript, OpenTelemetry's own sampler when EvalKit created the tracer provider. See Sampling.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMITandOTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT(both, unset): lowermax_value_bytes/maxValueByteswhen smaller.OTEL_BSP_MAX_QUEUE_SIZE(TypeScript, 2048): the most spans waiting to be sent, whenmaxQueueSizeis not passed.OTEL_BSP_EXPORT_TIMEOUT(TypeScript, 30000): the most milliseconds one export may take.EVALKIT_IGNORE_ROUTES,EVALKIT_IGNORE_URLSandEVALKIT_IGNORE_FUNCTIONS(both, unset, from 0.3.6): comma-separated patterns added toignore_routes,ignore_urlsandignore_functions(ignoreRoutes,ignoreUrls,ignoreFunctions). See Keeping things out of traces.
The environment key has no variable of the SDK's own: EVALKIT_API_KEY belongs to the evalkit command line, not to init().
Content capture
Content capture is on by default. With it off, the SDK still records the shape, timing and cost of every call and sends no payload. The switch covers every span the SDK sends: model calls, tools, functions, HTTP, databases and logs.
import os
import evalkit
evalkit.init(
subscription_key=os.environ["EVALKIT_SUBSCRIPTION_KEY"],
service_name="checkout-api",
environment="production",
capture_content=False, # keep timing, tokens and cost; send no payloads
)| Span | Still recorded with capture off | Removed |
|---|---|---|
| Model call | Model, provider, input, output, cache and reasoning tokens, cost, latency, time to first token, finish reasons, the names of the tools offered and called, tool-call ids, sampling settings, status and errors | Prompt, completion, thinking and refusal text, request and response bodies, tool-call arguments and results |
| Tool and function | Name, duration, status, and the exception type, message and stack trace | tool.arguments, tool.result, function.args, function.kwargs, function.result |
| HTTP | Method, URL with its query string, route, status code, latency | Request and response bodies and headers |
| Database | db.system, operation, table, row count, latency | SQL text (db.statement) and bound parameters (db.params) |
| Log | Level, and in Python the logger, file and line | The message |
| Retriever | Name, latency | The query (retriever.query) |
Every span sent with capture off carries evalkit.content_captured: false, so the trace page can say that capture was off rather than show an empty prompt.
Spans from other OpenTelemetry instrumentation lose their message text too, whatever that library's own content switch says: the GenAI conventions' gen_ai.input.messages, gen_ai.output.messages and gen_ai.system_instructions, gen_ai.prompt and gen_ai.completion with their indexed forms such as gen_ai.prompt.0.content, llm.input_messages.*, input.value and output.value, keys ending in .observation.input, .observation.output, .trace.input or .trace.output, and the content and message of gen_ai.* events such as gen_ai.user.message and gen_ai.choice. Model, tokens, cost, timing, roles, finish reasons and tool names stay. TypeScript also removes the Vercel AI SDK's ai.prompt*, ai.response.* and ai.toolCall.* content and mlflow.span*; Python also removes gen_ai.retrieval.* text.
What capture off does not remove:
- Error messages and stack traces: an exception whose message quotes user input carries it into the trace.
- URLs and their query strings. The scrubber masks parameters named like credentials; the rest, such as
?email=…, stay. - Span names and attributes you set yourself with
start_span,startSpanorstart_trace.
When a provider reports no token counts, the trace service estimates them from the prompt and completion. With capture off there is no text to estimate from, so such a call shows 0 tokens and no cost; for streamed OpenAI calls, see Streaming.
Function inputs and outputs
A function span records what the function was called with and what it returned, as JSON text: function.args (the positional arguments, as a list), function.kwargs (Python keyword arguments) and function.result. A tool span records tool.arguments and tool.result instead. Python calls functions in your source tree automatically; TypeScript traces only the functions you wrap.
- Each value is written as JSON by a serializer that masks secrets as it goes and stops at 4096 characters, with
…at the end, so a large argument is never serialized whole. An argument whose parameter is named like a credential is recorded as***; see Secrets. - A result of
None(Python) orundefined(TypeScript) is not recorded. TypeScript recordsnullasnull. - Python records keyword arguments apart from positional ones. TypeScript records every argument in one list, so an options object shows as an element of
function.args. - For a method, the receiver (
selforcls) is not recorded. - A Python async function, or a TypeScript function that returns a promise, is recorded when it settles, with the resolved value as its result.
- Content capture off removes all of these; the spans stay.
Automatic function tracing in Python
With function_tracing=True, the default, init() wraps functions of your own code. What it wraps:
- Modules under the directory of the file that calls
init(), and every module of a package named intrace_packages. Modules undersite-packages,dist-packages,venv,.venvor a Python installation are left alone, unlesstrace_packagesnames them. - Public functions defined at module level. Names that start with
_are skipped, and so are classes and their methods; use@evalkit.tracedfor a class. - Modules already imported when
init()runs are wrapped then, and modules imported later as they load. In the file that callsinit(), only the functions defined above the call are wrapped. - Calls through the module only. A reference taken before
init()keeps the plain function: afterfrom orders import lookupaboveinit(),lookup(...)is not traced, whileorders.lookup(...)is. - Each span is named
<module>.<function>after the last part of the module name, such asorders.lookup, and always records arguments and result; there is no switch per wrapped function.
Turn it off with function_tracing=False or EVALKIT_FUNCTION_TRACE=false. evalkit.trace_module(module) and evalkit.trace_package(package) then wrap only the modules you choose, with capture_io and include_private arguments, and return how many functions they wrapped.
A module-level function you decorate yourself with trace_function or trace_tool inside the traced directory keeps its one span: automatic tracing leaves it alone, so a capture_io=False you set holds. A decorator of your own stacked on top with functools.wraps carries the same mark.
Wrapping functions and classes
import os
import evalkit
evalkit.init(subscription_key=os.environ["EVALKIT_SUBSCRIPTION_KEY"], service_name="orders-api")
# The decorators below need init() to have run; import modules that use them after this line.
@evalkit.trace_function() # a function span named after the function
def plan_refund(order_id: str, reason: str) -> dict: ...
@evalkit.trace_function(name="refund.issue", capture_io=False) # the span, without arguments or result
def issue_refund(card_token: str, amount: int) -> dict: ...
@evalkit.trace_tool(name="lookup_order") # a tool_call span: tool.arguments and tool.result
def lookup_order(order_id: str) -> dict: ...
@evalkit.traced(prefix="Billing", capture_io=False) # every method except dunder methods
class BillingService: ...
import orders
evalkit.trace_package(orders, capture_io=True) # every public function of every module in a package- Python's
trace_functionandtrace_tooltakename,attributes,capture_ioand, from 0.3.6,error_fingerprint(see Errors and stack traces), and are called with parentheses, as@evalkit.trace_function(). A span is namedname, or the function's qualified name, such asBillingService.charge. Sync and async functions both work, and from 0.3.6 a generator is timed over its iteration, in both SDKs. - Python's
tracedwraps every attribute of the class except dunder methods, so methods starting with one_are traced too. Spans are named<prefix or class>.<method>. - TypeScript's
Tracedwraps the methods defined on the class itself and always records arguments and results, as does@TraceMethod(name?)for one method withexperimentalDecorators. UsetraceFunctionortraceObjectto choosecaptureIO. - Python's decorators need
init(): before it, they raiseRuntimeErrorwhere they are applied. From 0.3.6, TypeScript's wrappers made beforeinit()run untraced, with one warning, and trace onceinit()has run; on 0.3.5 and earlier,traceFunctionandtraceToolthrow there, andTracedandTraceMethodthrow on the first call of a decorated method. enableNestjsAutoTrace(app, { include, captureIO })wraps each method of a provider or controller whose class name matchesinclude, by default/(Service|Controller|Gateway|Resolver|Repository|UseCase|Handler)$/, and returns how many it wrapped. It skips lifecycle hooks,validate,authenticate,serializeUser,deserializeUser,canActivate,intercept,transform,catch,use, getters, setters and methods inherited from a base class. It reads the application's own module container, so no module has to be imported for it. On 0.3.4 and earlier, importDiscoveryModulefrom@nestjs/coreand passapp.get(DiscoveryService)instead ofapp.
Leaving functions out
- Python: from 0.3.6,
ignore_functionsleaves functions out bymodule.qualname, such as["myapp.cache.*"], wherever they would be wrapped: by automatic tracing,trace_module, a class undertraced, or an explicittrace_function. See Keeping things out of traces. A name starting with_is skipped anyway. On 0.3.5 and earlier there is no exclude list: turn automatic tracing off and calltrace_moduleortrace_packageon the modules you want. - TypeScript: from 0.3.6,
ignoreFunctionsleaves methods and functions out by span name, such as["AuthService.*"], forenableNestjsAutoTrace,@Traced,@TraceMethod,traceObjectandtraceFunctionalike. On NestJS theincludepattern still chooses the classes, such as/^(?!AuthService$).*(Service|Controller)$/. - Both SDKs: a function wrapped in
evalkit.untraced(TypeScriptuntraced(fn)) is never wrapped by function tracing, and nothing it calls is recorded. - Both SDKs: a mask hook can drop a function's spans by name, or remove only their arguments, as below.
def mask(span):
if span.operation == "auth.load_user": # drop this function's spans
return None
if span.operation == "billing.charge" and span.attributes: # keep the span, not its arguments
for key in ("function.args", "function.kwargs", "function.result"):
span.attributes.pop(key, None)
return spanSecrets
A secret scrubber runs on every span before your mask hook and before anything leaves the process, whether content capture is on or off. It replaces what it recognises with *** and leaves everything else as it was.
| How | What is masked |
|---|---|
| By key name | A value whose key, or one segment of it between ., _ or -, is api_key, apikey, api-key, secret, password, passwd, authorization, credential, credentials, subscription_key, cookie, set-cookie, private_key, access_key or client_secret, in any case and with or without the separator, so apiKey and clientSecret count. A key whose last segment is token, such as access_token, refresh_token or id_token, counts too; max_tokens, time_to_first_token and per-token prices such as input_cost_per_token and input_cost_per_audio_token do not. Both SDKs split camelCase and PascalCase keys at their capitals, so accessToken, refreshToken, secretKey and ClientSecret count; flags such as hasToken and counts such as maxTokens do not. This applies to attributes, to nested objects and lists, and to attribute values that are JSON text, which are parsed and searched as well, even when the JSON was cut short. |
| By parameter | Function and tool arguments are matched to the parameter they are bound to. One named like a credential, such as key, api_key, secret, token, password, credentials, auth, cookie, dsn, jwt or bearer, in snake or camel case, is recorded as ***, passed by position or by keyword, and so is a member of a TypeScript options object named that way, such as { accessToken }. Counts such as max_tokens keep their values. A function whose own name reads like a credential's, such as get_api_key or getApiKey, records neither arguments nor result. TypeScript reads parameter names from the function's source, so a destructured parameter, a bound or native function and minified code are masked by key and shape only. |
| By header | In request and response headers: authorization, cookie, set-cookie, x-api-key, api-key, x-auth-token, proxy-authorization, x-secret, x-access-token, x-subscription-key, subscription-key, token and password. The header name stays. |
| By shape | Anywhere in text, prompts and completions included: sk-… keys (OpenAI, Anthropic), tk_live_… and tk_test_…, Bearer … tokens, AWS access key ids (AKIA…), GitHub tokens (ghp_…), Google API keys (AIza…), JSON Web Tokens, PEM private keys, whole or cut before their END line, the user and password of a URL or connection string, such as postgres://user:pass@host, and quoted assignments to a credential name, such as password: "…" or api_key='…'. A prefix stays, as in sk-***. |
| In URLs | In http.url, url.full, http.target, server.address and url.query, and in any value that is one URL and nothing else: the user and password (https://***@host), and query or fragment parameters named like a credential above, or named key, sig or signature. Other parameters keep their values. |
Function arguments and results are masked as they are written, by key and by shape, so a credential in a nested object is found by its key, not only by its shape. The writer stops at 4096 characters and reads nothing past them. On 0.3.5, they are masked while whole and then cut.
What the scrubber does not catch, so add a mask hook for it if your app has it:
- Short key names in attributes and bodies:
auth,pwd,key,dsn,jwt. As parameter names they are masked. - Credentials without one of the shapes above: Stripe keys (
sk_live_…), Slack tokens (xoxb-…), AWS secret access keys, and an unquotedtoken=abcin prose. - Personal data: email addresses, names, phone numbers, card and account numbers. User and session ids are kept on purpose, because sessions and users are built on them.
capture_secrets=True (captureSecrets: true, or EVALKIT_CAPTURE_SECRETS=true) turns the scrubber off, credential headers included. Use it only against a local receiver while you debug your own authentication, and never in a deployment.
Mask hooks
A mask hook receives each span as the envelope that will be sent, and returns it changed, or None (TypeScript: null) to drop it. It runs after content stripping and the scrubber, on every span, spans from other OpenTelemetry instrumentation included. If the hook raises, or returns anything but an envelope, the span is dropped and a warning is logged, so a broken hook never sends what it was written to hide.
import os
import re
import evalkit
CARD = re.compile(r"\b(?:\d[ -]?){13,16}\b") # card-like digit runs
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
def mask(span):
if span.span_type == "db_query": # drop every span of one kind
return None
if span.prompt:
span.prompt = CARD.sub("<card>", span.prompt)
if span.completion:
span.completion = CARD.sub("<card>", span.completion)
attrs = span.attributes or {}
for key, value in attrs.items():
if isinstance(value, str):
attrs[key] = EMAIL.sub("<email>", CARD.sub("<card>", value))
return span
evalkit.init(subscription_key=os.environ["EVALKIT_SUBSCRIPTION_KEY"], mask=mask)- The envelope has the fields the receiver stores: Python
span_type,operation,prompt,completion,attributes,events,model,provider,status,user_id,session_id; TypeScript the same in camelCase, such asspanType. Change it in place and return it. - With content capture off, the hook sees the span already stripped. To keep some content and drop the rest, leave capture on and let the hook choose; see Recipes.
- Dropping a span does not drop the spans inside it: they are still sent, without that parent.
- Python calls the hook as each span is queued, usually in the thread that ended it; TypeScript calls it when a batch is exported. Keep it fast and free of I/O.
HTTP bodies and headers
| Python | TypeScript | |
|---|---|---|
| Incoming requests | With the framework middleware: method, URL, route, status, request and response headers, and request and response bodies up to max_body_bytes. Health and readiness probes, matched by whole path segment (/health, /healthz, /health/live, /readyz, /livez), are skipped with what their handler records, so /healthcare and /datasets/<id>/health are recorded. trace_health_checks=True records them, and ignore_routes skips more routes the same way. | Every request to a Node.js HTTP or HTTPS server: method, URL, route, status, request and response headers, the request body as your app reads it (a body nothing reads is not recorded, nor is multipart/form-data), and the response body, each up to maxBodyBytes. Health and readiness probes, matched by whole path segment (/health, /healthz, /health/live, /readyz, /livez), are skipped with or without a framework adapter, so /healthcare and /datasets/<id>/health are recorded. traceHealthChecks: true records them, and ignoreRoutes skips more routes the same way. |
| Outgoing calls | requests, httpx, httpx2 and aiohttp: method, URL, status, request and response headers, and request and response bodies up to max_body_bytes, inside a request or not. Requests to /v1/ingest, and health and readiness probes matched by whole path segment (/health, /healthz, /health/live, /readyz, /livez), are skipped, so /healthcare and /datasets/<id>/health are recorded. ignore_urls skips more calls the same way. | node:http and https inside a traced request: method, URL, status and headers. fetch calls are events on the current span, with URL, status and headers. Bodies are recorded only for the default axios instance, when axios was loaded before init(). Requests to /v1/ingest and health and readiness probes are skipped by the same whole-segment rule, and ignoreUrls skips more calls the same way. |
| Model providers | A model call's own HTTP request is recorded as well, so the prompt appears again in http.request.body and the reply in http.response.body. | A model call's own HTTP request is recorded without its body: as events on the model-call span for clients that use fetch, such as OpenAI and Anthropic, or as an HTTP span for clients on node:http. |
- The headers in the Secrets table are masked; every other header is recorded.
- Query strings are recorded with the URL. Parameters named like a credential are masked; the rest are not.
- The SDK adds headers of its own, on purpose:
traceparenton the outgoing requests it traces, andx-trace-idandtraceparenton the responses of a traced server, so one trace follows a request across services. Python addstraceparentto a copy of the headers you pass, never to your own dict. Nothing else in a request or response is changed. - To stop recording bodies and headers, turn content capture off, or remove
http.request.body,http.response.body,http.request.headersandhttp.response.headersin a mask hook. A smallermax_body_bytescuts bodies shorter.
Streaming
- Streamed model calls are always traced; there is no switch for it. The span is written when the stream ends, with the assembled completion, the usage and the time to first token. Streamed calls explains the details and which providers are covered.
- OpenAI sends token counts in a stream only when the request asks for them: pass
stream_options={"include_usage": True}in Python,stream_options: { include_usage: true }in TypeScript. Without it, the SDK records 0 tokens and logs a warning once per process; the trace service then estimates the counts from the text and marks the spanevalkit.cost_estimated. - Content capture off removes a streamed completion like any other; counts and timing stay.
- Python's
capture_stream_bodies(EVALKIT_CAPTURE_STREAM_BODIES) concerns raw HTTP streams only. With it on, a streamedrequests,httpxoraiohttpresponse is recorded when it ends, is closed or is garbage collected, with its body up tomax_body_bytesandhttp.response.streamed,http.response.stream.complete,http.response.stream.chunks,http.response.body.bytes,http.response.body.truncatedandhttp.server.time_to_first_byte_ms. With it off, the span is recorded when the headers arrive, without the body. It does not change model-call spans, though it does drop the raw server-sent events from the provider's own HTTP span. - TypeScript has no stream-body switch. A streamed response your server sends, such as server-sent events, is recorded like any response body, up to
maxBodyBytes.
Logs and console output
| Python `logging` | TypeScript `console` | |
|---|---|---|
| What is recorded | Each record at log_level and up that reaches the root logger, as a log span. log_level is WARNING by default; pass log_level="INFO" (or logging.INFO), or set EVALKIT_LOG_LEVEL=INFO, to record more. | Inside a span, console.log, console.warn and console.error are log events on it, at every level. Outside one, only warnings and errors become log spans of their own; consoleSpanLevel moves that line ("info", "warn", "error" or "none"). |
| Rate | At most log_rate_limit records a second, 50 by default. The rest are counted as dropped_rate_limited. | At most 50 lines a second. |
| Size | A message over 8 KiB keeps its start and its end around the …[cut N bytes]… marker, with its size in evalkit.truncated.log.message. | A line is cut to 2000 characters before anything in it is serialized. |
| Off | A higher log_level, such as "ERROR", or a mask hook that drops log spans | captureConsole: false |
- Neither SDK records its own lines: Python's
evalkitloggers and TypeScript's[evalkit]lines stay out. - Python's
init()changes no handler, formatter or level, so your log output stays as it was. A logger withpropagate=Falseis recorded only throughevalkit.install_logging_handler(client, logger_name). - A Python record at
ERRORor above has statusERROR; a record with exception info carries the exception as on Errors and stack traces. - On 0.3.5 and earlier, Python records each record the logger that wrote it lets through,
INFOincluded when your app sets that level, with no rate limit. TypeScript records aconsole.logoutside a span as a span of its own;consoleSpanLevel: "info"keeps that from 0.3.6.
Turning integrations off
Neither SDK has a switch per library: init() patches every supported library it finds installed. To keep one library's spans out, drop them in a mask hook by their type, provider or attributes. The call itself is unaffected; only its span is not sent.
def mask(span):
if span.provider == "cohere": # one model provider
return None
attrs = span.attributes or {}
if span.span_type == "db_query" and attrs.get("db.system") == "redis": # one database
return None
return span- Log records are spans of type
log(Python, and TypeScript outside a traced call). In TypeScript, aconsole.log,console.warnorconsole.errorinside a traced call is an event on that call's span instead. To record fewer, see Logs and console output. - TypeScript also registers the OpenTelemetry Node.js instrumentations installed with it, such as GraphQL and gRPC, when it creates the tracer provider itself; attached to a provider of yours, from 0.3.6 it registers none, since your setup chose its own. It leaves off those that would repeat what it records or add noise beside it: HTTP,
undici, sockets, DNS, the file system, OpenAI and the web frameworks (Express, router, connect, Koa, hapi, restify and the Nest core). OpenTelemetry's ownOTEL_NODE_DISABLED_INSTRUMENTATIONS, such asgraphql, turns more off. Turning off the one forpg,mysql2orioredisdoes not stop their spans, because EvalKit then patches the driver itself.
Recipes
| Goal | Settings | What you keep |
|---|---|---|
| Production, no content | capture_content=False (captureContent: false), or EVALKIT_CAPTURE_CONTENT=false in the deployment. On 0.3.4 and earlier, with other OpenTelemetry GenAI instrumentation in the process, also its own content switch; see Content capture. Scrubber left on. | Every span, with timing, status, model, tokens, cost, time to first token, tool names and errors. No prompts, completions, bodies, arguments, SQL or log text. |
| Debugging locally, everything | The defaults, plus debug=True (debug: true). In Python, trace_packages for code outside the directory of the file that calls init(). capture_secrets=True only against a local receiver, to debug your own authentication. | Everything the SDK records, and with the scrubber off, credentials too. |
| Function inputs and outputs, no prompts | Content capture on, with the mask hook below. | Function and tool arguments and results, SQL, logs and your own HTTP bodies. No prompts, completions or model request and response bodies. |
| Streaming with token counts | OpenAI and OpenAI-compatible APIs: stream_options={"include_usage": True} (stream_options: { include_usage: true }). Anthropic, Gemini and Bedrock send usage in the stream without an option. | Real token counts and cost for streamed calls, with time to first token. |
| Fewer traces | sample_rate=0.1 (sampleRate: 0.1, or EVALKIT_SAMPLE_RATE=0.1 in TypeScript). On 0.3.5 and earlier: in TypeScript, OTEL_TRACES_SAMPLER=parentbased_traceidratio with OTEL_TRACES_SAMPLER_ARG=0.1; Python has no sampling there, so drop spans in a mask hook. | About one trace in ten, each one whole, and every model call, tool call and failed span. See Sampling. |
| Tracing off in one deployment | EVALKIT_DISABLED=true in that deployment. | Nothing: the SDK records, patches and sends nothing, and the app runs as without it. |
| Long conversations, bounded memory | The defaults keep 16 MiB per value and 32 MiB of queued spans. Lower max_value_bytes (maxValueBytes) or max_queue_bytes (maxQueueBytes) on a small container; raise max_body_bytes (maxBodyBytes) to record longer HTTP bodies. | The start and the end of every long value, the newest messages included. See Limits and memory. |
import os
import evalkit
# Model-call payloads. Function arguments and results, SQL and log text are left as they are.
MODEL_CONTENT = ("gen_ai.request.body", "gen_ai.response.body", "gen_ai.response.thinking",
"gen_ai.tool.call.arguments", "gen_ai.tool.call.result")
def drop_prompts(span):
if span.span_type == "llm_call":
span.prompt = None
span.completion = None
for attrs in [span.attributes or {}, *[e.attributes or {} for e in span.events or []]]:
for key in MODEL_CONTENT:
attrs.pop(key, None)
elif span.span_type == "http_call" and span.span_kind == "CLIENT" and span.attributes:
# The provider's own HTTP request is recorded too, with the prompt in its body.
span.attributes.pop("http.request.body", None)
span.attributes.pop("http.response.body", None)
return span
evalkit.init(subscription_key=os.environ["EVALKIT_SUBSCRIPTION_KEY"], mask=drop_prompts)Upgrading to 0.3.7
SDK 0.3.7, for Python and TypeScript, makes every web framework integration decide errors and spans by the same rules. By default a request is still an error for every 4xx and 5xx answer, so most apps see no change. These changes can change what you see:
- You choose which answers are errors.
server_error_status_codes(TypeScriptserverErrorStatusCodes) takes codes and ranges,["400-599"]by default.["500-599"]leaves a4xxto the caller: the span staysOKwith its status code and no exception. See Which HTTP answers are errors. - A health route under a record is traced.
/health,/api/v2/healthand/actuator/health/readinessare still left out as probes, but/datasets/<id>/health,/users/42/healthzand a template such as/datasets/:datasetId/healthare your own routes and are now recorded. - Streamed responses end their span with the last chunk. Flask and Django stream spans now cover the whole stream, so their latency grows to match. Hono on Bun, Deno or a fetch handler no longer holds a streamed answer back until it ends.
- Spans are named by route. Koa, hapi and Hono name their own spans by the matched route (
GET /orders/:id), and Litestar by its route template, instead of the raw path.
Upgrading to 0.3.6
SDK 0.3.6, for Python and TypeScript, makes the SDK unable to crash, hold up or grow without bound in the app it traces, and records errors the same way in both SDKs. Most of it needs nothing from you. These changes can change what you see or what your code gets:
- Status messages read
<type>: <message>. A failed span's status is described as its type and message, such asopenai.RateLimitError: Rate limit reachedin Python, where it held the message alone. Python names the type by its module path without the private parts; TypeScript by the error's name or class. Anything that matches a status message exactly, such as a mask hook or a search, now sees the type in front of it. - Python no longer records INFO logs by default. Only records at
WARNINGand up becomelogspans, at most 50 a second. Passlog_level="INFO", or setEVALKIT_LOG_LEVEL=INFO, to record them again. See Logs and console output. - **Python's explicit
patch_*calls warn instead of raising.** A call such asevalkit.patch_sqlalchemy_engine(engine)orevalkit.instrument_flask(app)that cannot instrument its target now logs one warning,evalkit.<name> could not instrument its target, and the target runs untraced. Code that caught the exception gets none; look for the warning instead. Beforeinit()these calls still raiseRuntimeError. - HTTP bodies are recorded up to 64 KiB. The default was 10 MiB. Pass
max_body_bytes(maxBodyBytes) to record more.
Other changes:
- An option that cannot work leaves the SDK off with one warning, instead of tracing into failures, and
EVALKIT_DISABLEDorOTEL_SDK_DISABLEDturns it off. See Turning the SDK off. - A value over the per-value limit keeps its start and its end; Python no longer cuts prompts and completions to 32 KiB, and neither SDK keeps only the first 2 MiB of a request body. See Limits and memory.
- A failed span carries one
exceptionevent, its frames, its source line and its causes, the same in both SDKs, and the framework middleware now records the exception that failed the request. See Errors and stack traces. - Export failures log one warning, then at most one every 5 minutes, and a circuit breaker stops sending to a receiver that does not answer. See Export failures and health.
- TypeScript:
console.logoutside a span no longer becomes a span of its own; warnings and errors still do.consoleSpanLevel: "info"restores it. - TypeScript:
traceFunction,traceTool,traceObject,@TraceMethod,@Traced,startTrace,startSpanandstartHttpTracecalled beforeinit()run untraced, with one warning, instead of throwing. A wrapper made beforeinit()traces once it has run. The framework adapters still needinit(). - TypeScript: spans are sent on
beforeExit,SIGTERMandSIGINT;exitHooks: falseturns that off. See Workers and shutdown. - TypeScript: with
captureGlobalErrors: true, an uncaught exception your app has no handler for is printed and exits with code 1 again, after its span had up to 2 seconds to be sent. - TypeScript: attached to a tracer provider of your own, the SDK registers no OpenTelemetry instrumentations, which recorded each call twice.
- New in both SDKs:
ignore_routes,ignore_urls,ignore_functionsandevalkit.untraced(TypeScriptignoreRoutes,ignoreUrls,ignoreFunctions,untracedandwithoutTracing) keep routes, outgoing calls, functions and blocks out of traces. See Keeping things out of traces. - An outgoing call made while a health probe is answered no longer sends a
traceparent, since the span it named is never sent. In TypeScript, nothing a probe's handler records is kept any more; before, only the probe's own span was left out, except on NestJS.
Troubleshooting
| What you see | Why | What to do |
|---|---|---|
No spans, and one warning from init() at startup | From 0.3.6, an option cannot work, such as an empty key or a malformed base_url, so the SDK is off. The warning names each problem. | Fix the option the warning names. stats() (getStats()) reports circuit_state: "disabled" while the SDK is off. |
| No spans and no warning | EVALKIT_DISABLED or OTEL_SDK_DISABLED is set in that process, or init() never ran. | Unset the variable, or check that the code calling init() runs. |
| Spans of a few minutes are missing after an outage | The circuit breaker opened after 3 export cycles failed; spans that ended while it was open were dropped and counted. | Nothing: exporting resumes once a test batch is taken. last_error in stats() (getStats()) says what failed. |
Python records no INFO log lines | From 0.3.6 only WARNING and up are recorded by default. | Pass log_level="INFO" or set EVALKIT_LOG_LEVEL=INFO. |
An HTTP body stops short, or a value has …[cut N bytes]… in it | The body passed max_body_bytes (64 KiB), or the value passed max_value_bytes (16 MiB) and kept its start and end. | Raise max_body_bytes (maxBodyBytes) or max_value_bytes (maxValueBytes). evalkit.truncated.<field> has the full size. |
| A function span has no arguments or result | Content capture is off; the wrapper was given capture_io=False or captureIO false; or the function returned None (undefined). | Check capture_content and the content variables in Environment variables, then the wrapper. |
| A Python function has no span | It is not a public module-level function, it lives outside the traced directory, it is defined below init() in the file that calls it, or it is called through a reference taken before init(). | Import your modules after init() and call through the module, add the package to trace_packages, or decorate the function. |
| A class's methods have no spans (Python) | Automatic tracing does not wrap classes. | Decorate the class with @evalkit.traced, or a method with @evalkit.trace_function(). |
| A class's methods have no spans (TypeScript) | TypeScript traces only what you wrap. enableNestjsAutoTrace wraps a class only when its name matches include, and only the methods defined on that class. | Decorate the class with @Traced(), widen include, or wrap the inherited methods where they are defined. |
[evalkit] call evalkit.init() before using the SDK | A Python wrapper was applied, or a TypeScript framework adapter registered, before init(), or init() never ran because the key is unset. On 0.3.5 and earlier, TypeScript's traceFunction, traceTool and the other wrappers throw it too. | Call init() before the modules that use wrappers are imported. Where init() is guarded, guard those too. |
[evalkit] traceTool() was called before init(); it runs untraced until init() is called | TypeScript, from 0.3.6: a wrapper or startSpan ran before init(). It ran untraced, and the warning is printed once. | Call init() earlier, or let it be: a wrapper made before init() traces once init() has run. |
| A decorated Python function shows two spans | On 0.3.4 and earlier, automatic tracing wraps a function you had already decorated. | Upgrade to 0.3.5 or later, or see Automatic function tracing. |
| A streamed OpenAI call has no or estimated tokens | The request did not set include_usage, so OpenAI sent no usage. | Add stream_options={"include_usage": True}. |
| A streamed call has no time to first token | The reply had no text, only tool calls, or the stream failed. | Nothing; see Time to first token. |
| A streamed call has no model-call span | The stream was never read and your code still holds it, so it has not been collected. | Read the stream to its end, or leave it with break or a with block. |
| Prompts still show with capture off | The text sits in an error message, a URL, a span name or an attribute you set. On 0.3.4 and earlier, the span can also come from other OpenTelemetry instrumentation that wrote its own attributes. | Remove the attributes in a mask hook. On 0.3.4 and earlier, also turn content off in that library. |