Fireworks AI API from an Agent
Fireworks lets your agent call a second model as a tool, which means a model, not your code, is deciding how many tokens get spent. How to cap that spend with an allowlist and policy instead of trust.
Key takeaways
- -Fireworks lets your agent call a second model as a tool, which hands a language model control over how many tokens get spent.
- -The context length default silently truncates oversized prompts instead of erroring, so the call still returns a normal-looking answer built from an incomplete prompt.
- -Fireworks exposes quota methods that can update your own spending limit; leave them off the allowlist so no agent can raise its own cap.
- -Swytchcode caps output tokens and pins which models can be called through policy, backed by a local credential store the model never sees.
- -Inference calls have no side effect, so a retry is safe for correctness but still billed twice; cache by model and message hash to control cost.
There is a category of agent integration nobody writes about properly: your agent calling another model. Not the model running the agent, a second one it calls as a tool, because it is cheaper, faster, or better at one specific job.
Fireworks is a good place to do that, and it is also the point where your cost control quietly stops working. The usual assumption is that your own code decides how many tokens a call spends. Once an agent is choosing when to call a second model and what to send it, a language model is making that decision instead.
The risk is not that Fireworks is unreliable. It is that nothing stops a long-running agent from sending an oversized prompt and getting back a normal-looking answer anyway, or from reaching for an expensive model when a cheap one would do, with no obvious sign anything went wrong. Swytchcode's fix is to put a layer between the agent and the call that caps what gets spent and keeps that cap out of the model's hands.
The problem: a model decides how much your agent spends, and failures don't always look like failures
When an agent sends a prompt that is too long, the default behaviour is not to return an error. The request succeeds, computed from a prompt that was quietly cut down to fit, and the model answers based on whatever survived, which may be missing the actual question. For an agent this is a slow-burn problem: the same call works for weeks on short inputs, then starts producing subtly wrong answers once a conversation gets long, with a normal-looking response every time. Nothing in ordinary monitoring flags it, because nothing failed in the way monitoring expects a failure to look.
This is the exact shape of problem we wrote about in 200 OK but it failed: the call succeeded and the outcome is wrong.
The same dynamic shows up in spend. Fireworks exposes account-scoped methods that can list, retrieve, and update your own usage quotas. An agent that can see its own spending limit as just another field to edit is not under cost control. It is one confused tool call away from raising it.
How Swytchcode solves it
Swytchcode downloads Fireworks's full catalog of methods and lets you decide, one by one, which ones an agent is actually allowed to call. For a model-calling agent that usually means allowing the inference methods and nothing else. The quota-list, quota-retrieve and quota-update methods stay off the allowlist entirely, so no prompt, no injected instruction and no confused tool call can reach them, because the capability to call them does not exist in the first place.
The API key lives in a local store outside your project, encrypted at rest, and gets injected into the call only when it runs, so it never sits in the model's context, a log, or a prompt.
Setting up Fireworks with Swytchcode
npx swytchcode
swy login
swy init --mode=sandbox
swy get fireworks
swy auth connect fireworks # key goes to the local store, not your .env
swy auth status
swy discover "chat completions" --project fireworks
swy list methods fireworks
swy info <canonical_id>
swy add method <canonical_id> # inference only; not the quota-update methodsThat last comment matters: leave the quota methods out of the allowlist entirely. Keep --project fireworks on every discover call too, since "chat completions" matches a dozen model providers in the catalog, and run swy get before swy info, or info will report a real method as missing.
import { exec } from "@swytchcode/runtime";
const res = await exec("<fireworks chat-completions canonical_id>", {
body: {
model: "accounts/fireworks/models/<exact-model-name>",
messages: [{ role: "user", content: input }],
max_tokens: 512, // always set a ceiling
context_length_exceeded_behavior: "error" // never truncate silently
}
});
// completion_tokens is optional; derive it so accounting never breaks
const { prompt_tokens, total_tokens, completion_tokens } = res.usage;
logSpend({ prompt_tokens, completion: completion_tokens ?? total_tokens - prompt_tokens });Policies: a spend cap the model can't argue with
This is the clearest use of argument-level policy anywhere in this series. The risk here is not destruction, it is an agent in a loop spending money, and the arguments it sends are exactly where the cost lives.
{
"id": "cap-output-tokens",
"target": ["<fireworks chat-completions canonical_id>"],
"when": { "field": "max_tokens", "operator": ">", "value": 2048 },
"action": {
"type": "DENY",
"message": "Agent requested more than 2048 output tokens on a sub-call"
}
}A deny rather than an approval request, because nobody wants a Slack message every time an agent gets ambitious about its output length. Add a second rule pinning which models may be called, so the agent cannot wander onto an expensive one mid-task. Check the available operators in the policy reference, and keep the file in version control so raising a cap is a reviewed change rather than a quiet one. That is the policy-as-code argument.
Fireworks is a hosted inference API an agent can call as a tool, priced by token volume rather than decided by your own code. The problem is that its default behaviour hides an overlong prompt behind a normal-looking response, and it exposes the very quota settings meant to cap spend as something an agent could, in principle, edit. Swytchcode solves both halves: an allowlist that leaves the quota-update methods off by default, and a policy layer that caps token spend and pins which models are callable, backed by a local credential store the model never sees.
Related reading
- Fireworks integration page
- Using the Hugging Face API from an AI Agent
- Luma API for AI Agents
- Securely Connecting the Claude API to Your Agent
- Browse all 300+ API integrations
FAQ
Can I point OpenAI SDK code at Fireworks and expect it to just work?
Mostly, and the gaps are the interesting part. Parameters follow OpenAI's conventions closely enough that most code ports over, but model names are full paths like accounts/fireworks/models/kimi-k2-instruct-0905 rather than short slugs, so a model asked to "call Kimi" will confidently invent a slug that doesn't exist; resolve real model names from the dashboard and keep them in config. Streaming responses include usage data by default, which the docs flag as unlike the OpenAI spec, so you can account for a streamed call without a separate lookup. And the context-length behaviour differs deliberately: port the code, then test the long-prompt and streaming paths specifically rather than assuming they match.
How do I stop an agent spending without limit?
Three layers, and you want all of them. A max_tokens ceiling on every call, a policy that denies calls above a threshold so the ceiling is not optional, and a provider-side quota the agent cannot modify because you never allowlisted the quota-update method.
Should the agent get to choose which model it calls?
Within a list you approved, yes, and it is often a good judgement call since it has the context. Across any model it can name, no. Pin the allowed set in policy so the choice is bounded.
What does the usage and token accounting data actually look like?
The usage object gives you prompt_tokens and total_tokens as required fields, plus completion_tokens, which is optional and nullable, and detail objects for prompt_tokens_details.cached_tokens and reasoning tokens. Do not write accounting code that assumes completion_tokens is present; derive it from total minus prompt if you need it guaranteed. Log the usage object on every call, because when a bill jumps, the only way to answer "which agent step got expensive" is per-call records.
Where do I see what it actually spent?
swy audit network gives you every call with its arguments, which maps to your bill, and swy audit policy shows the calls a cap stopped. If the second number is large, your prompts are asking for more than you think.
Can I build an AI agent on top of Fireworks with Swytchcode?
Yes. That is what the catalog and the allowlist are for: you decide which Fireworks methods an agent can reach, Swytchcode handles the credential, and anything you did not add to the allowlist simply is not callable.
Can Swytchcode stop an agent from raising its own spending quota, even if it's asked to?
Yes. If the quota-update method is never allowlisted, it is an absent capability, not a prompt instruction the model can argue with. No injected text, confused tool call, or direct request can reach a method that was never turned on.
If an agent retries a Fireworks call after a timeout, will Swytchcode let it duplicate the spend?
Inference is a POST with no side effect: running it twice gives you two answers, not a corrupted record, so there is no idempotency key protecting it. But each retry is still billed, so the duplicate cost is real even though the duplicate data risk is not. That is a caching and rate-limiting problem rather than an idempotency one: cache by model plus a hash of the messages, and cap retries, which is exactly the policy shown above.
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.
