Skip to content
devpparikhPublic

About

Low-latency, self-hostable LLM gateway in Rust: drop-in OpenAI-compatible proxy with zero-copy streaming; agent-aware caching and routing on the roadmap.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

smart-llm

CI Rust License

A low-latency, self-hostable LLM gateway in Rust, built for agentic workloads. It is a drop-in proxy for OpenAI-compatible APIs: change one base URL, and every call your agents make goes through a gateway that will cache, route and fail over for you, without new code in each LangGraph node.

Status: milestone 1 of 6 is done. The streaming proxy is complete, hardened, tested (105 tests) and benchmarked. Caching, routing, failover and metrics are next; see the roadmap.

Contents

Project overview

smart-llm sits between your application and your model provider:

your agent / app  ──►  smart-llm (127.0.0.1:8080/v1)  ──►  OpenAI or any OpenAI-compatible API
What it is A single Rust binary exposing POST /v1/chat/completions and GET /health.
Who it is for Teams building agentic and RAG apps who want caching and model routing without writing it into every workflow.
How you adopt it Point your existing OpenAI SDK at it. Requests and responses are forwarded byte-for-byte, so nothing else changes.
How you run it Self-hosted on your own machine or infrastructure. Open source, no subscription, no hosted control plane.

What works today (milestone 1)

  • OpenAI-compatible chat completions, both JSON and stream: true.
  • Streaming with no buffering. Each chunk is forwarded the moment it arrives. A zero-copy tee captures it, and the full completion (including tool calls) is reassembled in the background after the stream ends. That is the hook the cache plugs into.
  • Transparent errors. Upstream 429s, 5xxs and redirects pass through unchanged (status, body, retry-after, rate-limit headers). The gateway's own errors use OpenAI's error shape, so SDK retries keep working.
  • x-gateway-overhead-ms on every response: time spent inside the gateway, excluding time waiting on the upstream.
  • Hardened for local use: JSON-only requests, a Host check against DNS rebinding, a concurrency cap, and size and time limits on every body and upstream stall. See Security.

Problem

Agentic applications make many small, repetitive LLM calls: query rewriting, intent classification, tool selection, the same RAG lookup for different users. Today teams handle this in one of three ways, and each one hurts:

  1. Hand-written logic in every node. Caching and "use the cheap model for this step" rules get copy-pasted into each LangGraph node or workflow. They drift, they are untested, and they couple business logic to provider details.
  2. Python gateways on the hot path. General-purpose proxies such as LiteLLM add measurable latency and memory under load (sources in the PRD). For a streaming agent, every millisecond before the first token is visible to the user.
  3. Blind semantic caching. Generic semantic caches embed the whole prompt. In RAG, two requests can be 96% identical (same system prompt, same retrieved policy) and still need different answers: "I bought it 29 days ago" versus "31 days ago" under a 30-day return policy. A whole-prompt cache returns the wrong one. There is also no clean way to expire answers when the underlying documents change.

The cost of leaving this unsolved is real money on duplicate frontier-model calls, slower agents, and caches that are either off or quietly wrong.

Solution

smart-llm moves these decisions out of application code and into one fast, transparent layer:

Problem smart-llm's approach Milestone
Proxy latency Rust, async I/O, zero-copy streaming. The gateway's own work is measured in microseconds and reported on every response. 1 ✅
Wasted duplicate calls Exact cache keyed on the normalised request, with safe bypass rules: temperature > 0.3, tool calls, or X-Cache-Bypass: true. 2
Wrong semantic hits Context-aware semantic cache. Static context (system prompt, retrieved documents) must match exactly; only the user's intent is compared semantically, at a strict threshold of ≥ 0.94. 3
Stale answers X-Doc-Version scopes entries to a document version, so updating a knowledge base invalidates only the answers built on it. 3
Every step on the frontier model X-Agent-Step routing. Cheap steps (rewrite, classify) go to a fast model; synthesis and tool decisions stay on the frontier model. 4
Provider outages and rate limits Failover to a backup model or provider on 429 and 5xx. 4
No visibility Decision headers (HIT-EXACT / HIT-SEMANTIC / MISS / BYPASS, model, overhead, cost saved) and GET /v1/metrics. 2, 5

