ktms

module
v1.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: Apache-2.0

README

Keystone. The Model Switchboard. (KTMS)

CI Buf Go Report Card Release Docker Image

A self-hosted LLM gateway and model switchboard. Your services talk to one endpoint; Keystone holds the vendor API keys, decides which model answers each request, falls back when a vendor is down, enforces rate and spend limits, and records usage. One Go binary: ~67 MB image, ~7 MiB idle RAM, under 1 ms of added latency.

Features

  • One place for vendor keys. OpenAI, Anthropic, Google Gemini, DeepSeek and TypeSafe credentials live encrypted in Postgres (AES-256-GCM); clients never see them. → Vendor keys, rotating the encryption key
  • Routing by rules, not code. Clients send their needs (medical: basic) and free-form attributes; models declare competencies. Ordered rules map them to a model chain with fallbacks, and a request no rule takes gets the cheapest models that fit. All of it changes at runtime without a redeploy. → Models and rules, Concepts
  • Configuration as code. One YAML file, planned and applied like Terraform. → Configuration as a file
  • Limits and money. Requests per minute, daily token budgets and hard USD caps per key and per end user; organizations and teams. → Spend limits, Organizations and teams
  • Resilience. Same-model retry, Retry-After back-off, circuit breakers and fallback across vendors. → Concepts, When a dependency fails
  • More than text. Streaming, structured (JSON-schema) output, batches at 50% discount, speech, images, typed judgments, embeddings and translation. → Calling Keystone
  • Drop-in APIs. OpenAI-compatible /v1, the OpenAI Responses API and the Anthropic Messages API: point an existing SDK, Codex CLI or Claude Code at Keystone. → HTTP APIs
  • Your own hardware. Ollama, vLLM, llama.cpp, FreeToken or a translation engine on a Mac or a GPU box, with cloud fallback; restricted data never leaves them. → Nodes, Restricted data
  • MCP gateway and agents' inbox. MCP servers behind one key with per-tool limits, and an inbox where agents send each other tasks. Experimental. → MCP gateway, Agents
  • Usage and observability. One event per call to light-tokenmeter, Prometheus metrics and ready-made alerts. → Operations
  • Console, CLI and assistants. The ktms-admin web console, the ktms CLI, an MCP server and a Claude Code plugin. → Console, CLI and AI assistants

How it works

 your services ──gRPC (Bearer ktms_…)──▶ KTMS ──▶ OpenAI / Anthropic / Gemini / DeepSeek / TypeSafe
                                          │  │
                                 Postgres ┘  └ Redis (limits)      └─▶ usage sink (optional)
                                 config, keys, encrypted vendor keys

Two gRPC services share port 9090:

Service Purpose Needed scope
ktms.v1.GatewayService GenerateText, GenerateTextStream, SubmitBatch, GetBatch, ListBatchResults, CancelBatch, SynthesizeSpeech, GenerateImage, Judge, JudgeStream, EvaluateRollouts, Translate, GetEmbeddings, ListModels generate
ktms.v1.AdminService models, rules, vendor keys, API keys, key rotation, ExplainRoute admin; admin:read for the Get* and List* reads and ExplainRoute; agents:read for the agents' cards and conversations

Port 8080 serves the health probes (/healthz, /readyz) and the OpenAI-compatible HTTP API under /v1. gRPC server reflection is on, so grpcurl works without the .proto files.

Quick start

curl -fsSL https://ai-process.dev/install.sh | sh

It needs Docker with Compose, starts Keystone with Postgres and Redis on localhost, asks for an OpenAI, Anthropic or Gemini key and prints your first request with a ready client key.

From a clone, with an AI assistant, or from scratch with ktms init: Quick start.

Documentation

Document What is in it
Quick start Docker Compose, the first call, ktms init, setting up with an AI assistant
Installation Resource footprint, Docker image, Helm chart, building from source, production checklist
Configuration Every environment variable; keys, vendor keys, models, rules, limits, tenants as API calls or a file
Nodes The node daemon, running a local or translation node, troubleshooting
Console, CLI and AI assistants ktms-admin, the ktms command, its MCP server, the Claude Code plugin
Calling Keystone (gRPC) Client SDKs, text, streaming, sampling, batches, speech, images, judge, translation, embeddings
HTTP APIs OpenAI-compatible endpoints, model and placement selection, Anthropic Messages and OpenAI Responses APIs
MCP gateway and agents MCP servers behind Keystone, the agents' inbox
Concepts Throttling, circuit breaker, back-off, usage reporting, restricted data, semantic cache
Error contract RPC status codes and reasons, batch item errors
API stability What is public, experimental features, compatibility, upgrading, deprecations
Operations Backups, dependency failures, metrics and alerts, sizing
Development Building, tests, code generation, repository layout

