# 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.

AI and LLM interview question Q238, Guardrails and AI safety. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-do-you-keep-api-keys-away-from-the-model

## Say it in 30 seconds

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.

## Say it in 2 minutes

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.

- **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.

*Diagram, The key never enters the model's view: The model sends a plain request with no key. Tool code takes the key from the secret store and makes the call. Only the reply comes back, and it holds no key.*
1. The model asks for claim 48213 by tool name, with no key.
2. The tool code takes the key from the secret store.
3. The call goes out with the key attached, from code.
4. Only 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.

```python
# 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:

```text
Model sends: {'tool': 'lookup_claim', 'args': {'claim_id': '48213'}}
Model sees: Claim 48213: open, waiting on documents
Key in what the model sends: False
```

## Does 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.

*Diagram, Keeping a deploy key out of a coding agent: The bad path puts the key in the agent's folder, where it reaches a log. The good path keeps the key in a proxy outside the sandbox, which makes the one allowed deploy call.*
1. The agent reads the file and takes the key into its context.
2. The key ends up printed in a log that many people can see.
3. The sandbox sends a plain call with no key in it.
4. The 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." Better: Rules 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." Better: Once 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." Better: Hiding 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?

A. The tool function adds the key from the secret store before the claims call.
B. The system prompt says: the claims key is PLACEHOLDER-NOT-A-REAL-KEY, use it for lookups.
C. The agent asks for lookup_claim with the claim number only, and nothing else.
D. The trace logger masks the key header before it writes each request.

**Answer:** B. The key sits in the system prompt, which the model reads on every call and can repeat when someone pushes it. Keep the key in a secret store and let code add it to the call.

**Quick check:** A coding agent needs a deploy key to ship its fix. Where should the key go?

A. In a .env file in the repo, so the agent can load it
B. Set as an environment variable in the sandbox the agent runs in
C. Held outside the sandbox by a proxy that adds it to the one deploy call
D. Pasted into the system prompt so the agent always has it

**Answer:** C. Anything inside the sandbox can be read or printed, including files and environment variables. A proxy outside the sandbox adds the key only on the one call that needs it.

## Can you answer these from memory?

**Flash cards**

- **Where should the real key live?** In your server or a secret store, never in the model's context.
- **Who adds the key to a call?** Your code or a proxy outside the agent, never the model.
- **Is an environment variable safe from the model?** No, if the agent can run code or read files where it sits.
- **Name four ways a key leaks to the model.** System prompt, files and documents, tool output, logs and traces.
- **Does hiding the key stop misuse?** No. Limit each key's scope, endpoints, spend and expiry too.
- **What is the backstop?** Redacting keys from outputs and logs, but never the only defence.

## Likely follow-up questions

- Q179 Excessive agency and least privilege? https://designervenkat.online/interview/ai/excessive-agency-and-least-privilege
- Q180 How do you sandbox code-running agents? https://designervenkat.online/interview/ai/how-do-you-sandbox-code-running-agents
- Q211 What is hidden context exposure (system prompt leakage)? https://designervenkat.online/interview/ai/what-is-hidden-context-exposure-system-prompt-leakage
- Q212 How do you detect and redact PII? https://designervenkat.online/interview/ai/how-to-detect-and-redact-pii
- Q213 What is sensitive information disclosure? https://designervenkat.online/interview/ai/what-is-sensitive-information-disclosure
- Q242 How do you log without storing sensitive data? (full answer coming)

## Learn it in depth

- [Protecting AI APIs](https://designervenkat.online/learn/ai-guardrails/api-protection)
