Using the Hugging Face API from an AI Agent
"The Hugging Face API" is really three APIs sharing one token, and the write one is almost never what an agent needs. How to scope the credential and the allowlist so a confused tool call can't reach it.
Key takeaways
- -"Hugging Face access" usually means one credential covering three different things: reading the Hub, running inference, and writing to the Hub.
- -A write-capable token handed to an agent means it can edit public model cards and repos, which is almost never what the task needed.
- -Use a fine-grained token scoped to one model or org per agent; a leaked read token exposes everything your account can see.
- -Swytchcode's allowlist keeps hub-write methods off by default, and policy pins which specific model an agent is allowed to call.
- -Inference calls have no side effect, so a retry duplicates cost, not data; cache by model and input hash rather than relying on an idempotency key.
Someone asks an agent to "pull the licence info for a few candidate models from Hugging Face so we can compare them." The agent looks the models up, reads the cards, and then, because the tool it was handed can also write, edits one of the model cards to leave a note for itself about which one it preferred. That model card is public. Dozens of other projects read it.
Nothing about the research task needed write access. The agent had it anyway, because "give the agent Hugging Face access" usually means handing over one token that can do far more than the task in front of it.
"The Hugging Face API" is really three different things wearing one name, and the difference decides how much damage a confused agent can do. The general problem is that one credential can span all three at once. Swytchcode's fix is to let you hand an agent exactly the slice it needs, and nothing else.
The problem: one token, three very different jobs
- Hub reads. Looking up models, datasets, metadata, model cards, downloading weights. Research and retrieval.
- Inference. Actually running a model on some input and getting a prediction back. This is the one most agents want: a classification step, an embedding, a reranker.
- Hub writes. Creating repos, pushing files, editing a model card. Almost never what an agent needs, and the one people accidentally enable.
That last point is worth sitting with. A write-capable token handed to an agent means the agent can modify a public model card, not because it wants to, but because a tool call went sideways or a document it read contained instructions. The fix is boring and effective: never give it a write token.
How Swytchcode solves it
Swytchcode downloads Hugging Face's catalog of methods and lets you turn on only the ones an agent actually needs, action by action. For a research or inference agent that means allowing hub-read and inference methods and leaving every hub-write method off the allowlist entirely, so there is no capability for a tool call, injected instruction, or confused prompt to reach.
The credential itself lands in a local store outside your project, encrypted at rest, and gets injected into the request only when a call runs. There is no environment variable sitting in your project for a model to read, which matters specifically with Hugging Face because its own Python libraries are designed to pick a token up from the environment, which is convenient in a notebook and a liability in an agent process.
Setting up Hugging Face with Swytchcode
npx swytchcode
swy login
swy init --mode=sandbox
swy get huggingface
swy auth connect huggingface # paste the FINE-GRAINED token here
swy auth status
# inference and hub reads are different methods; find both
swy discover "run inference on a model" --project huggingface
swy discover "get model info" --project huggingface
swy list methods huggingface
swy info <canonical_id>
swy add method <canonical_id> # allow inference + reads, nothing that writesPass --project huggingface on every discover call, because "run inference" matches a dozen model providers in the catalog, and run swy get before swy info, or info will claim a real method does not exist.
from swytchcode import exec
# canonical_id from `swy list methods huggingface`
res = exec("<hf inference canonical_id>", {
"params": {"model": "your-org/your-classifier"},
"body": {"inputs": ticket_text}
})
# the method was allowlisted; the token was injected; nothing to leak
label = res[0]["label"]Policies: build agents you can trust with a write token
The token type you choose is most of the security model here. Hugging Face gives you three roles, and the naming hides how different they are. A read token grants read access to every repo you can read, including private ones and your organisations', which is broader than it sounds: one leaked read token exposes everything your account can see. A write token is everything read can do, plus writing to anything you can write to, and it is for training jobs and model pushes, not agents. A fine-grained token scopes access to specific resources, such as one model or the models in one organisation; Hugging Face's own docs describe this as the type that is useful in production environments, and it is the only one where a leak has a bounded blast radius.
So the rule for an agent is one fine-grained token, scoped to the specific model or org it needs, per agent. Not a shared read token, and definitely not a personal write token that also happens to work.
Hugging Face also recommends one token per app or usage, so you can revoke the token for a misbehaving agent without taking down your CI, your notebook and your inference server at the same time. If you are wiring this into a pipeline, Trusted Publishers goes further still, exchanging a CI provider's OIDC token for a short-lived Hub token so there is no long-lived secret sitting in your settings at all, the same idea as credential brokering, applied upstream.
{
"id": "approved-models-only",
"target": ["<hf inference canonical_id>"],
"when": { "field": "model", "operator": "!=", "value": "your-org/your-classifier" },
"action": {
"type": "DENY",
"message": "Only the approved classifier may be called from this agent"
}
}That policy pins which models the agent may call, so it cannot wander off to some random community checkpoint, and a batch-size cap stops a loop running inference over an entire dataset. A deny rather than an approval request here, because "which model are we allowed to use" is a decision your team makes once, not something to interrupt someone about at runtime. Check the available operators in the policy reference and keep the file in version control, so swapping the model behind a production classifier is a reviewed change rather than a quiet one. See policy-as-code for AI agents.
Hugging Face is three APIs under one name: reading the Hub, running inference, and writing to the Hub. The problem is that a single token usually spans all three, so an agent that only needed to read a model card can end up able to edit one. Swytchcode solves it by scoping the allowlist to reads and inference, keeping write methods off entirely, and backing the model choice itself with policy so the model an agent calls is a reviewed decision rather than whatever it happened to pick.
Related reading
- Hugging Face integration page
- Keep API Keys Out of the LLM: Credential Brokering for AI Agents
- Securely Connecting the Claude API to Your Agent
- Luma API for AI Agents
- Browse all 300+ API integrations
FAQ
Can the agent download and run a model locally instead of calling a hosted endpoint?
It can, and that moves the problem rather than solving it: you now have weights on disk and a process that can execute arbitrary model code. For agent work, calling a hosted endpoint with a narrowly scoped token is usually easier to reason about and to get through review.
Do I need a dedicated inference endpoint, or is shared infrastructure fine?
If a human is waiting on the response, probably yes, because shared infrastructure has variable latency and cold starts: a model that has not been called recently may need loading, and the first request can be slow or come back saying it is not ready yet. Treat that as a retryable condition with backoff rather than a failure. For batch work on a schedule, shared infrastructure is fine and cheaper. Rate-limit responses are retried with exponential backoff automatically either way.
What is the single most important setting to get right?
The token type. A fine-grained token scoped to one model, created specifically for this agent, means a leak or a confused tool call cannot touch anything else you own. Everything else in this post is a refinement on that. Related thinking in best secrets management tools for AI agents.
Should I worry about a 200 response that isn't actually a clean prediction?
Yes. An inference response can be a perfectly valid 200 containing an error object or an empty result, which standard monitoring records as success and your agent treats as a real answer. Response validation catches it; the general pattern is in 200 OK but it failed.
How do I track what an agent is costing me on inference?
swy audit network gives you every inference call that actually ran, with arguments, which is the number that maps to your usage. If it is higher than you expected, you are missing a cache rather than a rate limit, since inference is a POST with no side effect: a cache keyed on model plus a hash of the input usually cuts call volume substantially, because agents re-ask the same question constantly inside a retry loop or a multi-step plan.
Can I build an AI agent on top of Hugging Face with Swytchcode?
Yes. The catalog and allowlist let you turn on exactly the hub-read and inference methods an agent needs, with the fine-grained token enforcing the same boundary at the credential level.
Can Swytchcode stop an agent from editing a model card or pushing a file, even if it's asked to?
Yes. If the hub-write methods are never allowlisted, they are an absent capability rather than a prompt instruction the model can argue with. A document containing injected instructions, or a user asking directly, has no write method to invoke.
If an agent retries an inference call after a timeout, will Swytchcode let it duplicate anything?
Inference has no side effect, so a retry produces a second prediction, not corrupted data; there is nothing for an idempotency key to protect. The real cost of a retry is paying for the same prediction twice, which is a caching problem rather than a deduplication one: cache by model plus a hash of the input rather than relying on a key Hugging Face's inference endpoints do not use.
More content
How to Stop an AI Agent From Booking the Same Meeting Twice
A scheduling agent that checks availability and then books the slot has a gap between those two steps — and a retry can fall straight into it. Here's how Swytchcode closes that gap.
How to Stop an AI Agent From Creating Duplicate Records
A retried "create" call doesn't update an existing contact, ticket, or row — it makes a second one. Here's why that happens across CRMs, databases, and ticketing tools, and how Swytchcode prevents it.
How to Stop an AI Agent From Sending the Same Email Twice
Most email APIs have no idempotency key to catch a repeat send, which makes a duplicate email a harder problem than a duplicate charge. Here's how Swytchcode handles the gap.