Every claim ships with a reproducible benchmark or eval. Milestone 1's is in docs/benchmarks.

Architecture

Request flow (milestone 1)

flowchart LR
    C[Client<br/>OpenAI SDK] -->|POST /v1/chat/completions| G

    subgraph G[smart-llm gateway]
        direction TB
        M[Middleware<br/>loopback Host check<br/>concurrency permit] --> H[Chat handler<br/>JSON-only · body limit + deadline<br/>peek model / stream]
        H --> U[Upstream client<br/>pooled reqwest · rustls<br/>timeouts · no redirects]
        U -->|SSE| T[TeeStream<br/>zero-copy forward + capture]
        U -->|JSON| J[Size-capped body<br/>passthrough]
        T -.->|after stream ends<br/>blocking pool| A[SSE parser +<br/>completion assembler]
        A -.-> S[CompletionSink<br/>today: log · M2: cache write]
    end

    U <-->|HTTPS| P[(OpenAI-compatible<br/>provider)]
    T -->|chunks as they arrive| C
    J --> C
Loading

The key design point is the tee. The forwarding path never parses or buffers: each Bytes chunk from the upstream is sent straight to the client, and only a reference-counted clone is kept. Parsing the SSE transcript and assembling the completion happens after the stream ends, on Tokio's blocking pool, so it cannot delay time-to-first-token. The concurrency permit stays held until the stream finishes, so open streams count against the limit.

Target architecture (milestones 2–5)

flowchart LR
    C[Client] --> D{Bypass?<br/>temp > 0.3 · tools<br/>X-Cache-Bypass}
    D -->|no| E[Exact cache]
    E -->|miss| SC[Semantic cache<br/>exact context +<br/>intent ≥ 0.94<br/>scoped by X-Doc-Version]
    E -->|hit| R[Response +<br/>decision headers]
    SC -->|hit| R
    SC -->|miss| RT[Router<br/>X-Agent-Step]
    D -->|yes| RT
    RT --> F[Fast model]
    RT --> FR[Frontier model]
    F -.->|429 / 5xx| B[Backup provider]
    FR -.->|429 / 5xx| B
    F --> T[Tee + reassembly]
    FR --> T
    B --> T
    T --> R
    T -.->|cache write| E
    T -.-> MT[Metrics<br/>GET /v1/metrics]
Loading

Code layout

Path Responsibility
src/main.rs CLI, config loading, logging, graceful shutdown with a 30 s drain limit.
src/config.rs TOML config with validated defaults. Keys come from the environment and are redacted in Debug.
src/proxy/ axum router, middleware (Host check, concurrency permit), chat handler, header policy, health.
src/upstream/ Pooled HTTP client to the provider: auth, timeouts, error mapping.
src/stream/tee.rs TeeStream: forwards chunks and captures them, then notifies a CompletionSink exactly once.
src/stream/sse.rs Incremental SSE parser (CR, LF, CRLF, split across chunks) and completion assembler, including tool-call deltas. Property-tested.
src/error.rs Gateway errors rendered in OpenAI's error format.
src/testsupport/ In-process mock upstream that records requests and scripts delays, statuses and mid-stream aborts.
tests/ Integration tests that run the real router against the mock.
examples/ ttft_bench (overhead benchmark) and mock_upstream (standalone mock server).

Stack: Rust 2024 edition · axum 0.8 · tokio · reqwest (rustls, HTTP/2) · serde · tracing · proptest. unsafe code is forbidden crate-wide.

Local setup

