Sub topic 15
Production practices: secrets, logging and safe handling of output
This chapter covers the habits that keep an LLM integration from leaking credentials, leaking user data, or turning model text into a security hole. It assumes you can already send a chat request, read usage and finish_reason, and apply retries and timeouts. You also need to be comfortable with environment variables, Python logging, and the difference between trusted and untrusted input.
Keeping secrets out of source code
An API key is a bearer credential. Anyone who holds the string can spend your money and read whatever your account's usage exposes. Treat it like a password.
Rules that apply in almost every deployment:
- Read the key from an environment variable or a secret manager at startup. Never write it in source files, notebooks, Dockerfiles, or command lines saved in shell history.
- Keep local
.envfiles out of version control by adding them to.gitignorebefore the first commit. - Use a separate key for each environment (development, staging, production) and, where the provider allows, for each service. A leak then has a small blast radius and you can revoke one key without an outage elsewhere.
- Grant the least privilege the provider offers, such as project-scoped keys or spending limits.
- Never ship a key to a browser or mobile app. Client code can be inspected. Route calls through your own backend, which authenticates the user and then calls the LLM API.
Fail fast when a secret is missing. A clear startup error is better than a confusing 401 on the first user request.
import os
import sys
def require_env(name):
value = os.environ.get(name)
if not value:
sys.exit(f"Missing required environment variable: {name}")
return value
API_KEY = require_env("OPENAI_API_KEY")
MODEL = require_env("LLM_MODEL")
print("Configuration loaded.")Note that the code prints a fixed message and not the key. A common accident is logging the whole configuration object at startup.
If a key leaks
Assume it is compromised the moment it appears in a public repository, a ticket, or a log line. Deleting the commit is not enough, because automated scanners copy keys within minutes and git history keeps old versions.
- Revoke or rotate the key in the provider console.
- Create a replacement and deploy it through your normal secret channel.
- Check the provider's usage page for calls you did not make.
- Find how the key escaped and fix that path.
Logging what matters
Logs are how you debug rate limits, slow calls and cost surprises. They are also a second copy of your data, often with weaker access control than your database. Decide deliberately what goes in.
Log these by default:
- A request identifier you generate, so you can match a log line to a user report.
- The model name, HTTP status, latency, and retry count.
finish_reason,prompt_tokens, andcompletion_tokensfromusage. These let you find truncated replies and compute spend.- Sizes (character or message counts) in place of content.
Leave these out unless you have a reason and a retention policy:
- The
Authorizationheader or any key. - Full prompts and replies. Users paste personal data, contracts and credentials into chat boxes, and your logs will then hold them.
- Raw request objects dumped on error. Exception handlers that print
resp.request.headersleak the key.
If you must keep content for debugging, redact first, sample a small fraction, and expire it quickly.
import json
import logging
import re
import time
import uuid
logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger("llm")
KEY_PATTERN = re.compile(r"sk-[A-Za-z0-9_\-]{8,}")
EMAIL_PATTERN = re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+")
def redact(text):
text = KEY_PATTERN.sub("[REDACTED_KEY]", text)
return EMAIL_PATTERN.sub("[REDACTED_EMAIL]", text)
def log_call(payload, data, started):
choice = data["choices"][0]
log.info(json.dumps({
"request_id": str(uuid.uuid4()),
"model": payload["model"],
"latency_ms": round((time.monotonic() - started) * 1000),
"finish_reason": choice["finish_reason"],
"prompt_tokens": data["usage"]["prompt_tokens"],
"completion_tokens": data["usage"]["completion_tokens"],
"prompt_chars": sum(len(m["content"]) for m in payload["messages"]),
}))
if __name__ == "__main__":
payload = {"model": "demo-model", "messages": [{"role": "user", "content": "Hi"}]}
data = {
"choices": [{"finish_reason": "stop"}],
"usage": {"prompt_tokens": 9, "completion_tokens": 3},
}
started = time.monotonic()
log_call(payload, data, started)
print(redact("Contact [email protected], key sk-abcdef123456"))The demo uses a fake response so you can run it without a key. Pattern-based redaction catches common shapes only. It is a safety net, not a guarantee, so the stronger control is not logging content at all.
Treating model output as untrusted input
The model produces text by predicting likely tokens. It can be wrong, and an attacker can influence it. Text that reaches the model from a web page, an email, a document or another user can contain instructions ("ignore previous instructions and..."). This is called prompt injection, and no prompt wording fully prevents it. So the output of the model has the same trust level as any other input from outside your system.
The practical consequences:
- Rendering. Escape output before putting it in HTML. Model text can contain
<script>tags, either by accident or after an injection. If you render Markdown, use a renderer with HTML disabled or a sanitizer. - Execution. Never pass model output to
eval,exec,os.system, or a shell. If you need generated code to run, use a sandbox with no network, no secrets and strict time and memory limits. - Queries. Never concatenate model output into SQL. Use parameterized queries, the same as for user input.
- Structure. When you ask for JSON, parse it and validate field names, types and allowed values. Treat a parse failure as a normal case with a defined fallback.
- Actions. If the model chooses an action or a tool, check it against an allowlist in your code. Check permissions for the current user, not for the model. A model that can call "delete record" on behalf of any user is an access-control bug.
import html
import json
ALLOWED_ACTIONS = {"refund", "escalate", "close"}
def render_as_html(model_text):
return f"<p>{html.escape(model_text)}</p>"
def parse_decision(model_text):
try:
obj = json.loads(model_text)
except json.JSONDecodeError as exc:
raise ValueError("model did not return valid JSON") from exc
if not isinstance(obj, dict):
raise ValueError("expected a JSON object")
action = obj.get("action")
if action not in ALLOWED_ACTIONS:
raise ValueError(f"action not allowed: {action!r}")
return action
print(render_as_html("<script>alert(1)</script>"))
print(parse_decision('{"action": "escalate"}'))
try:
parse_decision('{"action": "delete_everything"}')
except ValueError as err:
print("rejected:", err)Validation protects you from malformed output. It does not make a wrong answer correct. For high-stakes decisions such as money, medical or legal content, keep a human review step or a deterministic check.
Other production controls
| Risk | Control |
|---|---|
| Runaway cost from a loop or abusive user | Per-user rate limits, a cap on `max_tokens`, and a provider spending limit |
| Oversized input | Reject or truncate by token count before sending |
| Personal data sent to a third party | Minimize what you send, and check the provider's data retention and training terms |
| Provider outage | Bounded retries, timeouts, and a fallback message |
| Stale or leaked prompts | Keep system prompts in version control, but never put secrets in them |
Never place secrets in a prompt. The model can repeat anything in its context, and an injection can ask it to.
Also set alerts on spend and error rate. A cost graph that climbs overnight is often the first sign of a leaked key or a retry bug.
Exercise
A teammate's error handler prints the full requests exception, including the request headers, to the application log. Why is this a problem, and what two changes would you make?
Show answer
The request headers contain Authorization: Bearer <key>, so the key is copied into logs that many people and tools can read. Change the handler to log only the status code, request ID and error type, and rotate the key because it has already been exposed in the logs.
Exercise
A support bot asks the model to return JSON like {"action": "refund"} and then runs whatever action name comes back. A customer pastes text telling the model to answer {"action": "exportallusers"}. Which control stops this, and where does it live?
Show answer
An allowlist of permitted actions, checked in your application code after parsing and validating the JSON. The check must also confirm the current user may perform the action. Instructions in the prompt alone cannot be relied on.