The SDK talks only to a gateway: it never calls a provider itself. pip install theagentrouter installs the SDK (theagentrouter-core) and theagentrouter-local-gateway, which holds the aigw program; pip install theagentrouter-core is the SDK alone, for a remote gateway. The SDK starts it on the first call, writes its config from the provider keys in the environment, and sends every call through it. The developer runs no command. The SDK sends any format the gateway accepts (Claude in Anthropic Messages, the rest in OpenAI's), and holds no provider address, key or authentication of its own.
| Package | Contents | Wheels |
|---|---|---|
theagentrouter |
No code (packages/theagentrouter/, a hatchling wheel with bypass-selection). Depends on theagentrouter-core==<same version> and theagentrouter-local-gateway==<same version> on every platform, with no environment marker. Its empty local-gateway extra keeps older instructions working |
One wheel, metadata only |
theagentrouter-core |
The SDK, the repository's root package. Depends on httpx only; its local-gateway extra names the companion |
One pure-Python wheel |
theagentrouter-local-gateway |
theagentrouter_local_gateway/bin/aigw, binary_path() and has_binary() |
One per platform, built on that platform by local-gateway/hatch_build.py: macOS arm64 (macosx_13_0, the minimum read from the executable) and Linux amd64/arm64 (manylinux_2_36). Plus one py3-none-any fallback with no program (AGENTROUTER_NO_BINARY_WHEEL=1), which pip installs only where no platform wheel fits, so pip install theagentrouter never fails |
The second package lives in this repo under local-gateway/ and is released with the same version as theagentrouter. make local-gateway AIGW=/path/to/aigw puts a program in it and installs it for development.
The SDK never imports it at module load. local_gateway.installed() is checked only when a call needs the gateway: the package must be importable and has_binary() true, so the fallback wheel counts as not installed.
The macOS arm64 wheel is about 80 MB compressed (the program itself is 281 MB). That is under PyPI's default limit of 100 MB per file. The workflow checks the wheel metadata and builds Linux wheels too. Each wheel must fit PyPI's per-file limit before publication.
routing.resolve, first match wins:
api_baseon the call: that endpoint, in the provider's own format (LiteLLM's argument). It skips the gateway, so it warns once per address.- A gateway set with
AGENTROUTER_BASE_URL(orconfig.json). - A route name: the local gateway's route for it. The running gateway is used only if it has this computer's current routes (
routes_fingerprintinstate.json); otherwise it restarts. WithAGENTROUTER_AUTOSTART=0, a running gateway that already has the route is still used. - Anything else: the running local gateway, if it has a rule for this name and the name was not a route when it started (
local_gateway.serves). Otherwise, if the package is installed andAGENTROUTER_AUTOSTARTis not0, the gateway is started with this model, or restarted with a rule for it, as LiteLLM sends any name to the provider. With no package or no autostart, an error says to setAGENTROUTER_BASE_URL. Anapi_key=here cannot reach the provider (the gateway holds the keys), so it warns once.
State lives in AGENTROUTER_HOME/local-gateway/: config.yaml, state.json (pid, port, providers), aigw.log, lock, and aigw's own config and state folders. aigw's runtime folder, which holds Unix sockets, is a short path under /tmp, one per AGENTROUTER_HOME.
- A program takes a file lock on that folder before starting or restarting, so two programs never start two gateways.
- If
state.jsonnames a live process and its port accepts connections, the SDK uses that gateway. - Otherwise it writes
config.yaml, startsaigw runin its own session (so it outlives the program), and waits foraigw's "listening on" line and an open port. It prints the one-line notice once per start. - A call to a provider the running gateway lacks, with that provider's key set, stops the gateway and starts it again with every provider in this program's environment.
aigwreads its config once at start. - The very first start downloads Envoy into
~/.local/share/aigw(about 100 MB; older versions stay). The SDK setsENVOY_VERSION(local_gateway.ENVOY_VERSION, the 1.39 line that Envoy Gateway v1.9 targets) unless it is already set; without itaigwtakes the newest Envoy, and Envoy 1.40.0 does not start on macOS 14. - The gateway's own ports are chosen free at each start, so another gateway on 1975 does not block it; if a chosen port is taken before
aigwbinds it, the SDK chooses again (three tries).aigw's internal ports (1061, 18000) cannot move: when one is taken, the SDK names the program holding it (vialsof) and asks to stop it or setAGENTROUTER_BASE_URL.
local_gateway.stop() stops it; the docs give it as a python -c line. state.json records the SDK and companion versions. Existing rules are reused across versions; configuration changes require an explicit stop if another version started the process. Unknown models cannot restart an existing process; register custom models first.
The start lock times out after 30 seconds, since a start holds it for several seconds. The SDK checks that its runtime directory is owned by the current user, rejects symlinks, and sets mode 0700. It writes state atomically with mode 0600 immediately after spawning, so an interrupted start can be stopped and reaped. Stop removes generated key/state files once the process has stopped. Credential fingerprints detect supplied key changes: a program whose key differs from the running gateway's is refused until the gateway is stopped with local_gateway.stop(); the next call starts it with that program's keys. A process with no provider key can continue using an already configured provider, but cannot reconfigure the gateway while dropping its credentials.
The SDK writes the resources aigw run reads: a GatewayClass and Gateway at a free port chosen at each start (kept in state.json; --admin-port is chosen the same way), a buffer-limit ClientTrafficPolicy, a SecurityPolicy that answers only callers on this computer (127.0.0.1 and ::1; others get 403), one AIGatewayRoute, and per provider a Backend, a BackendTLSPolicy for HTTPS, an AIServiceBackend, a BackendSecurityPolicy and, for API keys, a Secret.
The SDK's config.yaml holds no key values. Each API key is written to its own file, keys/<VARIABLE> (mode 0600, in a 0700 folder), and the Secret names that file with aigw's substitution.aigw.run/file/ annotation, so aigw reads it when it starts. Stop removes the folder. An exported server config keeps ${OPENAI_API_KEY}-style references, filled in from the server's environment. Bedrock credentials come from aigw's own environment. aigw writes its translated resources and runtime configuration under aigw-state/. Those generated files can contain credentials. The end-to-end test checks the SDK input file and the key received by the provider; it does not assert that the upstream process keeps every generated file free of keys.
| Provider | Turned on when these are set | Schema |
|---|---|---|
| OpenAI | OPENAI_API_KEY |
OpenAI |
| Anthropic | ANTHROPIC_API_KEY |
Anthropic |
| AWS Bedrock | AWS_PROFILE, or AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY; and AWS_REGION or AWS_DEFAULT_REGION |
AWSBedrock, with the AWS default credential chain (no credentials file) |
| Gemini, Groq, Mistral, DeepSeek, Together | That provider's key (GEMINI_API_KEY and so on) |
OpenAI, with the provider's base path |
| Azure OpenAI | AZURE_API_KEY and AZURE_API_BASE; AZURE_API_VERSION optional (default 2024-10-21) |
AzureOpenAI with AzureAPIKey; the name after azure/ is the deployment, which aigw puts in the path |
Google Vertex AI is not set up yet. A call to it says so.
The local gateway runs the aigw release pinned in local-gateway/aigw-release.json, unchanged. Everything below is done in the config the SDK writes, with what that release offers.
Callers on other computers are refused. aigw run binds Envoy's listener to every address and has no setting to change it. The SecurityPolicy in the local config allows only 127.0.0.1/32 and ::1/128 and denies everything else with 403. Envoy Gateway matches these addresses against the connection's source address, not X-Forwarded-For, so a caller cannot claim to be local. It also allows only a Host of this computer's own address, so a web page cannot reach the gateway through DNS rebinding. A refused request never reaches a provider, so it never uses a provider key. The listener and the internal ports stay open on the network (see Known limits).
An exported server checks a client key. export_config() adds a SecurityPolicy whose authorization rules allow a request only when x-api-key equals ${AGENTROUTER_API_KEY}, or Authorization equals Bearer ${AGENTROUTER_API_KEY}. Everything else gets 403. aigw fills in the variable across the whole file when it starts. When the variable is missing or empty, the expected value becomes a line break (${AGENTROUTER_API_KEY:-\n}), which no request header can carry, so the server refuses every request. Each AIServiceBackend removes Authorization and x-api-key before the provider's own key is added, so a client key never reaches a provider. The config does not use Envoy Gateway's apiKeyAuth: that needs its keys in a Secret, and aigw run does not pass the Secrets in its config file on to Envoy Gateway.
A failed connection is tried again. A provider's name can resolve to an address that does not answer from your network. A BackendTrafficPolicy on the gateway retries a connection that failed, up to twice, because no request was sent on it. Routes have their own retry settings.
Configuration changes restart the gateway. aigw run reads its config once, at start. The SDK restarts the shared gateway for a new route, a model name it has no rule for, or a provider whose key the caller has. A gateway started by another SDK version raises instead of being replaced, and a caller without the keys of the providers already running raises. In these two cases the gateway keeps running. A rotated provider key is detected and refused until the gateway is stopped with local_gateway.stop().
No MCP session seed is set. aigw run always starts an MCP proxy and logs a warning that its session seed is the public default. aigw run has no setting for the seed. The SDK configures no MCP servers, so nothing sits behind the proxy.
The SDK sends the model name as the caller wrote it (bedrock/anthropic.claude-sonnet-4-5, claude-sonnet-4-5), on the same paths and in the same formats as to a gateway you set. There is no SDK-only header: the local gateway is stock Agent Router, and the same config serves a gateway that a team runs elsewhere.
aigw routes on the model name as it is sent and cannot strip a bedrock/ prefix. So the config has one route rule per model. Each rule matches the full name in the x-ai-eg-model header that aigw sets from the request, and for OpenAI and Anthropic the name without a provider too (gpt-4o-mini, claude-sonnet-4-5, as LiteLLM and Agent Router Enterprise write them). It passes the provider its own name with modelNameOverride.
- The rules cover the bundled model list for the providers whose keys are set. A model name without a rule restarts a same-version gateway with one, which interrupts other programs' requests, and a mistyped name does that too.
export_config()writes the same config for a server, on a fixed port. A server cannot add rules on demand, so it gets the bundled list plus the models named inmodels=.- Gateway API allows at most 16 rules in one route, and
aigwadds one rule of its own to eachAIGatewayRoute. So the rules are spread over severalAIGatewayRoutes of at most 15 (RULES_PER_ROUTE). A route with more never starts:aigwlogsHTTPRoute ... is invalid: spec.rules: Too manyonly with--debug, and waits.
Anthropic goes in its own format. This aigw build has no translation from OpenAI Chat Completions to the Anthropic schema ("unsupported API schema"). It takes Anthropic Messages as they are, under /anthropic/v1/messages (theagentrouter/agent-router internal/internalapi/internalapi.go). So for Anthropic the SDK sends Messages to that path. Every other provider gets Chat Completions on /v1/chat/completions.
A route (theagentrouter.route(), or LiteLLM's Router) becomes one AIGatewayRoute matching the route's name, with its models as backends at priority 0, 1, … (one per tier, models in a tier at the same priority), and a BackendTrafficPolicy that tries each tier attempts + 1 times before moving to the next. This is Agent Router's provider fallback, the way Agent Router Enterprise renders it. The SDK sends one request named after the route; the gateway does the retries and the fallback.
Every backend must be a hostname. Under aigw run, a backend written as an IP address gets its endpoints over EDS, and the AI Gateway extension server then labels the whole rule with its first backend (theagentrouter/agent-router internal/extensionserver/post_translate_modify.go, the LoadAssignment == nil case). A fallback is then sent the first backend's model name and key, and the priorities are lost. The same providers written as localhost fall back correctly. So the config writes 127.0.0.1 and ::1 as localhost. A provider at another IP address cannot fall back correctly until this is fixed in Agent Router.
Envoy looks up hostnames after it starts listening. Until it has, a fallback has nowhere to go, and requests sent right after the start get 503. So after a start the SDK waits, up to 15 seconds, until Envoy's /clusters lists a host for every backend of every route.
A route reaches Anthropic through its OpenAI-compatible endpoint (https://api.anthropic.com/v1, backend anthropic-openai), because routes go through the OpenAI format and aigw does not translate it to Anthropic Messages.
One request, different models. Any model in a route may get the request, so it has to suit them all. In a route of OpenAI or Azure with Anthropic, Gemini, Groq or Bedrock models, the SDK sends max_completion_tokens, because OpenAI's newer models refuse max_tokens and the others take it too. Any other route sends what the caller wrote, and if an OpenAI model refuses max_tokens, the SDK makes the call once more with max_completion_tokens. The backend of a newer Claude model has a bodyMutation that removes temperature and top_p, so a fallback to it does not fail on a setting the first model took. The mutation runs on the request as the backend gets it, so for Claude on Bedrock it names Converse's fields, and also removes the effort level the gateway would send there.
Request limits (Limit) go in the same BackendTrafficPolicy as the retry, because Envoy Gateway takes one per route: rateLimit.type: Local, one rule with requests and unit. Envoy's local rate limit filter answers 429 before the router, so a limited request is never retried. Two limits on what the local gateway can do:
- It counts requests, not tokens. Agent Router's token limits (
QuotaPolicy, usage-based rate limiting) need Redis and a rate-limit service configured in Envoy Gateway at install;aigw runhas neither, and Envoy Gateway's local rate limit cannot take a cost from the response (envoyproxy/gatewayv1.9api/v1alpha1/ratelimit_types.go, "response cost is not supported for Local Rate Limits"). - It needs an
aigwbuilt on Envoy Gateway newer than v1.8.1. With Envoy Gateway v1.8.1,aigw runrejects anyrateLimit: the schema declaresrequestsas int32 with a maximum of 4294967295, so validation fails for every value.
Embeddings need no config of their own: aigw sets the model header from the body on /v1/embeddings too, so the same per-model rules apply.
A prefix-strip option in Agent Router itself would replace the per-model rules with one rule per provider, and would let a stock gateway in Docker take provider/model names too. That needs a change in Agent Router first.
| What | Where |
|---|---|
Config per provider, no key in the file, one rule per model, rules spread over routes of 15; where calls go (not installed, the fallback wheel, AGENTROUTER_AUTOSTART=0, unknown provider, missing credentials, running gateway, set gateway wins, stale state, restart on a new provider, model or removed route) |
tests/test_local_gateway.py, tests/test_release_regressions.py, no aigw needed |
Real aigw against the fake provider: start on first call, key filled in by aigw, streaming tool call, Anthropic through the gateway, a second program reuses it, restart on a new key and model, the provider gets its own model name, error mapping, ports in use, Azure OpenAI's deployment path, api-key header and max_completion_tokens |
tests/test_local_gateway.py, skipped unless the package is installed |
Routes: config per model, retry policy, limits, the order models are tried, errors that do not move on, LiteLLM's Router, two programs defining routes at once |
tests/test_routes.py, tests/test_release_regressions.py |
Real aigw against two fake providers: fallback with each provider's own model name and key, retries then giving up, no retry on 401, Router with a fallback, a request limit answering 429, embeddings |
tests/test_routes.py, tests/test_embeddings.py, skipped unless the package is installed. CI runs them on every platform with a program, and none may skip |
| Real OpenAI and Anthropic through the real gateway, and a second program | scripts/smoke_local_gateway.py |
Real OpenAI and Anthropic routes: primary answers, a failing primary falls back to Anthropic, Router, a shared tier |
scripts/smoke_routes.py |
| Every example on real providers through the local gateway | scripts/smoke_examples.py, examples/ |
Run the real-provider scripts one at a time and stop the gateway between them: see DEVELOPMENT.md.
These are the things the local gateway cannot do today. This is the full list; other pages link here instead of repeating it.
- The gateway's ports listen on every address. Upstream Envoy Gateway binds Envoy's listeners and its own xDS (18000), wasm cache (18002) and health (8081) servers to every address, and upstream
aigw rundoes the same for the MCP proxy (9856), the external processor's admin port and Envoy Gateway's metrics (19001). TheSecurityPolicyrefuses any caller whose connection does not come from127.0.0.1or::1, so the network cannot reach the provider keys; the other ports stay open. Moving them to loopback needs changes in Agent Router and Envoy Gateway. - Fixed internal ports.
aigw runbinds fixed ports inside itself (extension server 1061, Envoy Gateway xDS 18000, health 8081, admin 19000 and others), so only one Agent Router gateway runs per computer. The SDK chooses its own listener and admin ports at each start and names the program holding 1061 or 18000. Moving the internal ones needs changes in Agent Router and Envoy Gateway. - Windows and Intel macOS have no program. Upstream provides macOS arm64 and Linux amd64/arm64 binaries only; those computers get the fallback wheel. The start lock and the route lock are POSIX only.
- Configuration changes restart the gateway.
aigwreads its config once, so a new route, model name or provider stops the shared gateway and starts it again, which interrupts other programs' requests and streams. - A rotated provider key needs a stop. The SDK detects that a caller's key differs from the one the gateway started with and refuses the call. Call
local_gateway.stop()when other programs have finished; the next call starts the gateway with the new key.aigw runcannot load a new key without a restart. - Backends at an IP address cannot fall back correctly until Agent Router labels each backend on its own (see "Routes").
- Request limits count requests, not tokens. Token limits need a Redis-backed rate-limit service, which
aigw rundoes not have (see "Routes"). - The MCP proxy uses the public default session seed.
aigw runalways starts an MCP proxy and has no setting for its seed. The SDK configures no MCP servers, so nothing sits behind the proxy. - Google Vertex AI is not set up. It needs Google Cloud credentials rather than a key;
aigwhas theGCPVertexAIschema.