@cetra-ai/cli 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +48 -0
  2. package/README.md +14 -2
  3. package/dist/cli.js +2816 -0
  4. package/dist/skills/cetra/SKILL.md +95 -0
  5. package/dist/skills/cetra/references/anthropic.md +82 -0
  6. package/dist/skills/cetra/references/attributes.md +178 -0
  7. package/dist/skills/cetra/references/bedrock.md +46 -0
  8. package/dist/skills/cetra/references/crewai.md +38 -0
  9. package/dist/skills/cetra/references/dspy.md +38 -0
  10. package/dist/skills/cetra/references/from-laminar.md +49 -0
  11. package/dist/skills/cetra/references/from-langfuse.md +59 -0
  12. package/dist/skills/cetra/references/google-adk.md +60 -0
  13. package/dist/skills/cetra/references/google-genai.md +50 -0
  14. package/dist/skills/cetra/references/integrations.md +71 -0
  15. package/dist/skills/cetra/references/langchain.md +76 -0
  16. package/dist/skills/cetra/references/litellm.md +45 -0
  17. package/dist/skills/cetra/references/llama-index.md +38 -0
  18. package/dist/skills/cetra/references/metadata-and-tags.md +117 -0
  19. package/dist/skills/cetra/references/openai-agents.md +55 -0
  20. package/dist/skills/cetra/references/openai.md +82 -0
  21. package/dist/skills/cetra/references/openinference.md +51 -0
  22. package/dist/skills/cetra/references/openllmetry.md +42 -0
  23. package/dist/skills/cetra/references/opentelemetry-genai.md +49 -0
  24. package/dist/skills/cetra/references/opentelemetry.md +134 -0
  25. package/dist/skills/cetra/references/otlp.md +73 -0
  26. package/dist/skills/cetra/references/privacy-controls.md +120 -0
  27. package/dist/skills/cetra/references/python-context.md +63 -0
  28. package/dist/skills/cetra/references/python-opentelemetry.md +136 -0
  29. package/dist/skills/cetra/references/python-tracing.md +77 -0
  30. package/dist/skills/cetra/references/python.md +79 -0
  31. package/dist/skills/cetra/references/sessions.md +84 -0
  32. package/dist/skills/cetra/references/sql-schema.md +210 -0
  33. package/dist/skills/cetra/references/troubleshooting.md +90 -0
  34. package/dist/skills/cetra/references/typescript-context.md +22 -0
  35. package/dist/skills/cetra/references/typescript-opentelemetry.md +68 -0
  36. package/dist/skills/cetra/references/typescript-runtimes.md +54 -0
  37. package/dist/skills/cetra/references/typescript-tracing.md +40 -0
  38. package/dist/skills/cetra/references/typescript.md +56 -0
  39. package/dist/skills/cetra/references/users.md +87 -0
  40. package/dist/skills/cetra/references/vercel-ai-sdk.md +82 -0
  41. package/package.json +39 -4
