Use it in your project
Put your own agent on a Flagsmith experiment in six steps. The kit does what this study's runner does: one task is one identity, the flag's value is the routing policy, and four events carry the outcome.
Have a Flagsmith environment
You need a project with experimentation on and a server-side environment key. Flagsmith Cloud works as it is. To try everything on your own machine first, the repository brings up open-source Flagsmith 2.295.2 with experimentation enabled, in Docker Compose.
selfhost/bootstrap.sh # compose up, initialise, environment, keys, warehouse, CLI binding
selfhost/demo.sh # forkbill init + start experiment, forkbill demo, refresh, results
selfhost/demo.sh all # the same experiment in remote, local, edge and edge-local modesThe self-hosted path uses a fake agent loop: no model is called and no money is spent. It needs Docker with Compose v2, jq, curl, openssl and the Flagsmith CLI. Details and the verified run are in selfhost/README.md. To remove it again:
docker compose -f selfhost/docker-compose.yml --profile edge down -v && rm -rf selfhost/.stateGet the kit
Python
git clone https://github.com/Prashant-thakur77/fork-in-the-bill.git
cd fork-in-the-bill
uv syncPackage forkbill in kit/forkbill, Python 3.12 or later, Flagsmith SDK 6.7.0. uv sync also installs the forkbill command.
TypeScript
npm install forkbill @flagsmith/nodejsPackage forkbill 0.2.0 in kit/ts, Node 20 or later, @flagsmith/nodejs 9.5.0. To work on the package itself, build it from the repository:
cd kit
npm ci
npm run build --workspace forkbill # tsc, strict
npm test --workspace forkbill # node:test with a fake Flagsmith clientCreate the flag, the variant, the metrics and the experiment
One command creates the flag with your control policy as its value, a keyed variant for the challenger, the kill switch and the four metrics, and can create and start the experiment from your hypothesis file. Running it twice reuses what exists and stops on any difference.
uv run forkbill init --control flagsmith/policies/control.json \
--variant lanes_v1=flagsmith/policies/lanes_v1.json \
--metrics flagsmith/metrics.json \
--hypothesis-file prereg/experiment-1.md --startStart from this study's files and change the models: control.json, lanes_v1.json, metrics.json. Write the hypothesis and the decision rule down first. How this study registered its own.