1. Prerequisites

  • Rust 1.88 or newer. Install it with rustup:

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    rustc --version   # 1.88.0 or newer
  • git and curl.

  • Optional: an OpenAI (or OpenAI-compatible) API key. You can try everything without one using the bundled mock upstream (step 3a).

2. Clone and build

git clone https://github.com/devpparikh/smart-llm.git
cd smart-llm
cargo build --release
cp config/gateway.example.toml config/gateway.toml   # git-ignored

3a. Try it without an API key (mock upstream)

Start the mock provider in one terminal. It answers any path, streams SSE when "stream": true, and returns JSON otherwise:

cargo run --release --example mock_upstream -- --port 9100 --chunk-interval-ms 150

In config/gateway.toml, point the upstream at it:

[upstream]
base_url = "http://127.0.0.1:9100/v1"

Start the gateway in a second terminal:

cargo run --release -- --config config/gateway.toml

Send a streaming request from a third terminal. Chunks appear every 150 ms, as the mock sends them:

curl -N http://127.0.0.1:8080/v1/chat/completions \
  -H "content-type: application/json" \
  -d '{"model":"gpt-4o-mini","stream":true,"messages":[{"role":"user","content":"hi"}]}'

3b. Run against OpenAI

Keep the default base_url = "https://api.openai.com/v1" and choose how auth works:

# Option 1: the gateway holds the key (clients send no key)
export SMART_LLM_UPSTREAM_API_KEY=sk-...
cargo run --release -- --config config/gateway.toml

# Option 2: no gateway key; each client's own Authorization header is forwarded
cargo run --release -- --config config/gateway.toml

4. Verify

curl -s http://127.0.0.1:8080/health
# {"status":"ok"}

curl -si http://127.0.0.1:8080/v1/chat/completions \
  -H "content-type: application/json" -H "authorization: Bearer $OPENAI_API_KEY" \
  -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Say hello"}]}' \
  | grep -i x-gateway-overhead-ms
# x-gateway-overhead-ms: 0.012

5. Point your app at it

Only the base URL changes:

from openai import OpenAI

client = OpenAI(base_url="http://127.0.0.1:8080/v1")  # api_key from env as usual
for chunk in client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Say hello"}],
    stream=True,
):
    print(chunk.choices[0].delta.content or "", end="", flush=True)
import OpenAI from "openai";
const client = new OpenAI({ baseURL: "http://127.0.0.1:8080/v1" });

Troubleshooting

Symptom Cause and fix
403 host_not_allowed On a loopback bind, the Host header must be localhost, 127.0.0.1 or [::1]. Use one of those in the URL.
415 unsupported_media_type Send content-type: application/json.
401 from the upstream No key reached the provider: set SMART_LLM_UPSTREAM_API_KEY or send Authorization: Bearer ....
502 upstream_unavailable The gateway cannot reach upstream.base_url. Check the URL and that the mock or provider is up.
No logs per request Per-request logs are at debug: run with RUST_LOG=smart_llm=debug.

Configuration

All settings are documented in config/gateway.example.toml.

Setting Default Notes
listen 127.0.0.1:8080 Localhost by default; see Security.
upstream.base_url — (required) Any OpenAI-compatible base, including /v1.
upstream.connect_timeout_ms 5000
upstream.response_timeout_ms 600000 Max wait for upstream headers (504), and max stall between body reads.
limits.max_body_bytes 16777216 Larger requests return 413.
limits.max_response_bytes 67108864 Larger non-streaming upstream bodies return 502.
limits.max_concurrent_requests 512 Includes open streams. Beyond it, requests get 503 (SDKs retry).
limits.request_body_timeout_ms 30000 Deadline to receive the request body. Exceeding it returns 408.
Environment variable Purpose
SMART_LLM_UPSTREAM_API_KEY Upstream key. Overrides any key in the file.
SMART_LLM_CONFIG Config path when --config is not given.
SMART_LLM_LOG_FORMAT json or pretty. The default is JSON in release builds.
RUST_LOG Default smart_llm=info,warn. Per-request logs are at debug.

