agentleFS
zwldarrenzwldarren/llm-proxy/AGENTS.md

llm-proxy

AGENTS.md3 starsChanged 50 days agoMITView on GitHub

LLM API proxy with multi-provider support (OpenAI, Anthropic, Gemini, Ollama, vLLM, SGLang, OpenRouter), protocol translation, streaming, rate limiting, MCP integration, and Vue 3 admin UI. User documentation lives in docs/ — a VitePress site published to GitHub Pages by .github/workflows/docs.yml (docs/adr/ and docs/agents/ are excluded from the site via srcExclude). English is the source language and lives at the site root. Simplified Chinese pages live under docs/zh/, mirroring the English structure. When you edit a page that has a Chinese…

  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.

    Of the AGENTS.md files we read, the 33,398 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository3 other files it gives its agents.

The file

We split this AGENTS.md into the rules it gives an agent

5 rules. About 0 are common, 2 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Write plain documentation, not marketing copy.

    line 40
  2. Very specific:

    Put lazy on the third-party SDK boundary, not on our own package edges.

    line 138
  3. Very specific:

    Verify with uv run python -X importtime -c "import llm_proxy.api".

    line 150
  4. Distinctive:

    Comments: All code comments must be in English

    line 225
  5. Distinctive:

    Anti-references: NOT playful/consumer; NOT boring/outdated admin panels.

    line 268

≈ “Common” is an estimate: at least 1 in 5 of the 43,423 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

LLM Proxy - Agent Guidelines

OVERVIEW

LLM API proxy with multi-provider support (OpenAI, Anthropic, Gemini, Ollama, vLLM, SGLang, OpenRouter), protocol translation, streaming, rate limiting, MCP integration, and Vue 3 admin UI.

COMMANDS

Backend

uv sync                           # Install dependencies
uv run ruff check --fix           # Lint (auto-fix)
uv run ruff format                # Format code
uv run ty check                   # Type check (ty, not mypy/pyright)
uv run pytest                     # Run tests
uv run llm-proxy                  # Run production server
uv run llm-proxy-dev              # Start backend + frontend dev servers concurrently

Verification order

uv run ruff check --fix && uv run ruff format && uv run ty check && uv run pytest

Documentation

User documentation lives in docs/ — a VitePress site published to GitHub Pages by .github/workflows/docs.yml (docs/adr/ and docs/agents/ are excluded from the site via srcExclude).

English is the source language and lives at the site root. Simplified Chinese pages live under docs/zh/, mirroring the English structure. When you edit a page that has a Chinese counterpart, update both in the same change; a page without a translation is linked from the Chinese navigation to its English original and marked “(英文)”. Style, terminology and worked examples for Chinese pages are in docs/agents/documentation-zh.md.

Write plain documentation, not marketing copy. Avoid em-dash glosses on every sentence, bold lead-ins on every bullet, parallel headline triads, “not X but Y” contrasts, and generic closers. The avoid-ai-writing skill (when installed) can audit a page; use its docs profile, which treats parameter lists and tables as legitimate.

cd docs
bun install          # Install the VitePress toolchain
bun run docs:dev     # Preview at http://localhost:9912/llm-proxy/
bun run docs:build   # Build docs/.vitepress/dist

ARCHITECTURE

Request Flow

  1. Incoming request → Protocol endpoint (protocols/) mounts the route
  2. Parse to InternalRequest via the protocol serializer (protocols/<name>/serializer.py)
  3. Route via UnifiedProcessor (core/processing/unified.py) to adapter
  4. Adapter calls provider API via the provider serializer (serialization/)
  5. Response → InternalResponse → Format for client via the protocol serializer

Serialization Pattern

Protocol serializers (client wire format ↔ internal models) and provider serializers (internal models ↔ provider API format) are two separate classes in two separate registries — one serializer never does both sides.

from llm_proxy.protocols.registry import get_protocol_serializer
from llm_proxy.serialization import get_provider_serializer

# Client side: wire format -> InternalRequest
protocol_serializer = get_protocol_serializer("openai")
unified_request = protocol_serializer.parse_request(raw_data)

# Upstream side: InternalRequest -> provider body
provider_serializer = get_provider_serializer("openai")
provider_body = provider_serializer.build_provider_request(unified_request)

Process-lifetime services