Glossary

Term Meaning
Client key A ktms_… API key a service calls Keystone with. Has scopes (generate, admin, admin:read, mcp, …) and an optional policy with limits. → API keys
Vendor key A provider's API key (OpenAI, Anthropic, …), stored encrypted and assigned to one client key. → Vendor keys
Model A vendor model registered in Keystone with its prices, limits and capabilities. → Models
Rule Maps needs and attributes to an ordered model chain; the first matching rule by priority wins. → Rules
Competencies, needs Topic → level (basic < proficient < expert): what a model is good at, and what a request needs. Without a matching rule Keystone selects the models that meet the needs, least excess and cheapest first. → Needs and competencies
Effort Deprecated: LOW, MEDIUM or HIGH, the needs general: basic, proficient, expert. With the HTTP model auto a judge can pick it. → Needs and competencies
Attributes Free-form key–value pairs on a request that rules match on and usage records carry.
Modality The modality attribute (tts, image, judge, translate) that sends a request to rules and models for that kind of work. → Speech, image and judgment rules
Fallback chain The models a rule lists; Keystone moves to the next one when a model fails, is throttled or paused.
Circuit breaker Skips a (vendor, model) after repeated failures until a probe succeeds. → Concepts
Placement Where a request may run: cloud vendors, self-hosted nodes, or nodes first. → Choosing a model and placement
Node A machine with your own inference engine that Keystone routes to. → Run a node
Node daemon The process on a node that reports its models and load to Keystone. → Node daemon
Node key The credential a node daemon authenticates with, optionally limited to some models.
Engine The inference server behind a node: Ollama, vLLM, llama.cpp, FreeToken or ktms-mt for translation.
Restricted data data_classification: restricted: a call that stays on your nodes, with no cloud fallback. → Restricted data
Spend limit A hard USD cap per key or end user per day or month, reserved before a call. → Spend limits
Organization, team Tenants that keys belong to; limits and visibility follow them. → Organizations and teams
Batch An asynchronous set of generations at the vendors' batch discount. → Batch text generation
Judge A typed judgment (score, choice, yes/no) by a model, also used for auto effort and shadow evaluation. → Judge
Shadow routing Mirroring a share of traffic to a candidate model, optionally judged against the primary.
Semantic cache, latent guardrails Experimental: answers for similar prompts and prompt screening in embedding space. → Semantic cache and latent guardrails
Usage sink A gRPC service that receives one usage event per call; light-tokenmeter is the reference one. → Concepts
light-tokenmeter The companion service that stores usage and answers spend questions. Repository
ktms-admin The web console for Keystone. → Web console
MCP gateway Keystone as a proxy for MCP servers, with per-key tool access and per-tool limits. → MCP gateway
Agent, inbox An agent's card and the tasks other agents send it through Keystone. → Agents

Roadmap

What we build now, next and later, and what is not planned, is in ROADMAP.md. Requests and ideas are welcome as issues. Contributions: CONTRIBUTING.md and Development.

License

Apache 2.0

Directories

