How Do You Keep API Keys Away From the Model?
Why the model should never hold your keys, where they leak from, and how a proxy or your own server adds them, explained for your AI interview.
In short
Keep API keys in your own server or a secret store, never in the model's prompt, files or tool output. The model asks for an action by name, and your code adds the key when it calls the outside service.
12 min readIntermediateCommon · estimateFacts checked 26 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
The model should never hold the key. It only asks for an action, like looking up a claim. My code, outside the model, makes the call and adds the key from a secret store. I also keep keys out of the system prompt, the files it reads and the logs. Even then a fooled model can still ask, so each key gets narrow access, an expiry and a spend cap.
The rule is simple: the model should never hold a key. A key is a secret that proves to a paid service that you are allowed to use it. Anything the model can read, it can repeat. That includes its system prompt, the documents it retrieves, the output of its tools and any log that records the conversation. So the key has to stay somewhere the model cannot see.
In practice, the model only writes a request: look up claim 48213. My code receives that request, checks it against a list of allowed tools, and makes the call itself. It takes the key from a secret store, a locked service made for this, and adds it on the way out. The reply goes back to the model without the key. If a key ever shows up in an output, a last-step filter removes it. That filter is only a backstop.
Watch out for the common mistakes. Putting the key in the system prompt leaks it as soon as someone gets the model to repeat its instructions. An environment variable only helps if the agent cannot run code or read files in that same place, because otherwise it can read the variable too. Hiding the key stops theft. Misuse needs its own limits, so each key should have narrow access, a list of allowed endpoints, a spend cap and an expiry date.
In an interview, name the place the key lives, the four routes it can leak through, and what a fooled model can still do with a key it can reach.
What is an API key, in plain words?
An API key is a long secret string. It proves to a service, such as a model provider or a claims system, that your app may use it. Anyone holding the key can make requests as you, and those requests can cost money or read data.
A model reads everything in one stream of text: its instructions, the user's message, the documents it fetched and the output of its tools. Anything in that stream can be repeated, quoted or leaked. So the rule is that the model never gets the key, not even hidden in its instructions.
Think of a bank teller. The teller can open the vault, but never hands the vault key across the counter, even to a customer who asks nicely. The teller asks the vault for the money, checks the amount and passes over only that.
A real case: an insurer's claims assistant helps an adjuster. The model asks to look up claim 48213. Code behind it holds the claims key, makes the call, and returns only the claim's status to the model.
Key words
- API key
- A secret string that proves your app may use a paid or private service.
- Secret store
- A locked service built to hold keys and hand them to code that needs them.
- Proxy
- A middleman server that adds the key to a request before it leaves.
- Tool call
- The model asking your code to do something, such as look up a claim. Your code runs it.
- Context
- Everything the model reads in one request, which it may repeat back.
Where should the key live?
Keep the key in a secret store, and let code outside the model use it. OpenAI's guidance is to route requests through your own server, so the key never reaches a user's device. Anthropic describes the same idea as a proxy, a middleman that adds the key to each request.
“Do not embed credentials, secrets, or security-critical configuration directly in the system prompts or hidden context.”
OWASP, LLM08:2026
“rather than giving an agent direct access to an API key, you could run a proxy outside the agent's environment that injects the key into requests.”
Anthropic, Securely deploying AI agents
The model only asks. Code checks the ask, adds the key and makes the call.
The key never enters the model's view
Claims model
Asks for an action, holds no key
Secret store
Keeps the real key, locked away
Tool code
Checks the call, adds the key
Claims system
Gets the call with its key
- 1The model asks for claim 48213 by tool name, with no key.
- 2The tool code takes the key from the secret store.
- 3The call goes out with the key attached, from code.
- 4Only the reply comes back to the model, and it holds no key.
How does a key leak into the model?
A key reaches the model by four routes. Check all four when you review an agent, because each one is easy to miss.
The system prompt
Instructions the user never sees, but the model reads on every call and can repeat under pressure.
Files and retrieved documents
A .env file in a coding agent's folder, or a page the search tool fetched, can carry the key into the context.
Tool output and errors
A command that prints its environment, or an error that shows the full request, puts the key back in view.
Logs, traces (step-by-step call records) and memory
Some observability tools record full prompts and replies by default, so the key can land in a log that many people can read.
OWASP's 2026 list names API keys among the hidden context that can be exposed. It also notes that some observability tools log full prompts and traces by default. A key that gets into a log is a leaked key, even if the model never printed it.
Tip
A .env file in the agent's folder can leak the key. Even read-only access to a code folder can expose credentials, so keep those files out of the agent's reach.
Here is the pattern in plain Python. The model's request has no key, and the tool code adds it.
# A made-up claims assistant. The model only asks for a tool by name.
# The real key sits in a store the model never sees.
SECRET_STORE = {"claims_api": "PLACEHOLDER-NOT-A-REAL-KEY"}
def model_asks():
# What the model may send: a tool name and plain arguments, no secrets.
return {"tool": "lookup_claim", "args": {"claim_id": "48213"}}
def run_tool(call):
if call["tool"] != "lookup_claim":
return "BLOCKED: tool not on the list"
key = SECRET_STORE["claims_api"] # code adds the key, outside the model
headers = {"Authorization": "Bearer " + key}
# Stand-in for the real claims call, which would send the headers above.
reply = "Claim " + call["args"]["claim_id"] + ": open, waiting on documents"
assert key not in reply # the model's view never holds the key
return reply
call = model_asks()
print("Model sends:", call)
print("Model sees:", run_tool(call))
print("Key in what the model sends:", "PLACEHOLDER" in str(call))Output
Model sends: {'tool': 'lookup_claim', 'args': {'claim_id': '48213'}}
Model sees: Claim 48213: open, waiting on documents
Key in what the model sends: FalseDoes keeping the key hidden also stop misuse?
No. Hiding the key stops someone stealing it. A fooled model can still use a key it can reach through a tool. So you limit what each key can do, as well.
- 1
Give each key the least access
A claim lookup key reads claims. It cannot pay them or change a policy. OWASP's advice is to give each operation only the access it needs (least privilege).
- 2
Allow only known addresses
The tool code calls one claims address (an endpoint) and nothing else, so a fooled model cannot send the key to an attacker's server.
- 3
Cap the spend and set an expiry
OpenAI's guidance is that keys can expire, and that spend limits with hard enforcement help limit the cost of a leaked key.
- 4
Check each tool call in code
The model can ask, but your code decides. Authorisation belongs in the component that runs the tool, outside the agent's context.
Redacting keys from outputs and logs helps too, but treat it as the last line. A regex or blocklist filter can miss a key that is encoded, for example in base64 or hex.
How would you keep a deploy key away from a coding agent?
A coding agent runs in your CI pipeline (the automatic build and test run each time code changes) to fix failing tests. It needs one deploy key to ship its fix. That key must never sit in its folder, its shell or its logs.
- Without the rule
The key sits in the folder
The deploy key is in a .env file the agent reads, and a test log prints it.
- With the rule
The key stays outside
The sandbox has no key. A proxy holds it and allows only the one deploy call.
Keeping a deploy key out of a coding agent
Key in the folder
Deploy .env file
Holds the real key in plain text
Agent reads it
The key lands in its context
Key outside the sandbox
Agent sandbox
Has no key, sends plain calls
Proxy
Adds the key, one allowed call
Key in a log
Printed in a test log
Deploy goes out
Key never entered the sandbox
- 1The agent reads the file and takes the key into its context.
- 2The key ends up printed in a log that many people can see.
- 3The sandbox sends a plain call with no key in it.
- 4The proxy adds the key, and the deploy goes out once.
What does the interviewer want to hear?
A strong answer covers
- Keys stay out of the model: the model asks, code acts.
- The four leak routes: system prompt, files, tool output, logs.
- A secret store or a proxy holds the real key.
- Environment variables and sandboxes: the agent sees what it can run.
- Least privilege, an endpoint allowlist, a spend cap and an expiry.
- Redaction is only a backstop.
Common traps
Trap"A stronger system prompt keeps the key safe."
BetterRules in the prompt are a partial control. An injected line can ask for the key, so keep it out of the context.
Trap"An environment variable keeps the key from the model."
BetterOnce the agent can run code or read files there, it can see the variable. Keep the key in a proxy outside. Environment variables still keep keys out of source code, which is a different risk.
Trap"Hiding the key means nobody can misuse it."
BetterHiding stops theft. Misuse needs its own limits: scope, endpoints, spend and expiry.
Can you spot the leak?
Spot the leak
Which setup puts the key where the model can read it?
Quick check
A coding agent needs a deploy key to ship its fix. Where should the key go?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
- Q179Excessive agency and least privilege?11 min
- Q180How do you sandbox code-running agents?11 min
- Q211What is hidden context exposure (system prompt leakage)?11 min
- Q212How do you detect and redact PII?13 min
- Q213What is sensitive information disclosure?12 min
- Q242How do you log without storing sensitive data?Coming soon
Learn it in depth
Last updated on 26 November 2026
Building an agent that calls paid or private APIs?
I design and build AI agents and the tool layer behind them, including the keys, permissions and logs. Book a short call and tell me which services your agent needs to reach.