Subsystems that outlive a request (config manager, pooled HTTP client, Redis, circuit breaker, provider stats, MCP manager, per-protocol processors, web-search runtime) live behind one typed interface, llm_proxy/services.py (ADR-0021). Read them with runtime_services(request).config_manager() — never by probing app.state for an attribute name. The lifespan installs them through the same module's install_* methods; required services raise when absent, optional ones return None.

from llm_proxy.services import runtime_services

services = runtime_services(request)
config = await services.config_manager().get_config()
redis = services.redis_client()  # None when Redis is disabled

Request-scoped facts

What a request accumulates as it travels (its id, identity, the resolved model/provider, the auditor's captured bodies, the disconnect/audit latches) lives in one typed record, llm_proxy.core.request_facts (ADR-0022). Read and write it with facts_for(request) — never with getattr(request.state, "some_name", None), and never by setting a request.state attribute directly.

from llm_proxy.core.request_facts import facts_for, get_request_identity

facts = facts_for(request)
request_id = facts.request_id  # minted once, by the first toucher
key_name = get_request_identity(request).api_key_name
facts.model = requested_model

Admin API schemas

Dashboard request/response models live in llm_proxy.api.schemas, one module per resource, mirroring api/routers/ (ADR-0023): models.py, providers.py, api_keys.py, mcp.py, auth.py, server_config.py, and common.py for what more than one resource reuses (ValidatorMixin). Put a new schema in the module of the resource it belongs to; a resource may import a peer's read shape it embeds (ProviderDetails.models is ModelRead), never a peer's write schema. Small router-local response shapes may stay inline in the router.

Python 3.15 features

The project runs on Python 3.15 (requires-python >= 3.15), so use the language features it adds instead of the hand-rolled equivalents. Full rationale and measurements: docs/adr/0030-lazy-imports-at-the-sdk-boundary.md.

PEP 810 — lazy imports. Mark an import lazy at module scope to keep its module out of the startup graph until the name is first used.

  • Put lazy on the third-party SDK boundary, not on our own package edges. Package __init__.py façades (http/, streaming/, observability/, mcp/) are already lazy — do not reintroduce a module __getattr__ + importlib shim.
  • Never hoist a function-level import into a module-scope lazy import. Hoisting turns per-call attribute reads into bind-once and silently breaks tests that patch the source module (api/lifecycle.py keeps its per-function imports for this reason).
  • lazy is module-scope only (SyntaxError inside functions, class bodies, try blocks), so optional-dependency guards stay as they are.
  • @dataclass, pydantic BaseModel and TypedDict fields evaluate annotations at class creation, reifying a lazy proxy immediately. For those fields keep the import under if TYPE_CHECKING: with a string annotation.
  • Verify with uv run python -X importtime -c "import llm_proxy.api". The CLI is a separate check: llm-proxy --help must not import the server stack.

Other 3.15 idioms in this repo.

  • frozendict (builtin) for module-level lookup tables that are never mutated. It is not a dict subclass: check consumers for isinstance(x, dict) and for passing the table as a pydantic/FastAPI/SQLAlchemy payload.
  • sentinel (builtin) for "argument not provided" markers (database/repositories/api_keys.py). Keep the module-level variable name so pickle/copy identity holds.
  • typing.disjoint_base on mixins that must never coexist in one MRO (static only — the runtime __init_subclass__ ordering check still has to stay).
  • PEP 798 comprehension unpacking ([*x for xs in xss], {**d for ds in dicts}) where the element is passed through unchanged.
  • re.prefixmatch replaces re.match when the pattern is anchored at the start.
  • PEP 686 makes UTF-8 the default encoding, but keep passing encoding="utf-8" explicitly at I/O boundaries.
  • Do not add from __future__ import annotations. PEP 649 makes annotations lazy by default, so the import is redundant — and not byte-identical: __annotations__ holds strings under the future import but evaluates on access under PEP 649, which is why a lazy name must never appear in a @dataclass / pydantic / TypedDict field.
  • PEP 799: for production performance work use the profiling package (python -m profiling.sampling attach <pid>); cProfile is now an alias for profiling.tracing.

Streaming prefetch

The read-ahead both streaming tiers do before the first byte reaches the client (the first user-visible content, and the in-band fallback signals that arrived before it) is one loop, core/processing/stream_prefetch.py (ADR-0024). A tier supplies a decoder — ConvertedStreamDecoder (chunks re-encoded through the protocol transformer) or NATIVE_BLOCKS (raw SSE blocks replayed verbatim) — while the loop owns the stop rule and the finish-reason policy. Do not add a second read-ahead loop per tier; add a decoder.

MCP Integration

  • mcp/manager.py: MCP server lifecycle management
  • mcp/proxy.py: Request proxying to MCP servers
  • Configure MCP servers in provider config with mcp_servers key

DATABASE MIGRATIONS

Migrations are the single source of truth for schema. There is no create_all fallback — if migrations fail, startup fails loudly.

  • connection.py:init_db() calls alembic upgrade head on startup via asyncio.to_thread()
  • env.py creates an async engine with NullPool, runs migrations, and explicitly commits
  • render_as_batch is enabled only for SQLite; PostgreSQL uses native DDL
  • Generated migrations are auto-formatted by the ruff post-write hook in alembic.ini

Commands

# After modifying models in database/tables.py:
uv run alembic revision --autogenerate -m "description_of_change"

TESTS

  • tests/conftest.py provides MockResponse and create_mock_client for mocking httpx2

DEV SERVER

uv run llm-proxy-dev (llm_proxy.__main__:main_wrapper_dev) starts:

  • Backend uvicorn with --reload on port 9911
  • Frontend Vite dev server on 0.0.0.0:5173, proxying API to backend via VITE_API_BASE_URL

Requires bun in PATH. node_modules is auto-installed on first start if missing.

STYLE & CONVENTIONS

  • Python: 3.15+ (pyproject.toml)
  • Comments: All code comments must be in English
  • Ruff: line-length 100, excludes **/versions/**
  • Type checker: ty (configured in pyproject.toml with include = ["src"])

Exception Handling

  • Python 3.14 (PEP 758) allows omitting parentheses in multi-exception except clauses when there is no as binding. Ruff format will therefore collapse except (ValueError, ConfigurationError): into except ValueError, ConfigurationError: — this is valid Python 3.14 and catches both exceptions.

    Correct without as:

    except ValueError, ConfigurationError:
        pass

    Correct with as (parentheses are still required):

    except (ValueError, ConfigurationError) as exc:
        ...
    # or, when the exception object is unused:
    except (ValueError, ConfigurationError) as _:
        pass

    Do not write:

    except ValueError, ConfigurationError as exc:  # WRONG: binds only to ValueError
        ...

DESIGN CONTEXT

Strategic + visual context for the admin UI. Full detail in PRODUCT.md (strategy: register, users, purpose, brand, anti-references, principles, accessibility) and DESIGN.md (visual system: tokens, typography, elevation, components, do's/don'ts). The frontend's own frontend/AGENTS.md carries the tactical DESIGN CONTEXT for the Vue app; PRODUCT.md / DESIGN.md are the root source of truth and win on conflicts.

  • Register: product — design serves the product (admin console / dashboard / tool).
  • Primary users: operators who self-host the proxy and run the dashboard (configure providers/models/keys, monitor usage, cost, logs). API consumers are a non-design surface.
  • Brand personality: Technical Sophistication, Reliable, Modern. Direct, precise, professional; confident, not arrogant.
  • Aesthetic: Monochrome Editorial — dark-first (deep cool-neutral, hue 220°), light mode a crisp mirror. Space Grotesk display + Manrope body + IBM Plex Mono for all data. Low-saturation semantic tints (violet/blue/amber/rose + status) for differentiation only, never decoration.
  • Design principles: Clarity Over Cleverness · Confidence Through Feedback · Technical Sophistication · Dark-First Design · Respectful of Time.
  • Anti-references: NOT playful/consumer; NOT boring/outdated admin panels; NO loud color accents; NOT the generic 2026 AI-tool aesthetic (no cream/sand bodies, gradient-text, identical card grids, hero-metric template).
  • Accessibility: WCAG AA both themes; prefers-reduced-motion respected; visible focus rings + skip link; color never the sole status signal; i18n (English primary, Chinese secondary).
  • Frontend stack: Vue 3 + Vite (rolldown) + TypeScript + Tailwind v4 + shadcn-vue (new-york, neutral) + reka-ui + Pinia + vue-router + vue-i18n + vue-sonner. Tokens in frontend/src/assets/main.css; primitives in frontend/src/components/ui/.

Agent skills

Issue tracker

Issues live as GitHub issues in this repo; use the gh CLI. See docs/agents/issue-tracker.md.

Triage labels

Five canonical labels (needs-triage, needs-info, ready-for-agent, ready-for-human, wontfix). See docs/agents/triage-labels.md.

Domain docs

Single-context: CONTEXT.md + docs/adr/ at the repo root. See docs/agents/domain.md.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.