@@ -0,0 +1,49 @@
1
+ <!-- Generated from website/src/content/docs/docs/integrations/opentelemetry-genai.mdx by website/scripts/skill-references.mjs. Do not edit: run `just docs-gen`. -->
2
+
3
+ # OpenTelemetry GenAI instrumentations
4
+
5
+ Send the official OpenTelemetry GenAI instrumentation packages to cetra: OpenAI and Google Gen AI, with GenAI semantic conventions.
6
+
7
+ cetra reads the OpenTelemetry GenAI semantic conventions, so the official `opentelemetry-instrumentation-*` packages work with a plain OTLP exporter.
8
+
9
+ ## Point the exporter at cetra
10
+
11
+ Add an OTLP exporter to your provider, then instrument the library. This is the setup the fixtures were captured with, with the endpoint and the key changed.
12
+
13
+ ```python
14
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
15
+ from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor
16
+ from opentelemetry.sdk.trace import TracerProvider
17
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
18
+
19
+ provider = TracerProvider()
20
+ provider.add_span_processor(
21
+ BatchSpanProcessor(
22
+ OTLPSpanExporter(
23
+ endpoint="http://localhost:8080/v1/traces",
24
+ headers={"Authorization": "Bearer <SK_CETRA_KEY>"},
25
+ )
26
+ )
27
+ )
28
+ OpenAIInstrumentor().instrument(tracer_provider=provider)
29
+ ```
30
+
31
+ Replace `<SK_CETRA_KEY>` with your `sk-cetra-` API key. See [Send OpenTelemetry](https://cetra.sh/docs/get-started/opentelemetry/) for the endpoint and the ports.
32
+
33
+ ## What carries over
34
+
35
+ - The `gen_ai.operation.name` decides the span kind: `chat` and `generate_content` are `llm`, `embeddings` is `embedding`, `execute_tool` is `tool`, `invoke_agent` is `agent`, `retrieval` is `retriever` and `invoke_workflow` is `chain`.
36
+ - Messages come from `gen_ai.input.messages` and `gen_ai.output.messages`, and when the span does not have them, from the operation-details event. The older `gen_ai.*.message` events are read as well.
37
+ - System instructions, tool definitions, the token counts including cache and reasoning tokens, request parameters and finish reasons are read.
38
+ - The time to first token is read from `gen_ai.response.time_to_first_chunk`.
39
+
40
+ ## Limits
41
+
42
+ - The captured fixtures are two Python packages: `opentelemetry-instrumentation-openai-v2` 2.4b0 and `opentelemetry-instrumentation-google-genai` 1.1b1.
43
+ - Some instrumentations send prompts and completions as log events instead of span attributes. cetra drops log events, so those prompts do not arrive. Turn on the instrumentation's option to record content on spans. See [OTLP endpoint](https://cetra.sh/docs/reference/otlp/).
44
+
45
+ ## Next
46
+
47
+ - [Traces](https://cetra.sh/docs/tracing/traces/): read the trace as a tree and a timeline.
48
+ - [Cost and tokens](https://cetra.sh/docs/tracing/cost-and-tokens/): how cost is computed from the token counts.
49
+ - [Online rules](https://cetra.sh/docs/evaluation/online-rules/): score these traces automatically.
@@ -0,0 +1,134 @@
1
+ <!-- Generated from website/src/content/docs/docs/get-started/opentelemetry.mdx by website/scripts/skill-references.mjs. Do not edit: run `just docs-gen`. -->
2
+
3
+ # Send OpenTelemetry
4
+
5
+ Send traces to cetra from any OpenTelemetry setup, in Python, Node.js, Go, Java or through a Collector.
6
+
7
+ Use plain OpenTelemetry when your application already has it, or when it is written in a language without a cetra SDK.
8
+
9
+ ## Endpoints
10
+
11
+ | Protocol | Endpoint |
12
+ |---|---|
13
+ | OTLP/HTTP | `http://<HOST>:8080/v1/traces` or `http://<HOST>:4318/v1/traces` |
14
+ | OTLP/gRPC | `<HOST>:4317` |
15
+
16
+ Authenticate with an API key in a header: `Authorization: Bearer sk-cetra-…`. cetra accepts protobuf and JSON bodies, and gzip compression.
17
+
18
+ ## Python
19
+
20
+ Install the OpenTelemetry SDK and the OTLP/HTTP exporter:
21
+
22
+ ```bash
23
+ pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
24
+ export CETRA_API_KEY=sk-cetra-<32_LETTERS_OR_DIGITS>
25
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:8080
26
+ ```
27
+
28
+ The exporter reads the endpoint from `OTEL_EXPORTER_OTLP_ENDPOINT` and adds `/v1/traces` itself.
29
+
30
+ ```python
31
+ import os
32
+
33
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
34
+ from opentelemetry.sdk.trace import TracerProvider
35
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor
36
+
37
+ provider = TracerProvider()
38
+ provider.add_span_processor(
39
+ BatchSpanProcessor(
40
+ OTLPSpanExporter(headers={"Authorization": f"Bearer {os.environ['CETRA_API_KEY']}"})
41
+ )
42
+ )
43
+ tracer = provider.get_tracer("my-app")
44
+
45
+ with tracer.start_as_current_span("chat") as span:
46
+ span.set_attribute("gen_ai.provider.name", "openai")
47
+ span.set_attribute("gen_ai.request.model", "gpt-4o-mini")
48
+ span.set_attribute("gen_ai.usage.input_tokens", 12)
49
+ span.set_attribute("gen_ai.usage.output_tokens", 3)
50
+
51
+ provider.shutdown() # flushes the spans before the script ends
52
+ ```
53
+
54
+ ## Node.js
55
+
56
+ ```bash
57
+ npm install @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-proto
58
+ export CETRA_API_KEY=sk-cetra-<32_LETTERS_OR_DIGITS>
59
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:8080
60
+ ```
61
+
62
+ ```ts
63
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
64
+ import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-node";
65
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
66
+
67
+ const provider = new NodeTracerProvider({
68
+ spanProcessors: [
69
+ new BatchSpanProcessor(
70
+ new OTLPTraceExporter({ headers: { Authorization: `Bearer ${process.env.CETRA_API_KEY}` } }),
71
+ ),
72
+ ],
73
+ });
74
+ provider.register();
75
+
76
+ const tracer = provider.getTracer("my-app");
77
+ const span = tracer.startSpan("chat");
78
+ span.setAttribute("gen_ai.provider.name", "openai");
79
+ span.setAttribute("gen_ai.request.model", "gpt-4o-mini");
80
+ span.end();
81
+
82
+ await provider.shutdown();
83
+ ```
84
+
85
+ ## Go
86
+
87
+ Use the OTLP/HTTP exporter and set the endpoint and header through the standard variables:
88
+
89
+ ```bash
90
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:8080
91
+ export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer sk-cetra-…"
92
+ ```
93
+
94
+ ```go
95
+ exporter, err := otlptracehttp.New(ctx) // go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp
96
+ if err != nil {
97
+ log.Fatal(err)
98
+ }
99
+ provider := sdktrace.NewTracerProvider(sdktrace.WithBatcher(exporter))
100
+ defer provider.Shutdown(ctx)
101
+ otel.SetTracerProvider(provider)
102
+ ```
103
+
104
+ ## Java
105
+
106
+ With the OpenTelemetry Java agent, set the same variables:
107
+
108
+ ```bash
109
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:8080
110
+ export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
111
+ export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer sk-cetra-…"
112
+ java -javaagent:opentelemetry-javaagent.jar -jar app.jar
113
+ ```
114
+
115
+ ## OpenTelemetry Collector
116
+
117
+ If your application already sends to a Collector, add an `otlphttp` exporter with the header:
118
+
119
+ ```yaml
120
+ exporters:
121
+ otlphttp/cetra:
122
+ endpoint: http://localhost:8080
123
+ headers:
124
+ Authorization: Bearer ${env:CETRA_API_KEY}
125
+
126
+ service:
127
+ pipelines:
128
+ traces:
129
+ exporters: [otlphttp/cetra]
130
+ ```
131
+
132
+ ## What cetra reads
133
+
134
+ cetra reads the OpenTelemetry GenAI attributes (`gen_ai.*`) and the OpenInference conventions, and records inputs, outputs, token usage and cost from them. Spans without these attributes are stored as they are. See [Semantic conventions](https://cetra.sh/docs/concepts/conventions/) for every convention cetra reads.
@@ -0,0 +1,73 @@
1
+ <!-- Generated from website/src/content/docs/docs/reference/otlp.mdx by website/scripts/skill-references.mjs. Do not edit: run `just docs-gen`. -->
2
+
3
+ # OTLP endpoint
4
+
5
+ Where to send OpenTelemetry spans to cetra, the encodings it accepts, its limits and what each answer means.
6
+
7
+ cetra ingests spans over OTLP, the OpenTelemetry protocol, from the cetra SDKs or from any OpenTelemetry exporter.
8
+
9
+ ## Endpoints
10
+
11
+ | Transport | Endpoint | Encodings |
12
+ |---|---|---|
13
+ | OTLP/HTTP | `POST /v1/traces` on the main port (default 8080) and on port 4318 | `application/x-protobuf`, `application/json`; `Content-Encoding` of `gzip`, `zstd`, `deflate` or none |
14
+ | OTLP/gRPC | `opentelemetry.proto.collector.trace.v1.TraceService/Export` on port 4317 | protobuf; gzip |
15
+
16
+ Port 4318 serves only the OTLP routes and `/v1/agent-context`, for exporters that use the standard OpenTelemetry port.
17
+
18
+ OTLP/JSON follows the OpenTelemetry specification strictly: lowerCamelCase field names, hex trace and span IDs, enums as integers and 64-bit integers as decimal strings or numbers. A body with enum names or base64 IDs gets `400`.
19
+
20
+ ## Authentication
21
+
22
+ Send an API key that has the `ingest` scope as a bearer token. The key chooses the project; there is no project header.
23
+
24
+ ```bash
25
+ export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:8080"
26
+ export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer <API_KEY>"
27
+ ```
28
+
29
+ ## Limits
30
+
31
+ | Limit | Default | When exceeded |
32
+ |---|---|---|
33
+ | HTTP request body, before and after decompression (`ingest.max_request_bytes`) | 10 MiB | `413` |
34
+ | gRPC message (`ingest.max_grpc_message_bytes`) | 32 MiB | gRPC `OUT_OF_RANGE` |
35
+ | Spans in one request (`ingest.max_spans_per_request`) | 50,000 | `413`, gRPC `INVALID_ARGUMENT` |
36
+ | One attribute value (`ingest.max_attribute_bytes`) | 8 MiB | The value is cut and marked as truncated |
37
+ | Request bytes held in memory at once (`ingest.max_inflight_bytes`) | 256 MiB | `503` with `Retry-After: 1` |
38
+
39
+ The limits are set in the server configuration.
40
+
41
+ ## Answers
42
+
43
+ | Status | Meaning |
44
+ |---|---|
45
+ | `200` | Every accepted span is on disk. The body is an OTLP `ExportTraceServiceResponse` in the request's encoding. |
46
+ | `400` | The body is malformed. |
47
+ | `401` | No key, or an invalid one. |
48
+ | `402` | The org's monthly units cap is reached. Do not retry; `Retry-After` is the seconds until the cap resets. |
49
+ | `403` | The credential is not a key with the `ingest` scope. |
50
+ | `413` | The request is over a limit above. |
51
+ | `415` | Unknown `Content-Type` or `Content-Encoding`. |
52
+ | `429` | The org's ingest rate limit; wait for `Retry-After`. |
53
+ | `503` | The server is overloaded, out of disk space or shutting down; retry after `Retry-After`. |
54
+
55
+ Error bodies are `application/problem+json` as described in the [REST API](https://cetra.sh/docs/reference/api/overview/#errors), not an OTLP status message. gRPC uses the matching status codes: `UNAUTHENTICATED`, `PERMISSION_DENIED`, `INVALID_ARGUMENT`, `RESOURCE_EXHAUSTED` for the units cap and `UNAVAILABLE` for overload and the rate limit.
56
+
57
+ When the units cap is reached, the cetra SDKs stop sending until the reset time instead of retrying.
58
+
59
+ ## Partial success
60
+
61
+ cetra rejects a span, and accepts the others in the request, when:
62
+
63
+ - its trace ID or span ID is missing, has the wrong length or is all zeros;
64
+ - a start or end time does not fit in a signed 64-bit integer of nanoseconds;
65
+ - its start time is before 2000-01-01, older than the project's retention, or more than one day in the future.
66
+
67
+ The response is `200` with `partial_success.rejected_spans` set and an `error_message` that lists the reasons and counts, for example `rejected 3 spans: invalid_span_id ×2, start_time_out_of_range ×1`. The message never contains a value from your request.
68
+
69
+ Some problems are fixed instead of rejected. A parent span ID of all zeros or of the wrong length counts as no parent. An end time before the start time is set equal to the start time, and a warning is recorded on the span.
70
+
71
+ ## Logs and metrics
72
+
73
+ `POST /v1/logs` and `POST /v1/metrics` (and the gRPC equivalents) are accepted on the same ports, with the same authentication and limits, and then dropped. cetra stores spans only. If your instrumentation sends prompts and completions as log events, set it to capture them on spans.
@@ -0,0 +1,120 @@
1
+ <!-- Generated from website/src/content/docs/docs/tracing/privacy-controls.mdx by website/scripts/skill-references.mjs. Do not edit: run `just docs-gen`. -->
2
+
3
+ # Masking, sampling and truncation
4
+
5
+ Control what your SDK sends, with content capture, masking, sampling and export filters, and what cetra cuts when a value is too large.
6
+
7
+ Use these controls to keep sensitive content out of cetra, to send fewer traces, and to understand what cetra cuts.
8
+
9
+ There are two places to act. The SDK controls what leaves your process. The server cuts values that are too large when it receives them.
10
+
11
+ ## Turn off content capture
12
+
13
+ With content capture off, cetra records that a call happened, with its model, parameters, token counts, cost and timing, but not its input or output. The SDK drops the payloads of your spans, and the payload attributes of spans from other instrumentation libraries.
14
+
15
+ **Python**
16
+
17
+ ```python
18
+ import cetra
19
+
20
+ cetra.init(capture_content=False)
21
+
22
+ @cetra.observe(name="answer")
23
+ def answer(question: str) -> str:
24
+ return "42"
25
+
26
+ answer("why?")
27
+
28
+ cetra.flush()
29
+ ```
30
+
31
+ **TypeScript**
32
+
33
+ ```ts
34
+ import { init } from "@cetra-ai/sdk";
35
+
36
+ init({ apiKey: process.env.CETRA_API_KEY, captureContent: false });
37
+ ```
38
+
39
+ You can also set `CETRA_CAPTURE_CONTENT=false` in the environment.
40
+
41
+ ## Mask values
42
+
43
+ A mask is a function that receives each value the SDK records, before it is sent, and returns the value to send instead. It runs on inputs, outputs, metadata values and messages. For spans from other instrumentation libraries, it runs on the payload attributes when the span is exported. The mask gets the decoded value: text, or a parsed JSON structure.
44
+
45
+ **Python**
46
+
47
+ ```python
48
+ import re
49
+
50
+ import cetra
51
+
52
+ SECRET = re.compile(r"sk-live-\w+")
53
+
54
+ def redact(value):
55
+ if isinstance(value, str):
56
+ return SECRET.sub("[key]", value)
57
+ return value
58
+
59
+ cetra.init(mask=redact)
60
+
61
+ @cetra.observe(name="answer")
62
+ def answer(question: str) -> str:
63
+ return "done"
64
+
65
+ answer("my key is sk-live-abc123")
66
+
67
+ cetra.flush()
68
+ ```
69
+
70
+ **TypeScript**
71
+
72
+ ```ts
73
+ import { init } from "@cetra-ai/sdk";
74
+
75
+ init({
76
+ apiKey: process.env.CETRA_API_KEY,
77
+ mask: (value) => (typeof value === "string" ? value.replaceAll("sk-live-", "[key]") : value),
78
+ });
79
+ ```
80
+
81
+ The mask fails closed. If it raises an error, the value becomes `[cetra: mask failed]`, and a batch that cannot be masked is dropped, not sent in clear.
82
+
83
+ ## Sample traces
84
+
85
+ Sampling keeps a share of your traces. The decision is made per trace, from the trace ID, so a trace is kept whole or dropped whole.
86
+
87
+ ```bash
88
+ export CETRA_SAMPLE_RATE=0.25
89
+ ```
90
+
91
+ `CETRA_SAMPLE_RATE` is a number from 0 to 1, and the default is 1. You can also pass `sample_rate` (Python) or `sampleRate` (TypeScript) to `init()`. Scores need their trace, so a run with a low sample rate can lose the scores of dropped traces.
92
+
93
+ ## Export filters
94
+
95
+ When the SDK shares the global OpenTelemetry provider (`use_global_provider` in Python, `useGlobalProvider` in TypeScript), it sends only LLM-related spans by default. Spans from your web framework or database are left out. Pass `export_filter` (Python) or `exportFilter` (TypeScript) to choose your own rule, in either mode. It receives each finished span and returns whether to send it.
96
+
97
+ ## Truncation on the server
98
+
99
+ cetra cuts values that are too large, so one huge attribute cannot fill the storage. It never rejects a span for the size of a value.
100
+
101
+ The limit for one value is 8 MiB by default. It applies to inputs, outputs, system instructions, tool definitions, attributes, metadata values, tags and names. The server's `ingest.max_attribute_bytes` setting changes it. See the [configuration reference](https://cetra.sh/docs/self-hosting/configuration-reference/).
102
+
103
+ What a cut value looks like:
104
+
105
+ - A text value is cut and ends with `…[cetra: truncated, original N bytes]`, where N is the original size.
106
+ - For a list of messages, cetra keeps the system messages, the first user message and the most recent messages that fit, and replaces each removed run with the message `[cetra: K messages truncated]`.
107
+ - A JSON input or output that is cut becomes text, because the cut value is no longer valid JSON.
108
+ - A value nested more than 32 levels deep is replaced by `[cetra: max depth]`.
109
+
110
+ The UI shows a **truncated at ingest** badge on a cut input or output. The `truncated` column of `spans` lists the names of the cut values. The Python SDK also cuts a payload larger than 1 MiB before it sends it, and marks it the same way.
111
+
112
+ A request is limited separately by the OTLP endpoint. See [OTLP endpoint](https://cetra.sh/docs/reference/otlp/).
113
+
114
+ ## The assistant
115
+
116
+ The in-app assistant sends your questions, the page context, the chat history and the results of the tools it calls to the provider of the connection it uses. Its chats are private to you and are deleted 30 days after their last activity. Its turns are traced in the `cetra-assistant` environment with no message text. See [Assistant](https://cetra.sh/docs/platform/assistant/) for what is stored and for how long.
117
+
118
+ ## Deleting data
119
+
120
+ To remove data cetra already stored, by user, trace, filter, project or organization, see [Deletion and retention](https://cetra.sh/docs/platform/deletion-and-retention/).
@@ -0,0 +1,63 @@
1
+ <!-- Generated from website/src/content/docs/docs/reference/python/context.mdx by website/scripts/skill-references.mjs. Do not edit: run `just docs-gen`. -->
2
+
3
+ # Context (Python)
4
+
5
+ Attach sessions, users, tags and metadata to every span, send them downstream as baggage and carry them across threads.
6
+
7
+ Use `cetra.context` to group traces by session and user, and to carry that context across threads.
8
+
9
+ ## Context and baggage
10
+
11
+ `cetra.context(session_id=..., user_id=..., tags=[...], metadata={...})` is a sync and async context manager that applies those values to every span started inside it, ours and the instrumentors' alike. The values live in the OpenTelemetry context, so they follow `contextvars` (and `copy_context()`) across tasks.
12
+
13
+ Nested blocks merge: the inner `session_id`/`user_id` win when given, tags are the union (outer first, no duplicates), metadata merges by key with the inner value winning. Metadata values are masked when the block is entered.
14
+
15
+ ```python
16
+ import cetra
17
+
18
+ cetra.init(api_key="sk-cetra-test", environment="production", release="1.4.2")
19
+
20
+ @cetra.observe(name="turn")
21
+ def turn() -> None: ...
22
+
23
+ with cetra.context(session_id="chat-42", user_id="u-17", tags=["beta"], metadata={"plan": "pro"}):
24
+ turn()
25
+
26
+ cetra.flush()
27
+ ```
28
+
29
+ Every span of the block then carries `cetra.session.id`, `cetra.user.id`, `cetra.tags`, `cetra.metadata.plan`, and, when set at `init()`, `cetra.environment` and `cetra.release`. Metadata keys must match `[A-Za-z0-9_.-]+`; a key that does not is skipped (logged at debug level with its length only).
30
+
31
+ `context(prompt=...)` takes a `Prompt` from `get_prompt` and stamps its name as `cetra.prompt.name` and its version as `cetra.prompt.version` on every span of the block; a fallback prompt has no version, so only the name is written. A nested block without a prompt keeps the outer one, and an inner prompt replaces it. Any other value is ignored and logged at debug level. The [Prompts](https://cetra.sh/docs/evaluation/prompts/) page shows the whole flow.
32
+
33
+ `context(..., propagate=True)` additionally writes the session and user ids to W3C **baggage** as `cetra.session.id` and `cetra.user.id`. It is opt-in because baggage is sent as an HTTP header on every outgoing request of the app, to third-party APIs included. Tags and metadata never go into baggage. A downstream service running this SDK picks the ids up from baggage without calling `context()` itself.
34
+
35
+ ## Threads
36
+
37
+ The SDK does not patch `threading` or executors. The OpenTelemetry context, including `context()` values and the current span, does not cross a thread boundary by itself, so a span started in a worker thread would be a detached root without them. Copy the context explicitly:
38
+
39
+ ```python
40
+ import threading
41
+ from contextvars import copy_context
42
+
43
+ import cetra
44
+
45
+ cetra.init(api_key="sk-cetra-test")
46
+
47
+ @cetra.observe(name="lookup")
48
+ def lookup(key: str) -> str:
49
+ return "found"
50
+
51
+ def work() -> None:
52
+ lookup("pricing")
53
+
54
+ with cetra.span("request", input="why?"):
55
+ ctx = copy_context()
56
+ worker = threading.Thread(target=ctx.run, args=(work,))
57
+ worker.start()
58
+
59
+ worker.join()
60
+ cetra.flush()
61
+ ```
62
+
63
+ For thread pools, `ThreadPoolExecutor(..., initializer=...)` cannot capture a per-task context this way; OpenTelemetry's [opentelemetry-instrumentation-threading](https://pypi.org/project/opentelemetry-instrumentation-threading/) instrumentor patches `threading` for you instead.
@@ -0,0 +1,136 @@
1
+ <!-- Generated from website/src/content/docs/docs/reference/python/opentelemetry.mdx by website/scripts/skill-references.mjs. Do not edit: run `just docs-gen`. -->
2
+
3
+ # OpenTelemetry (Python)
4
+
5
+ Enable instrumentors, work next to an existing OpenTelemetry setup, mask payloads and know the limits of the Python SDK.
6
+
7
+ Use these settings to capture spans from LLM libraries, to share a process with other OpenTelemetry code and to keep content out of your traces.
8
+
9
+ ## Instrumentation
10
+
11
+ `init(instrument=[...])` enables [OpenInference](https://github.com/Arize-ai/openinference)
12
+ instrumentors by name, from the fixed registry in the [install table](https://cetra.sh/docs/reference/python/#install):
13
+
14
+ ```python
15
+ cetra.init(api_key="sk-cetra-test", instrument=["openai", "anthropic"])
16
+ ```
17
+
18
+ An unknown name raises `ConfigError` listing the known names; a name whose
19
+ package is missing raises `ConfigError` naming the extra to install (for
20
+ example `instrument: 'openai' needs \`pip install cetra-sdk[openai]\``). Nothing
21
+ is installed when a name fails: the error surfaces from `init()` itself.
22
+
23
+ The instrumentors are created with our tracer provider, so their spans nest
24
+ under ours and carry the `context()` values. A library you already
25
+ instrumented yourself is left alone (one debug line). `shutdown()` uninstruments
26
+ everything the SDK enabled. Our provider raises the OTel attribute limit to
27
+ 10 000, so flattened message attributes are not clipped.
28
+
29
+ ## Existing OpenTelemetry setups
30
+
31
+ By default `init()` builds its own `TracerProvider` and never registers it
32
+ globally: your OTel setup is untouched, and instrumentor spans reach cetra
33
+ because the SDK binds them to our provider. The OTel *context* is always the
34
+ global one, so spans nest correctly in both modes.
35
+
36
+ With `use_global_provider=True`:
37
+
38
+ - an app's SDK `TracerProvider` already set as global takes our span processor
39
+ (the app keeps its sampler: a `sample_rate` below 1 logs one warning and is
40
+ ignored);
41
+ - when nothing is registered yet, our provider becomes the global one;
42
+ - any other global provider cannot take processors: the SDK logs one warning
43
+ and keeps its own.
44
+
45
+ In global mode other libraries create spans on the same provider, so the
46
+ default export filter keeps only the LLM-related ones: spans whose
47
+ instrumentation scope is `cetra` or `ai`, or with an attribute key starting
48
+ with `cetra.`, `gen_ai.`, `llm.`, `openinference.`, `ai.`, `traceloop.`,
49
+ `langfuse.`, `lmnr.` or `gcp.vertex.agent.`, or with an `input.value` /
50
+ `output.value` key. Pass your own callable as `export_filter=` to replace that
51
+ rule in either mode: it receives the finished span and returns a boolean; if
52
+ it raises, the span is exported.
53
+
54
+ `cetra.span_processor()` returns our span processor for apps that build their
55
+ own OTel pipeline, and `cetra.tracer_provider()` returns the provider in use
56
+ (a no-op provider before `init()`, when disabled or after `shutdown()`), for
57
+ libraries that accept a provider or tracer.
58
+
59
+ ## Masking and `capture_content`
60
+
61
+ `mask` is a callable applied at capture time to every value the SDK records —
62
+ inputs, outputs, metadata values, LLM messages — before serialization:
63
+
64
+ ```python
65
+ def redact(value): ... # return the value with secrets removed
66
+
67
+ cetra.init(api_key="sk-cetra-test", mask=redact)
68
+ ```
69
+
70
+ At export time a second pass rewrites spans from *other* instrumentation
71
+ scopes (the instrumentors'): for each attribute under a payload key —
72
+ `cetra.input`, `cetra.output`, `gen_ai.input.messages`,
73
+ `gen_ai.output.messages`, `gen_ai.system_instructions`, `input.value`,
74
+ `output.value`, the `llm.input_messages.*` / `llm.output_messages.*` /
75
+ `gen_ai.prompt.*` / `gen_ai.completion.` prefixes and the other keys of spec
76
+ 10 — the mask receives the decoded value (JSON-parsed when the string is a
77
+ JSON object or array) and the result is serialized back. Only string values
78
+ are masked; a non-string value under a payload key is deleted. If `mask`
79
+ raises, the value becomes `[cetra: mask failed]` — the SDK fails closed, and
80
+ a batch that cannot be rewritten is dropped, never exported unmasked.
81
+
82
+ `capture_content=False` records no payloads at all on our spans (no
83
+ input/output, no messages, no system instructions; metrics-like attributes —
84
+ models, params, token counts, cost — are kept), deletes the payload keys from
85
+ instrumentor spans, and configures the OpenInference instrumentors we create
86
+ with their hide-inputs/hide-outputs options.
87
+
88
+ ## Serverless
89
+
90
+ `atexit` handlers do not run when a serverless platform freezes or terminates
91
+ an invocation. Call `cetra.flush()` at the end of every invocation (or
92
+ `cetra.shutdown()` when the instance is not reused); otherwise spans and
93
+ scores still sitting in the batch queue are lost.
94
+
95
+ ## Known limits
96
+
97
+ - **Abandoned async generators are never exported.** An async generator that
98
+ is neither exhausted nor `aclose()`d leaves its span unended — an async
99
+ generator cannot be closed from a finalizer. `aclose()` it when you stop
100
+ early.
101
+ - **`inspect.isasyncgenfunction` (and `isgeneratorfunction`) is false on a
102
+ wrapped function.** `observe` detects generator functions at decoration
103
+ time; decorating an already-wrapped async generator function traces it as a
104
+ plain call whose output is not recorded.
105
+ - **In global mode, the app's own spans get `cetra.*` attributes.** Our
106
+ processor stamps `cetra.session.id`, `cetra.user.id`, `cetra.tags`,
107
+ `cetra.metadata.*`, `cetra.environment` and `cetra.release` on every span
108
+ of the provider it is attached to, so the app's other exporters see them.
109
+ - **`OTEL_EXPORTER_OTLP_HEADERS` is sent to cetra too.** The OTel HTTP
110
+ exporter merges `OTEL_EXPORTER_OTLP_HEADERS` and
111
+ `OTEL_EXPORTER_OTLP_TRACES_HEADERS` from the environment into its request
112
+ headers; headers meant for another OTLP backend reach the cetra server as
113
+ well. Unset them if that matters.
114
+ - **`KeyboardInterrupt` and `asyncio.CancelledError` are not errors.** Only
115
+ `Exception` gets the error status. A `BaseException` that is not an
116
+ `Exception` — inside a `span()` / `llm_span()` block or raised through
117
+ `@observe` (functions, coroutine functions and both generator wrappers)
118
+ alike — ends the span with the status unset, records no output, and is
119
+ re-raised unchanged.
120
+ - **Zero-argument functions and `None`**: a call with no arguments records
121
+ `{}` as input; a `None` return records `null` as output. TypeScript records
122
+ no input for no arguments and no output for `undefined` (return `null` there
123
+ to record a JSON `null`).
124
+ - **Integral floats**: Python writes `1.0` as a double; TypeScript has one
125
+ number type and writes an integral value as an int. The server reads both.
126
+ - **Large integers**: Python ints beyond ±(2^53−1) inside JSON payloads are
127
+ written as JSON numbers; TypeScript `bigint` becomes a decimal string. As
128
+ metadata values both are JSON strings.
129
+ - **Resource attributes**: Python reads `OTEL_RESOURCE_ATTRIBUTES`; TypeScript
130
+ reads only `OTEL_SERVICE_NAME`.
131
+ - **Abandoned sync generators** that are garbage-collected half-consumed end
132
+ with status ok (TypeScript has no finalizer and leaves them unexported).
133
+ - **Usage counts**: `set_usage` records any non-negative `int`, including
134
+ values beyond 2^53; TypeScript `setUsage` records only safe integers.
135
+ - **Threads and serverless**: see [Threads](https://cetra.sh/docs/reference/python/context/#threads) and
136
+ [Serverless](#serverless).
@@ -0,0 +1,77 @@
1
+ <!-- Generated from website/src/content/docs/docs/reference/python/tracing.mdx by website/scripts/skill-references.mjs. Do not edit: run `just docs-gen`. -->
2
+
3
+ # Tracing (Python)
4
+
5
+ Trace Python functions with observe, write spans by hand and record LLM calls with llm_span.
6
+
7
+ Use `observe`, `span` and `llm_span` to turn your Python code into spans.
8
+
9
+ ## Decorator rules
10
+
11
+ `@cetra.observe` traces a function, coroutine function, generator function or async generator function as one span. Both forms work: `@cetra.observe` and `@cetra.observe(name=..., kind=..., capture_input=..., capture_output=..., reduce_output=...)`. The span name defaults to the function's qualified name; `kind` defaults to `"chain"` and must be one of `llm`, `embedding`, `tool`, `agent`, `chain`, `retriever`, `reranker`, `guardrail`, `evaluator`, `span`. An invalid `kind` raises `ValueError` at decoration time, before the function runs. A function decorated before `init()` is traced once the SDK starts: the runtime is looked up at call time.
12
+
13
+ **Input.** The bound arguments with defaults applied, as one JSON object keyed by parameter name. A first parameter named `self` or `cls` is dropped, `*args` becomes a list and `**kwargs` an object under their parameter names. `capture_input=False` records no input.
14
+
15
+ **Output.** A `str` return value is recorded as text; anything else is serialized to compact JSON (dataclasses, pydantic v2 models, enums, UUIDs, datetimes, `bytes` as base64 data URIs, mappings and sequences, with cycle and depth guards). Payloads over 1 MiB are cut and marked `…[cetra: truncated, original N bytes]`. `capture_output=False` records no output. A plain function that *returns* a generator is traced as a call: the returned object is passed through untouched, never consumed, and its output is not recorded.
16
+
17
+ **Async.** The span of a coroutine function starts when the coroutine is first awaited, not when it is created.
18
+
19
+ **Generators.** Detected at decoration time. The span starts at the generator's first step and is current only while the body runs. Exhaustion records the items: the joined string when every item is a `str`, otherwise a JSON list, or `reduce_output(items)` when given. Closing early (`break`, `close()`, `aclose()`) ends the span with status `ok` and the items yielded so far. A half-consumed sync generator that is garbage-collected is closed the same way; an abandoned async generator is never exported (see [Known limits](https://cetra.sh/docs/reference/python/opentelemetry/#known-limits)), so `aclose()` it if you stop early.
20
+
21
+ **Errors.** An exception raised by the function adds one `exception` event (`exception.type`, `exception.message`, `exception.stacktrace`), sets the span status to error with the message `"<type>: <message>"`, and is re-raised unchanged. A `GeneratorExit` is not an error.
22
+
23
+ ## Manual spans and `llm_span`
24
+
25
+ `cetra.span(name, kind=..., input=..., metadata=...)` is a sync and async context manager. The body's return value is never recorded; the handle's setters write it instead.
26
+
27
+ ```python
28
+ import cetra
29
+
30
+ cetra.init(api_key="sk-cetra-test")
31
+
32
+ with cetra.span("rerank", kind="reranker", input=["a", "b"]) as s:
33
+ ranked = ["b", "a"]
34
+ s.set_output(ranked)
35
+ s.set_metadata(model="bge")
36
+
37
+ cetra.flush()
38
+ ```
39
+
40
+ The handle (`cetra.Span`) exposes `set_input(value)`, `set_output(value)`, `set_metadata(**values)` and the `trace_id` / `span_id` properties (32 and 16 lowercase hex characters). Every method is a no-op after the span ended and never raises.
41
+
42
+ `cetra.llm_span(name, provider=..., model=...)` writes the GenAI attributes of a chat call, for providers without an instrumentor. `provider` and `model` are required non-empty strings (a bad one raises `ValueError` at construction).
43
+
44
+ ```python
45
+ import cetra
46
+
47
+ cetra.init(api_key="sk-cetra-test")
48
+
49
+ with cetra.llm_span(
50
+ "chat",
51
+ provider="acme",
52
+ model="acme-1",
53
+ params={"temperature": 0.2},
54
+ input_messages=[{"role": "user", "content": "hi"}],
55
+ ) as s:
56
+ s.set_output_messages([{"role": "assistant", "content": "hello"}])
57
+ s.set_response_model("acme-1-2026-01")
58
+ s.set_usage(input_tokens=12, output_tokens=3)
59
+ s.set_cost(total_usd=0.0004)
60
+ s.record_first_token()
61
+
62
+ cetra.flush()
63
+ ```
64
+
65
+ Messages may use the canonical `{"role", "parts"}` form or the short form `{"role", "content": "<text>"}`, converted to one text part. On the `cetra.LlmSpan` handle:
66
+
67
+ | Setter | Attribute |
68
+ |---|---|
69
+ | `set_input_messages(messages)` | `gen_ai.input.messages` |
70
+ | `set_output_messages(messages)` | `gen_ai.output.messages` |
71
+ | `set_response_model(m)` | `gen_ai.response.model` |
72
+ | `set_usage(input_tokens=, output_tokens=, cache_read_tokens=, cache_write_tokens=, reasoning_tokens=)` | the `gen_ai.usage.*` counts; ints >= 0 only, `input_tokens` includes cache tokens |
73
+ | `set_cost(total_usd)` | `cetra.cost.total` (USD, finite, >= 0) |
74
+ | `record_first_token()` | `cetra.ttft_ns`; only the first call counts |
75
+ | `set_metadata(**values)` | `cetra.metadata.<key>`, like every span |
76
+
77
+ The inherited `set_input` / `set_output` remain available for non-chat payloads. With `capture_content=False` the models, params, usage, cost and metadata are kept, but no messages, system instructions or input/output payloads are written.