Path Synopsis
bench
mock-upstream command
Command mock-upstream is a deterministic OpenAI-compatible upstream for gateway benchmarks.
Command mock-upstream is a deterministic OpenAI-compatible upstream for gateway benchmarks.
cmd
ktms command
Command ktms administers a Keystone (KTMS) gateway: its configuration as a file, keys, spend, limits and nodes through the Admin API, and a test call and health checks through the HTTP API.
Command ktms administers a Keystone (KTMS) gateway: its configuration as a file, keys, spend, limits and nodes through the Admin API, and a test call and health checks through the HTTP API.
node-agent command
node-tray command
Command ktms-node-tray shows a local node's level in the menu bar or tray and lets its owner pause it, limit it and edit its schedule.
Command ktms-node-tray shows a local node's level in the menu bar or tray and lets its owner pause it, limit it and edit its schedule.
server command
gen
internal
agentrun
Package agentrun answers an agent's inbox with a local CLI agent: it polls the MCP server "agents" with the agent's key, hands each task that waits for the agent to a command (claude, codex, agy or the user's own) and sends what the command printed back as the reply.
Package agentrun answers an agent's inbox with a local CLI agent: it polls the MCP server "agents" with the agent's key, hands each task that waits for the agent to a command (claude, codex, agy or the user's own) and sends what the command printed back as the reply.
agents
Package agents lets people's agents talk through Keystone, as A2A does: an agent is a client key with a card, a task one request from one agent to another, delivered to the recipient's inbox (the MCP server "agents").
Package agents lets people's agents talk through Keystone, as A2A does: an agent is a client key with a card, a task one request from one agent to another, delivered to the recipient's inbox (the MCP server "agents").
apikeys
Package apikeys mints and verifies the caller credentials stored in the api_key table.
Package apikeys mints and verifies the caller credentials stored in the api_key table.
audio
Package audio transcodes the raw PCM emitted by Gemini TTS into the OGG/Opus container chat apps such as Telegram render as a voice message.
Package audio transcodes the raw PCM emitted by Gemini TTS into the OGG/Opus container chat apps such as Telegram render as a voice message.
cooldown
Package cooldown holds back upstream targets whose vendor answered 429 or 503 with Retry-After, so routing skips them without network IO until it expires.
Package cooldown holds back upstream targets whose vendor answered 429 or 503 with Retry-After, so routing skips them without network IO until it expires.
crypto
Package crypto encrypts vendor LLM keys at rest with AES-256-GCM.
Package crypto encrypts vendor LLM keys at rest with AES-256-GCM.
declarative
Package declarative keeps a Keystone configuration in a file and applies it through the Admin API.
Package declarative keeps a Keystone configuration in a file and applies it through the Admin API.
grpcapi
Package grpcapi implements the proto services on top of proxydb, the registry, and the router.
Package grpcapi implements the proto services on top of proxydb, the registry, and the router.
keytext
Package keytext recognises Keystone's plain keys in text, so errors and logs that quote what a caller sent never carry one.
Package keytext recognises Keystone's plain keys in text, so errors and logs that quote what a caller sent never carry one.
latent
Package latent projects text into a representation space (JEPA or any embedding encoder) for semantic caching and latent guardrails.
Package latent projects text into a representation space (JEPA or any embedding encoder) for semantic caching and latent guardrails.
llm
mcpgw
Package mcpgw is Keystone's MCP gateway: clients reach registered MCP servers through /mcp with a KTMS key, and the gateway holds the servers' credentials, enforces each key's allowed_mcp and tool_rpm, and accounts for every tool call.
Package mcpgw is Keystone's MCP gateway: clients reach registered MCP servers through /mcp with a KTMS key, and the gateway holds the servers' credentials, enforces each key's allowed_mcp and tool_rpm, and accounts for every tool call.
nodetray
Package nodetray is the desktop tray's logic, kept apart from the GUI so it is tested without one: what the menu bar shows for a daemon status, the notifications state changes raise, the icons and the settings page.
Package nodetray is the desktop tray's logic, kept apart from the GUI so it is tested without one: what the menu bar shows for a daemon status, the notifications state changes raise, the icons and the settings page.
panicsafe
Package panicsafe turns a panic into a reported, recoverable error instead of a silent process death.
Package panicsafe turns a panic into a reported, recoverable error instead of a silent process death.
pricing
Package pricing turns token usage into money.
Package pricing turns token usage into money.
proxydb
Package proxydb is the pgx data layer: api keys, the model registry, routing rules, encrypted vendor keys, and the config version counter.
Package proxydb is the pgx data layer: api keys, the model registry, routing rules, encrypted vendor keys, and the config version counter.
redisguard
Package redisguard fails Redis commands fast while Redis is unreachable.
Package redisguard fails Redis commands fast while Redis is unreachable.
rediskeys
Package rediskeys builds every Redis key this service uses, so one Redis can host several deployments behind REDIS_KEY_PREFIX.
Package rediskeys builds every Redis key this service uses, so one Redis can host several deployments behind REDIS_KEY_PREFIX.
router
Package router picks a rule for a request and walks its model chain.
Package router picks a rule for a request and walks its model chain.
safefetch
Package safefetch validates and downloads external media URLs with SSRF protection.
Package safefetch validates and downloads external media URLs with SSRF protection.
spendlimit
Package spendlimit names the monetary limit subjects, periods and refusal reasons, and computes the UTC calendar windows they reset on.
Package spendlimit names the monetary limit subjects, periods and refusal reasons, and computes the UTC calendar windows they reset on.
throttle
Package throttle enforces per-model RPM via GCRA, daily token budgets and monetary spend limits in Redis, shared across replicas.
Package throttle enforces per-model RPM via GCRA, daily token budgets and monetary spend limits in Redis, shared across replicas.
Package migrations carries this service's own DDL, embedded so the binary applies it at startup instead of waiting for an operator to run psql.
Package migrations carries this service's own DDL, embedded so the binary applies it at startup instead of waiting for an operator to run psql.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL