FastAPI gateway · Groq Llama 3.1 8B / 3.3 70B · Ollama fallback

Trim the context. Reuse the answer. Route the rest.

Semantic Gateway sits in front of Groq-hosted Llama models. Before a call, it splits long context into blocks, scores each block against the question with keyword rules, and drops the low scorers. Repeat questions are answered from a semantic cache, and each remaining prompt goes to Llama 3.1 8B or Llama 3.3 70B depending on what it contains.

examples
# From a clone of the repo
$ pip install -r requirements.txt
$ uvicorn main:app --port 8000

# Model replies need a Groq key in .env:
#   GROQ_API_KEY=<your key>
# Without one you get a placeholder reply;
# trimming, cache and routing still run.
3915
Estimated tokens · one sample input

This is the README example sent to /v1/compress: a short context with two sections, where one section answers the question and the other is a repeated log line. It is a single input, not a benchmark. The repo has no benchmark script and no measured average.

Token counts everywhere on this page are estimates (max(words × 1.3, chars ÷ 4)), not output from a real tokenizer. For numbers on your own text, use the playground below.

// How it works

What happens to a request

The steps POST /v1/chat/completions runs, in order, with the file each one lives in. Trimming is done by rules, with no model call.

  1. Drop repeated messages

    Messages in the history that repeat an earlier message word for word are removed. The latest message is always kept.

    services/compression.py
  2. Remove duplicate lines

    Repeated lines are dropped. Timestamps and log levels are ignored when comparing, so the same log line at two different times counts as a duplicate. Lines inside code fences are left alone.

    services/compression.py
  3. Split the context into blocks

    The text is cut at markdown headings, code fences, runs of log lines, and paragraph breaks in long passages.

    services/compression.py
  4. Score each block against the question

    The score is the share of the question's keywords found in the block (weight 0.7), plus 0.25 if the block's heading contains one, plus 0.35 for error text when the question is about a failure, minus 0.4 for log blocks with little overlap.

    services/compression.py
  5. Keep the blocks at or above the cutoff

    Blocks that score 0.30 or more are kept and the rest are dropped. At least one block is always kept. The response lists every kept and dropped block with its reason.

    services/compression.py
  6. Look in the cache

    The trimmed text is checked for an exact match first. If there is none, it is embedded with all-MiniLM-L6-v2 and compared with stored prompts by cosine similarity. The default threshold is 0.82 (CACHE_SIMILARITY_THRESHOLD).

    hit → return the stored reply, skip steps 07 and 08
    services/cache.py
  7. Pick the model

    Prompts that contain code markers, are longer than 250 characters, or include a keyword such as debug or architecture go to llama-3.3-70b-versatile. Everything else goes to llama-3.1-8b-instant.

    services/llm.py
  8. Call Groq, with fallbacks

    Groq is called first. If that fails, an Ollama server is tried. If both fail, the gateway returns a canned placeholder so the request still completes, and marks it with provider.simulated: true. The reply is then stored in the cache and the request is counted in the metrics.

    services/llm.py

Steps 02 to 05 are also available on their own as POST /v1/compress. If a request carries a long system message, that message is what gets trimmed.

// Try it

Playground

Send a context and a question through this server. Every number in this section is read from this server's API responses.

1 · Context and question 0 chars · ~0 est. tokens

Requests are logged. The Request log tab shows recent prompts to anyone who opens this page, so do not paste secrets or personal data.

Ctrl or ⌘ + Enter to send

Using the gateway

Semantic Gateway runs in front of Groq-hosted Llama models, with an Ollama server as a fallback. Both endpoints below are served with and without the /v1 prefix. The generated OpenAPI reference is at /docs.

1. Trim a context: POST /v1/compress

curl -X POST http://localhost:8000/v1/compress \
  -H "Content-Type: application/json" \
  -d '{"context": "Long context...", "query": "What failed?"}'

2. Chat: POST /v1/chat/completions

curl -i -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content": "What is the capital of France?"}]}'

3. Python: import from a clone of the repo

from services.compression import compress_for_turn

result = compress_for_turn(context=long_text, user_query="What failed?")
print(result["compressed_text"], result["tokens_saved_pct"])

Good to know