DEV Community

Tony Bob
Tony Bob

Posted on Originally published at aiagentshubpk.blogspot.com

Free AI API Code: Build Your Own LLM Gateway with FastAPI (Open Source)

Want one single API that can talk to many AI models? This free open-source project does exactly that. It is called LLM Gateway — a small Python (FastAPI) server that sits in front of AI providers like OpenAI, OpenRouter, Groq or a local Ollama, and gives you one OpenAI-style address for all of them. It also has API-key login, rate limiting, automatic retries, and a live dashboard that shows requests, tokens, cost and speed. Best part: it runs fully offline with a built-in demo (mock) provider, so you can test everything without any paid API key.

What you need: Python installed on your computer. That is all.

STEP 1 — Download and run the code

git clone https://github.com/nisarahmad78/llm-gateway.git
cd llm-gateway
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
uvicorn app.main:app --port 8000
Enter fullscreen mode Exit fullscreen mode

Now open these in your browser:

Dashboard: http://localhost:8000/
API docs: http://localhost:8000/docs
Health check: http://localhost:8000/health

STEP 2 — Test the API with one command

curl http://localhost:8000/v1/chat/completions -H "Authorization: Bearer YOUR_KEY" -H "Content-Type: application/json" -d '{"model": "mock-1", "messages": [{"role": "user", "content": "Explain RAG in two sentences."}]}'
Enter fullscreen mode Exit fullscreen mode

You will get a normal OpenAI-style JSON reply from the demo provider.

STEP 3 — Use it from Python code

from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="YOUR_KEY")
reply = client.chat.completions.create(
    model="mock-1",
    messages=[{"role": "user", "content": "Hello, gateway!"}],
)
print(reply.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode

To connect a real AI model later, put your provider key in the .env file (OPENAI_API_KEY) and use a model like gpt-4o-mini — the rest of your code stays the same.

FULL SOURCE CODE (FREE)

The complete project — every file, free to use, copy and modify — is on GitHub: https://github.com/nisarahmad78/llm-gateway

Credit and license: "LLM Gateway" is created by Nisar Ahmad (GitHub: nisarahmad78) and is released under the MIT License, which allows free use with attribution. All credit for the code goes to the original author.

More free AI code and simple AI agent guides are posted here on AI Agents Hub every day. Bookmark this page and come back for the next one.

Top comments (0)