Auth. If a gateway key is configured it replaces the client's Authorization header, and the client's openai-organization/openai-project headers are dropped, so clients cannot pick which org pays. Otherwise the client's Authorization and scope headers are forwarded unchanged.

Security

Gateway-side client authentication is not part of milestone 1. With a gateway-held key, anyone who can reach the listen address can spend on that key, so keep it on localhost (the default) or put an authenticating proxy in front. The gateway warns at startup if you combine a gateway key with a non-loopback listen.

Threat Defence
A web page POSTing to 127.0.0.1 cross-site (CSRF) Only application/json is accepted (415 otherwise), which forces a CORS preflight the gateway never approves. Upstream access-control-* headers are stripped.
DNS rebinding On loopback binds, requests whose Host is not a loopback name get 403.
Key leakage The key lives in the environment. Debug output is redacted, the header is marked sensitive, config parse errors never echo the offending line, and base_url cannot carry credentials.
Header leakage An allowlist going upstream: client cookies, accept-encoding and internal headers never reach the provider.
Slow or huge requests Body size limit (413) and body deadline (408).
Resource exhaustion Concurrency cap that counts open streams (503). Non-streaming responses are size-capped, upstream stalls time out, and shutdown drains for at most 30 s.
Redirect tricks Upstream 3xx responses are passed through, never followed.

Known limitation: axum::serve has no header-read timeout, so a client can hold idle connections open while sending headers slowly. Each one costs only a small buffer, and the concurrency cap applies once headers arrive. A custom hyper accept loop with header_read_timeout is planned.

Performance

The gateway's own processing is 2–42 µs per request, with every security guard on. End-to-end on one shared 8-vCPU WSL2 machine, it adds:

Concurrency Added at p99 < 2 ms p99 target
1 +0.1 – 0.7 ms met in every run
16 +0.7 – 2.0 ms met, close to the limit
64 +2.2 – 9.6 ms missed

At concurrency 64 the load generator, mock and gateway compete for the same 8 CPUs, which is the likely cause; this has not yet been confirmed on separate hosts. Full method, raw tables, variance and caveats are in docs/benchmarks/m1-proxy-overhead.md.

cargo run --release --example ttft_bench -- --requests 2000 --concurrency 1,16,64

Development

cargo test                                                # unit + integration tests
cargo clippy --all-targets --all-features -- -D warnings  # lint
cargo fmt --all --check                                   # format

Integration tests run the real router against an in-process mock upstream that records every request and can script delays, status codes and mid-stream aborts. Highlights:

  • the first chunk reaches the client in under 100 ms while the upstream stays silent for 500 ms (no buffering);
  • a client disconnect cancels the upstream request;
  • an upstream abort reaches the client as a transport error, never as a fake clean end;
  • request and response bodies are byte-identical through the proxy.

CI runs fmt, clippy and the test suite on every push (.github/workflows/ci.yml).

Roadmap

# Milestone Status
1 Drop-in streaming proxy, with overhead benchmark ✅ done
2 Exact cache, bypass rules (temperature > 0.3, tool calls, X-Cache-Bypass), decision headers planned
3 Context-aware semantic cache (≥ 0.94 on user intent only), X-Doc-Version invalidation, tenant scoping, adversarial eval planned
4 X-Agent-Step routing (fast vs frontier model) and 429/5xx failover planned
5 GET /v1/metrics: hit rate, routing split, overhead, spend saved planned
6 Write-up, evals, before/after agent demo, container image planned

Requirements and design notes: PRD · milestone 1 plan

License

Dual-licensed under MIT or Apache-2.0, at your option.

About

Low-latency, self-hostable LLM gateway in Rust: drop-in OpenAI-compatible proxy with zero-copy streaming; agent-aware caching and routing on the roadmap.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages