Sub topic 14
Capturing prompts and responses safely
Prompts and responses are the most useful data in an LLM trace. They are also the riskiest. A prompt can hold a customer's name, an order number, a medical question, or a pasted API key. This chapter assumes you can create spans and set attributes (see the earlier chapters on spans and the GenAI conventions). It covers what to capture, where to put it, and how to remove sensitive data before it leaves your process.
Why content capture needs its own decision
Metadata such as model name, token counts and latency is low risk. Content is different, for three reasons:
- Privacy and compliance. Traces often go to a third-party backend with its own retention rules. Personal data in a span may fall under GDPR, HIPAA or your contract terms.
- Size. A prompt with retrieved documents can be tens of thousands of tokens. Span attributes of that size slow down export and raise storage cost.
- Secrets. Users and tools paste credentials into chats. Once a secret is in a trace, many people can read it.
The OpenTelemetry GenAI conventions treat prompt and response content as opt-in for these reasons. Instrumentation should not record it unless you turn it on. The same default is a good rule for your own code.
Where content can live
Content can be attached in three ways. Each has different trade-offs.
| Option | Where it goes | Good for | Drawbacks |
|---|---|---|---|
| Span attribute | On the span itself | Short, simple data | Size limits, always stored with the span |
| Span event | A timestamped event on the span | Per-message records, such as one event per chat turn | Still stored in the trace backend |
| External store | A separate store, with only a reference on the span | Large or sensitive content | More infrastructure |
The GenAI conventions are still evolving. Attribute and event names for content have changed between versions, so check the version you depend on. The examples below use names that follow the current convention style, but treat them as a pattern, not a fixed contract.
A capture switch controlled by configuration
Make content capture a setting you can change without editing code. An environment variable works well, and it defaults to off.
import os
def capture_content_enabled() -> bool:
return os.getenv("CAPTURE_LLM_CONTENT", "false").lower() in ("1", "true", "yes")OpenTelemetry's own GenAI instrumentation libraries use a similar environment variable. Its name has changed across releases, so confirm it in the documentation for the library you use.
Redacting before you record
Redaction must happen before the data is attached to a span. If you redact in the Collector only, the raw content still travels from your app to the Collector. A Collector processor is a useful second layer, not the first one.
The function below masks email addresses, long digit sequences such as card or phone numbers, and strings that look like API keys. It is a starting point. Real systems often use a dedicated PII detection library.
import re
PATTERNS = [
(re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"), "[EMAIL]"),
(re.compile(r"\b(?:sk|pk|key|token)[-_][A-Za-z0-9_-]{16,}\b"), "[SECRET]"),
(re.compile(r"\b\d[\d -]{8,}\d\b"), "[NUMBER]"),
]
def redact(text: str) -> str:
for pattern, replacement in PATTERNS:
text = pattern.sub(replacement, text)
return text
def truncate(text: str, limit: int = 2000) -> str:
if len(text) <= limit:
return text
return text[:limit] + f"... [truncated {len(text) - limit} chars]"
if __name__ == "__main__":
sample = "Email [email protected], card 4111 1111 1111 1111, key sk-abcdefghijklmnop1234"
print(truncate(redact(sample)))Running it prints Email [EMAIL], card [NUMBER], key [SECRET]. Regular expressions miss names, addresses and free-form details. Treat redaction as risk reduction, not a guarantee.
Putting it together on a model call
This version of the traced chat function records content only when the switch is on, and it always redacts and truncates first. It records the messages as span events, one per message.
import json
import os
import re
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
tracer = trace.get_tracer("support_agent")
_EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
def redact(text):
return _EMAIL.sub("[EMAIL]", text)
def truncate(text, limit=2000):
return text if len(text) <= limit else text[:limit] + "...[truncated]"
def capture_content_enabled():
return os.getenv("CAPTURE_LLM_CONTENT", "false").lower() in ("1", "true", "yes")
def call_model(messages):
return {"text": "Sure, I emailed [EMAIL].", "input_tokens": 12, "output_tokens": 6}
def traced_chat(messages, model="example-model"):
with tracer.start_as_current_span(f"chat {model}", kind=SpanKind.CLIENT) as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.request.model", model)
capture = capture_content_enabled() and span.is_recording()
if capture:
for m in messages:
span.add_event(
"gen_ai.content.prompt",
{"role": m["role"], "content": truncate(redact(m["content"]))},
)
try:
result = call_model(messages)
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
raise
span.set_attribute("gen_ai.usage.input_tokens", result["input_tokens"])
span.set_attribute("gen_ai.usage.output_tokens", result["output_tokens"])
if capture:
span.add_event(
"gen_ai.content.completion",
{"content": truncate(redact(result["text"]))},
)
return result["text"]Points to notice:
span.is_recording()skips the work for spans that sampling dropped. Redacting large prompts costs CPU, so avoid it when nothing will be stored.- The error status uses the exception type, not
str(exc). Exception messages from API clients sometimes echo part of the request. The earlier chapter's version usedstr(exc). Switch to the type name if your errors might carry content. record_exceptionalso stores the exception message and stack trace as an event. Apply the same caution there.
Storing a reference instead of the content
For large or highly sensitive content, write it to a store you control, such as an access-controlled bucket, and record only an identifier on the span.
import hashlib
def content_reference(text: str) -> dict:
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()
return {"app.content.sha256": digest, "app.content.length": len(text)}A hash lets you check that a stored prompt matches the trace without exposing it. A hash of a short or predictable string can be guessed, so do not use a bare hash as a stand-in for private data. You can then use this pattern: save the full text under a key in your own store, attach the key to the span, and apply your normal access controls and retention to that store.
Defense in depth with the Collector
The Collector can drop or rewrite attributes before data reaches the backend. This catches mistakes in application code. The attributes processor below deletes a content attribute and hashes a user identifier.
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
attributes/scrub:
actions:
- key: app.user.email
action: delete
- key: enduser.id
action: hash
batch: {}
exporters:
debug:
verbosity: basic
service:
pipelines:
traces:
receivers: [otlp]
processors: [attributes/scrub, batch]
exporters: [debug]This processor works on attributes of spans. Content stored in span events needs a different processor, such as the transform processor from the Collector contrib distribution. Check which components your Collector build includes.
Common mistakes
- Capturing by default. Developers turn content on locally and forget it in production. Make off the default and set it per environment.
- Redacting only in the backend. Data is already stored and sent across the network by then.
- Logging content elsewhere. Instrumentation libraries and debug loggers may record the same prompts. Check them too.
- Forgetting retention. Even redacted traces should expire. Set a short retention for traces that include content.
- Trusting regular expressions. They catch patterns, not meaning. Combine them with a switch, truncation and access control.
- Unbounded attribute size. Without truncation, a single huge prompt can bloat the span or be dropped by an SDK attribute length limit.
Decision checklist
- Do you need content for this environment? If not, capture metadata only.
- Is the content small enough for a span? If not, store a reference.
- Is it redacted in the application before recording?
- Does the Collector scrub anything that slips through?
- Who can read the backend, and how long are traces kept?
Exercise
A teammate enables prompt capture in production and relies on a Collector processor to remove emails. Name two problems with this setup and one fix for each.
Show answer
First, the raw prompts, including emails, still leave the application and cross the network to the Collector, so redaction should also happen in the app before the data is attached to the span. Second, the Collector's attribute processor only covers span attributes and patterns it is configured for, so content in span events or unusual formats can slip through. Fix this by adding a transform processor for events, or by storing content outside the trace and keeping only a reference. Making capture opt-in through a configuration switch that defaults to off also limits the exposure.
Exercise
Why does the example call span.is_recording() before redacting content?
Show answer
When sampling drops a span, nothing is stored. Redacting a large prompt for a span that will be discarded wastes CPU, so the code skips the work.