LLM Hosting APIWhy This Is the Best LLM API for Developers
LLM Using Fast API: Call a Hosted Model
You can put a language model behind a FastAPI app in about thirty lines, because the hosted endpoint speaks the OpenAI protocol. The steps below go from a first route to streaming, JSON mode, tools and rate-limit handling.
Updated

Key points
- Use the official openai package with AsyncOpenAI, a custom base_url and the model ID uncensored.
- Keep one shared client; create it at startup, not per request.
- Stream with StreamingResponse and hold a semaphore slot until the stream ends.
- Handle HTTP 429 with the Retry-After header and a concurrency limit that matches your key.
Setup in five minutes
The simplest way to do llm using fast api work is to treat the model as one more HTTP dependency. FastAPI handles your routes, the OpenAI Python SDK handles the request format, and the hosted endpoint does the generation. You do not need a GPU or any model files on your machine.
Install the packages and set your key. Get a key from the API key page; new accounts can claim a $0.50 trial in one click.
pip install fastapi uvicorn openai
export LLM_API_KEY="your-key-here"
# base URL for every example below: https://api.llmhostingapi.com/v1
# model ID: uncensored
The service is OpenAI-compatible, with POST /v1/chat/completions and GET /v1/models. Authentication is the usual Authorization: Bearer header, which the SDK sets for you. Only the base URL and the model name differ from a stock OpenAI project.
A first chat endpoint
Create main.py. The client is built once at import time and reused, which lets the SDK keep connections open.
import os
from fastapi import FastAPI, HTTPException
from openai import AsyncOpenAI, RateLimitError
from pydantic import BaseModel
client = AsyncOpenAI(
base_url="https://api.llmhostingapi.com/v1",
api_key=os.environ["LLM_API_KEY"],
max_retries=2,
)
app = FastAPI()
class ChatIn(BaseModel):
message: str
@app.post("/chat")
async def chat(body: ChatIn):
try:
resp = await client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": body.message},
],
temperature=0.7,
)
except RateLimitError:
raise HTTPException(status_code=429, detail="Model is busy, retry shortly")
return {"reply": resp.choices[0].message.content}
Run it with uvicorn main:app --reload and test:
curl -s localhost:8000/chat -H "Content-Type: application/json" \
-d '{"message":"Give me one sentence on FastAPI."}'
# calls https://api.llmhostingapi.com/v1 with model uncensored
Because the route is async def and the client is async, one worker process can wait on many model calls at once. A sync client inside an async route would block the event loop, so do not mix them.
Streaming tokens to the browser
Waiting for a full completion feels slow on long answers. Streaming sends tokens as they are produced, using server-sent events. Add this route to the same file.
import asyncio
import json
from fastapi.responses import StreamingResponse
slots = asyncio.Semaphore(8) # full key: 8 concurrent requests
@app.post("/chat/stream")
async def chat_stream(body: ChatIn):
async def events():
async with slots:
stream = await client.chat.completions.create(
model="uncensored", # base_url https://api.llmhostingapi.com/v1
messages=[{"role": "user", "content": body.message}],
stream=True,
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
yield "data: " + json.dumps(chunk.choices[0].delta.content) + "\n\n"
yield "data: [DONE]\n\n"
return StreamingResponse(events(), media_type="text/event-stream")
Two details matter. First, the guard on chunk.choices: the final chunk carries usage and can have an empty choices list. Second, the semaphore sits inside the generator. A streamed request occupies its concurrency slot until the stream ends, so the slot must be held until the last token arrives, and not released after the first call returns. If you are on the trial key, use Semaphore(2) instead.
JSON mode for structured output
When another program consumes the reply, ask for a JSON object. Set response_format and describe the shape in the prompt, since the model needs to know which keys you want.
@app.post("/extract")
async def extract(body: ChatIn):
resp = await client.chat.completions.create(
model="uncensored", # base_url https://api.llmhostingapi.com/v1
messages=[
{"role": "system", "content": 'Reply with JSON only: {"title": string, "tags": [string]}'},
{"role": "user", "content": body.message},
],
response_format={"type": "json_object"},
temperature=0,
)
try:
return json.loads(resp.choices[0].message.content)
except json.JSONDecodeError:
raise HTTPException(status_code=502, detail="Model returned invalid JSON")
Keep json.loads inside a try block anyway. If a reply is cut off by a token limit, the JSON can be incomplete, and a clear 502 beats a stack trace. Failed or refused requests are not charged, which keeps retries cheap while you tune the prompt.
Tool calling from a route
Tool calling lets the model ask your code to do something, such as looking up an order. The loop is short: send the tools, run whatever the model requests, return results as role: "tool" messages, and ask again.
TOOLS = [{
"type": "function",
"function": {
"name": "order_status",
"description": "Look up the status of an order by id",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
}]
def order_status(order_id: str):
return {"order_id": order_id, "status": "shipped"} # replace with a real lookup
@app.post("/agent")
async def agent(body: ChatIn):
messages = [{"role": "user", "content": body.message}]
for _ in range(4): # hard cap on tool rounds
resp = await client.chat.completions.create(
model="uncensored", # base_url https://api.llmhostingapi.com/v1
messages=messages,
tools=TOOLS,
tool_choice="auto",
)
msg = resp.choices[0].message
if not msg.tool_calls:
return {"reply": msg.content}
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = order_status(**args)
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}
)
raise HTTPException(status_code=508, detail="Too many tool rounds")
The round cap protects you from a loop that never ends and from a surprise bill. Tool calls also work when streaming; the arguments arrive in pieces inside tool_calls deltas and you join them before parsing.
Structuring the app for growth
Module-level globals are fine for a demo. Once the app has tests and more than one router, create the client in a lifespan handler and inject it with Depends.
import os
from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI, Request
from openai import AsyncOpenAI
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.llm = AsyncOpenAI(
base_url="https://api.llmhostingapi.com/v1",
api_key=os.environ["LLM_API_KEY"],
)
yield
await app.state.llm.close()
app = FastAPI(lifespan=lifespan)
def get_llm(request: Request):
return request.app.state.llm
@app.get("/summary")
async def summary(text: str, llm: AsyncOpenAI = Depends(get_llm)):
resp = await llm.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Summarize in one line: " + text}],
max_tokens=100,
)
return {"summary": resp.choices[0].message.content}
With this layout a test can replace get_llm through app.dependency_overrides and return a fake object, so your test suite never spends money or needs a key.
Conversation memory is your job
The chat endpoint is stateless. The model only sees what you send in messages, so a multi-turn chat means storing the history yourself, in memory, Redis or a database, and resending it each turn. Input tokens grow with every turn, and you pay for them each time at $0.15 per 1M. A simple policy works well: keep the system prompt, keep the last N turns, and replace older turns with a short summary.
Behind a proxy
If nginx or another proxy sits in front of FastAPI, streaming can look broken because the proxy buffers the response. Turn buffering off for the streaming route, or send the header X-Accel-Buffering: no from the route when using nginx. Then tokens reach the browser as they are generated.
Rate limits, 429s and cost
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 and 60. Past a limit the API returns HTTP 429 with error code rate_limited for requests per minute, or concurrency for too many at once. During temporary overload it also returns 429, with a Retry-After: 5 header.
The SDK retries 429 responses a couple of times by default, and the max_retries setting above makes that explicit. For a public API of your own, the semaphore is the better first defense: it queues requests inside your process instead of letting them hit the limit. If a client may wait long, return 429 yourself with your own Retry-After.
What a route costs
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens. A chat call with 1,500 input and 400 output tokens costs 1,500 x $0.15 / 1M = $0.000225 plus 400 x $0.50 / 1M = $0.0002, so $0.000425. Ten thousand such calls come to $4.25. Read the X-Balance-USD response header through the SDK's raw-response mode if you want to log the balance per request.
Hardening for production
- Keep the key in an environment variable or secret store, never in the repo.
- Set a client timeout; the 100,000 token window allows long completions.
- Limit request body size. The API accepts bodies up to 8 MB.
- Pass a stable
seedwhen you need repeatable output in tests.
The quickstart lists every supported parameter, and the pricing page has the prepaid top-up tiers, from $20 to $500.
Common errors and how to fix them
Most first-run problems come from a short list of causes.
| Symptom | Likely cause | Fix |
|---|---|---|
| 401 Unauthorized | Missing or wrong key, or the environment variable is not set in the shell that runs uvicorn | Print bool(os.environ.get("LLM_API_KEY")) at startup and restart the server from the same shell |
| 404 on the request | Base URL missing the /v1 suffix, or a doubled /v1/v1 | Use exactly the base URL shown in the code above |
| Model not found | A model name copied from another project | Set the model to uncensored, or call GET /v1/models to confirm |
429 with concurrency | More simultaneous calls than your key allows | Add a semaphore sized to the key, 8 for full and 2 for trial |
429 with rate_limited | Too many requests in a minute | Slow the loop or queue work; a full key allows 300 per minute |
| Stream arrives all at once | A proxy is buffering | Disable buffering for that route |
When you open a support request, include the X-Request-Id response header. It lets the operator find the exact call. You can reach people through the site's support page.
Picking sampling settings per route
One service often needs different behavior on different routes, and the parameters are passed through to the model, so each route can set its own.
- Extraction and classification.
temperature=0with JSON mode. You want the same answer for the same input. - Chat and fiction. A temperature around 0.7 to 1.0, with
top_pleft alone. Raise the presence or frequency penalty a little if the text starts to repeat itself. - Tests. Pass a fixed
seedso a failing test can be reproduced, and compare structure instead of exact wording. - Short answers. Use
stopsequences to cut output at a delimiter, which also saves output tokens.
Change one setting at a time and rerun the same ten prompts. Guessing across three knobs at once makes it hard to know which one helped. Since output tokens cost more than input tokens, shorter replies are the quickest way to lower the bill, and a clear instruction such as "answer in under 80 words" often does more than any parameter.
For a wider view of what to expect from this kind of provider, see the best LLM API article.
More guides
Questions and answers
Do I need a special SDK to call this model from FastAPI?
No. The official openai Python package works once you set the base URL to https://api.llmhostingapi.com/v1 and use the model ID uncensored.
Should I use the sync or async client in FastAPI?
Use AsyncOpenAI inside async def routes so waiting on the model does not block the event loop. A sync client belongs in plain def routes, which FastAPI runs in a thread pool.
How do I avoid hitting the concurrency limit?
Put an asyncio.Semaphore sized to your key (8 for a full key, 2 for the trial) around each call, and hold it for the whole stream when streaming.
Does streaming cost more than a normal request?
No. Billing counts input and output tokens the same way, and usage is reported at the end of the stream.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.
Get API key