Sub topic 15
Production practices: secrets, logging and safe handling of output
This chapter assumes you can send a chat request, read the response, and handle retries as covered earlier. You should also be comfortable with environment variables and basic Python. Here you will harden a working client for production. The three areas are secrets, logs, and the model's output.
Keep secrets out of code
An API key lets anyone who holds it spend your money and read your usage. Treat it like a password.
- Read keys from environment variables or a secret manager, never from source files.
- Keep
.envfiles out of version control by adding them to.gitignore. - Use a separate key for each environment and each service, so you can revoke one without breaking the others.
- Rotate keys on a schedule and immediately after any suspected leak.
- Never ship a key in browser or mobile code. Call the API from your own server and authenticate your users there.
Fail fast when a key is missing, so you see a clear error at startup instead of a confusing 401 later.
import os
def require_env(name):
value = os.environ.get(name)
if not value:
raise RuntimeError(f"Missing required environment variable: {name}")
return value
API_KEY = require_env("OPENAI_API_KEY")
MODEL = require_env("LLM_MODEL")
print("Configuration loaded for model:", MODEL)Log carefully
Logs help you debug and track cost, but they are also a place where secrets and personal data leak. Log metadata, not content.
| Log this | Avoid logging this |
|---|---|
| Request ID, timestamp, model name | The `Authorization` header |
| HTTP status code and latency | Full prompts and replies by default |
| Token counts from `usage` and `finish_reason` | Personal data typed by users |
| Retry attempt number | Raw error bodies that echo your input |
If you must store prompts for debugging, redact obvious sensitive values first and set a short retention period. The function below records only safe metadata from a response.
import logging
import time
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("llm")
def log_call(data, started):
choice = data["choices"][0]
usage = data.get("usage", {})
log.info(
"model=%s finish_reason=%s prompt_tokens=%s completion_tokens=%s latency=%.2fs",
data.get("model"),
choice.get("finish_reason"),
usage.get("prompt_tokens"),
usage.get("completion_tokens"),
time.time() - started,
)Treat model output as untrusted input
The model produces text that is shaped by user input, and users can try to manipulate it. A prompt injection is text that tries to override your instructions, and it can arrive inside a document or web page you pass to the model. So handle the reply the way you would handle any data from a stranger.
- Escape the text before putting it in HTML, or render it as plain text, to prevent cross-site scripting.
- Never pass model output to
eval, a shell, or string-built SQL. Use parameterized queries. - Validate structured output against a schema before acting on it.
- Check
finish_reason. A value oflengthmeans the reply was cut off and may be incomplete. - Require human approval, or an allow-list of actions, before the model can trigger anything that is hard to undo.
import html
def render_reply(reply):
return "<p>" + html.escape(reply) + "</p>"
print(render_reply("<script>alert('x')</script>"))The output is <p><script>alert('x')</script></p>, which a browser shows as text instead of running it.
How the pieces fit
Common mistakes
- Printing the full request headers while debugging, which writes the key to the logs.
- Putting the key in a frontend bundle because it is "only a demo".
- Trusting the model's reply as safe HTML or as a valid command.
- Ignoring
finish_reasonand acting on a truncated answer.
Exercise
A teammate's debug code logs the full request, including headers and the prompt, for every call. Name two problems with this and what you would log instead.
Show answer
The Authorization header exposes the API key to anyone who can read the logs, and the prompt may contain personal data from users. Log only metadata: model name, status code, latency, finish_reason and token counts from usage, plus a request ID.
Exercise
The model returns text that your app inserts directly into a web page. What risk does this create, and how do you reduce it?
Show answer
The reply could contain markup or script, either from a user's manipulation or from a prompt injection, which would run in the reader's browser (cross-site scripting). Escape the text, or render it as plain text, before display.