Sub topic 2
Correlating LLM Calls with Request IDs
Assume you know basic Python, regular expressions, application logging, and how to call an LLM API. This chapter focuses on tracing a call without storing sensitive request data.
Correlating calls with request IDs
A request ID is a unique value assigned to one application request. Put it in every related log record, including the LLM call, so you can follow one request across services. A trace ID can connect several related requests.
Generate IDs at a trusted boundary, or reuse IDs supplied by your tracing system. Never use a user-provided value as an unrestricted log field.
import hashlib
import json
import logging
import re
import uuid
logger = logging.getLogger("llm")
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
SECRET = re.compile(r"\b(?:sk|key|token)[-_][A-Za-z0-9_-]{16,}\b")
def redact(text: str) -> str:
text = EMAIL.sub("[EMAIL]", text)
return SECRET.sub("[SECRET]", text)
def call_llm(client_call, model: str, prompt: str, trace_id: str) -> str:
request_id = str(uuid.uuid4())
record = {
"event": "llm_call",
"request_id": request_id,
"trace_id": trace_id,
"model": model,
"prompt_chars": len(prompt),
"prompt_sha256": hashlib.sha256(prompt.encode()).hexdigest(),
}
try:
response = client_call(model, prompt)
record.update(status="ok", response_chars=len(response))
return response
except Exception as exc:
record.update(status="error", error_type=type(exc).__name__)
raise
finally:
logger.info(json.dumps(record))
def fake_client(model, prompt):
return "Answer for " + model
logging.basicConfig(level=logging.INFO)
print(call_llm(fake_client, "example-model",
"Email [email protected]", "trace-123"))The default record contains metadata and a prompt hash, not the prompt itself. Do not log authorization headers, API keys, cookies, or complete provider request objects. Keep credentials in environment variables or a secret manager, and configure HTTP libraries to omit sensitive headers from request logs.
Redacting PII and secrets
Personally identifiable information (PII) identifies a person, such as an email address or phone number. Redact it before logging content. Apply redaction to prompts, responses, exception text, and headers that might contain copied values.
Pattern matching catches common formats, not every secret. Add tests for each discovered data type, and prefer removing fields at the source when possible.
Treating model output as untrusted log input
Prompts and responses can contain newlines, fake timestamps, or text that looks like log fields. Serialize records as JSON rather than concatenating strings. json.dumps escapes newlines, so model output cannot create extra log entries through the message field.
Exercise
Why should a request ID be logged while an API key should not?
Show answer
A request ID helps correlate records and is not an authentication credential. An API key grants access and must stay outside logs.