Wrap your agent loop
The kit reads the policy once per task, which records the exposure, tells your loop which model to call in each lane, prices every call you report, and sends the events when the task ends. Your model calls and your stopping test stay yours.
import os
from flagsmith import Flagsmith
from forkbill import RoutedLanes, TablePricing, Usage
flagsmith = Flagsmith(environment_key=os.environ["FLAGSMITH_ENVIRONMENT_KEY"], enable_events=True)
pricing = TablePricing.from_json("harness/pricing.json")
lanes = RoutedLanes(flagsmith=flagsmith, identity=f"swelive:{instance_id}", pricing=pricing)
turns = 0
while not done and not lanes.over_budget and turns < lanes.policy.caps.turns:
turns += 1
reply = client.messages.create(model=lanes.main_model, max_tokens=lanes.policy.main.max_tokens, ...)
lanes.record_call("main", Usage.from_anthropic(reply.usage))
if needs_grunt_work:
sub = client.messages.create(model=lanes.delegate_model, max_tokens=lanes.policy.delegate.max_tokens, ...)
lanes.record_call("delegate", Usage.from_anthropic(sub.usage))
result = lanes.finish(solved=solved, turns=turns) # task_cost, task_solved, task_turns, task_seconds
flagsmith.close()For local evaluation or an Edge Proxy, build the client with forkbill.client.make_client(mode, ...) or flagsmithConfig(mode, ...). The four evaluation modes.
Run your tasks and read the result
Run each task through the loop. When the last one has finished, Flagsmith's results page shows, per metric, the chance each variant beats control. Read it against the rule you wrote down in step 3, then end the experiment with the winner as the rollout decision.
The kit sends events only for tasks that were exposed. A task under the kill switch, or one whose flag value was not a valid policy, runs control and is not counted.
task_costmean, primarytask_solvedoccurrence, guardrailtask_turnsmean, secondarytask_secondsmean, secondary
What this study's own run looked like, live: the board. What the result looked like: the results.
The MCP server
forkbill-mcp 0.3.0, Node 22 or later. It gives any agent that speaks MCP the same loop as tools, built on the forkbill kit. The server never chooses an arm: if Flagsmith cannot serve a valid policy, the tool returns Flagsmith's error and no models.
{
"mcpServers": {
"forkbill": {
"command": "npx",
"args": ["-y", "forkbill-mcp"],
"env": {
"FLAGSMITH_SERVER_KEY": "<your environment key>"
}
}
}
}get_routing_policyReturns the routing policy for one task and records the exposure.report_outcomeSends the task's cost, solve, turns and seconds as metric events.get_kill_switchReads the kill switch flag.explain_assignmentRe-derives an identity's arm from a saved environment document and shows the working.price_usageTurns token counts into dollars with the pricing table.register_decision_ruleRecords a rule file's SHA-256 for an experiment that has not started.get_experiment_resultsSummarises Flagsmith's results per metric: n, mean, chance to win, lift, interval, sample-ratio p.evaluate_decision_ruleApplies the registered rule and says ship or keep, with the reason per condition.propose_rolloutWrites a proposal with the exact End Experiment request and the approve command.apply_rolloutSends that request once a valid approval exists, reads it back, returns a receipt.watch_experimentPolls the results on an interval (default 6 min, up to a time limit) and writes the rollout proposal the first time the rule holds. Never applies.propose_flag_changeWrites a proposal to turn a feature on or off, set its value or its variant weights: the state read now, the exact Admin API request, what is served afterwards.apply_flag_changeSends that request once a valid approval exists, reads the flag back, returns a receipt.
Ending the experiment: the agent proposes, a person approves
5 of the tools end an experiment with a person in the middle. The agent registers the rule before the run, reads Flagsmith's results, applies the rule and writes a proposal with the exact End Experiment request. apply_rollout refuses until a person has approved that proposal at a terminal:
export FORKBILL_APPROVAL_SECRET_FILE=~/.forkbill-approval-secret # the same secret the server has
forkbill-mcp approve rp-1a2b3c4d5e6f7a8bThe approval is signed, expires and is used up by one apply. The server then sends the request, reads the experiment and the flag back and returns a receipt. A recorded run, refusal included.
Flagsmith needs the same four things as in step 3 before the first task. The tools' inputs and a worked example are in kit/mcp/README.md.
Toggle Wars
One project, four tracks
The kit, the tools and the skill on this page are entries in their own right. The project is entered in all four tracks, on the same flag and the same evidence.
- Track 01
Test Something Real
Three pre-registered experiments on one flag
Experiment 1 shipped lanes_v1. Experiment 2, a follow-up, lost and is published as run. Experiment 3 ran experiment 1 again on unused tasks, and it replicated.
−56.7% mean cost per task in experiment 1
- Track 02
AI Agents and Feature Flags
forkbill-mcp0.3.0An agent reads Flagsmith's results, applies the registered rule and proposes the rollout. Then it waits: nothing changes in Flagsmith until a person approves that exact proposal. In the recorded run a person read it at their own terminal and typed approve; the rollout followed seconds later. Flagsmith's own MCP server works alongside it to inspect the project and read the rollout back.
13 tools, 5 of them for the rule and the rollout
The approval exampleFlagsmith's MCP server, with oursThe person's approval, recordedkit/mcp/README.md
- Track 03
Build on Open Source Flagsmith
A one-command self-hosted starter
One command brings up open-source Flagsmith with Experimentation on your own machine, a sample app whose button is a flag, a pre-registered experiment on simulated visitors, and a results dashboard that applies the rule and shows flag changes from the webhook. From a fresh clone, with the images already pulled, it was ready in about three minutes.
Flagsmith 2.295.2, in Docker Compose
- Track 04
Flagsmith Agent Skills
A skill for the Flagsmith CLI
Takes a coding agent through one whole job with the Flagsmith CLI: set up an experiment, register the rule, read the result, and roll out the winner after a person agrees.
4,675 tokens for the whole job, 8,178 with the plain CLI
Run it on your own agent
The kit turns any agent loop into a two-lane loop driven by a Flagsmith experiment flag. It does what this study's runner does, so your own agent can answer the same question with the same method.
What it does for one task
One task is one Flagsmith identity.
- Reads
routing_killwithout an exposure. If it is on, the task runs control and is not counted. - Reads
agent_routingwithget_experiment_flag, which records the exposure, and validates the value as a routing policy. A bad value fails closed to control. - Tells your loop which model to call in each lane and prices every call you report.
- On
finish, sendstask_cost,task_turns,task_secondsand, on a solve,task_solved, flushing after each one.
Set up the flag, variants and metrics
One command creates everything, through the Flagsmith CLI.
forkbill init creates the flag with your control policy as its value, a keyed variant per challenger, the kill switch and the metrics, and can create and start the experiment from your pre-registration file. Running it twice reuses what exists and stops on any difference.
INIT_ARGS=(init --control "$P/control.json" --variant "lanes_v1=$P/lanes_v1.json"
--metrics "$ROOT/flagsmith/metrics.json" --ids-out "$STATE/ids.json")Policies: control.json, lanes_v1.json. Metrics: metrics.json.
Python quickstart
Flagsmith Python SDK 6.7.0. Package forkbill, in kit/forkbill.
git clone https://github.com/Prashant-thakur77/fork-in-the-bill.git
cd fork-in-the-bill && uv sync
PYTHONPATH=kit uv run python -m forkbill.cli --helpimport os
from flagsmith import Flagsmith
from forkbill import Lane, RoutedLanes, TablePricing, Usage
flagsmith = Flagsmith(environment_key=os.environ["FLAGSMITH_SERVER_KEY"], enable_events=True)
pricing = TablePricing.from_json("pricing.json") # USD per million tokens, your provider's prices
# One task = one Flagsmith identity. Reads the policy once and records the exposure.
lanes = RoutedLanes(flagsmith=flagsmith, identity=f"swelive:{instance_id}", pricing=pricing)
turns = 0
while not done and not lanes.over_budget and turns < lanes.policy.caps.turns:
turns += 1
reply = call_model(lanes.main_model, max_tokens=lanes.policy.main.max_tokens)
lanes.record_call(Lane.main, Usage.from_anthropic(reply.usage))
if needs_grunt_work:
sub = call_model(lanes.delegate_model, max_tokens=lanes.policy.delegate.max_tokens)
lanes.record_call(Lane.delegate, Usage.from_anthropic(sub.usage))
# Sends task_cost, task_turns, task_seconds and, on a solve, task_solved.
lanes.finish(solved=solved, turns=turns)
flagsmith.close()call_model, done and needs_grunt_work are yours. Everything else is the kit's public API. A fake loop that runs without any model is in kit/forkbill/demo.py.
TypeScript quickstart
@flagsmith/nodejs 9.5.0. Package forkbill 0.2.0, in kit/ts.
npm install forkbill @flagsmith/nodejsTo work on the package itself, it sits in an npm workspace under kit/ with the MCP server:
cd kit
npm ci
npm run build --workspace forkbill # tsc, strict
npm test --workspace forkbill # node:test with a fake Flagsmith clientimport { Flagsmith } from "@flagsmith/nodejs";
import { RoutedLanes, TablePricing, usageFromAnthropic } from "forkbill";
const flagsmith = new Flagsmith({
environmentKey: process.env.FLAGSMITH_SERVER_KEY!,
enableEvents: true,
// self-hosted: apiUrl: "http://localhost:8000/api/v1/",
// eventProcessorConfig: { eventsApiUrl: "http://localhost:8000/api/" },
});
const pricing = new TablePricing({
models: {
"<frontier-model>": { input: 3, output: 15, cache_write_5m: 3.75, cache_read: 0.3 },
"<small-model>": { input: 1, output: 5 },
},
}); // US dollars per million tokens; use the provider's current prices
const lanes = await RoutedLanes.create({ flagsmith, identity: `swelive:${instanceId}`, pricing });
let turns = 0;
while (!done && !lanes.overBudget && turns < lanes.policy.caps.turns) {
turns += 1;
const reply = await callModel(lanes.mainModel, lanes.policy.main.max_tokens /* ... */);
lanes.recordCall("main", usageFromAnthropic(reply.usage));
if (needsGruntWork) {
const sub = await callModel(lanes.delegateModel, lanes.policy.delegate.max_tokens /* ... */);
lanes.recordCall("delegate", usageFromAnthropic(sub.usage));
}
}
await lanes.finish(solved, turns); // seconds default to wall-clock time since create()
await flagsmith.close();Four evaluation modes
Pick where flags come from. Events always go to the core API.
| mode | flags come from | key |
|--------------|--------------------------------------------------|----------------|
| `remote` | the core API, one `POST /identities/` per read | any SDK key |
| `local` | the environment document, evaluated in process | server-side |
| `edge` | an Edge Proxy, one `POST /identities/` per read | any proxy key |
| `edge-local` | the environment document served by an Edge Proxy | server-side |In edge the Edge Proxy serves the right value but no variant, so no exposure is recorded and the kit sends no task events. Use edge-local to run an experiment through the proxy. forkbill compare reads the flag for the same identities in every mode and stops unless they agree. More on the Flagsmith page.
Through OpenFeature
Use the official Flagsmith provider behind the same RoutedLanes.
from flagsmith import Flagsmith
from forkbill.openfeature import OpenFeatureFlagsmith
flagsmith = Flagsmith(environment_key=..., enable_events=True)Install the extra with pip install fork-in-the-bill[openfeature]. The exposure is sent with OpenFeature track() by default; the provider's exposure hook is also supported.
Self-hosting
Open-source Flagsmith 2.295.2 with experimentation on, in Docker Compose.
selfhost/bootstrap.sh # bring up, initialise, create env + keys + warehouse, bind the CLI
selfhost/demo.sh # forkbill init + start experiment, forkbill demo, refresh, print results
selfhost/demo.sh all # the same experiment in the four evaluation modes belowThe demo uses the Flagsmith database as the warehouse, which suits a demo of a few hundred events. Full instructions, the verified run and the teardown command are in selfhost/README.md.