Deploying Models and AI Apps
Deploying a model means making it available to real users through a reliable service, usually a web API that other programs call. A good deployment loads the model once, checks every input, reports its own health and version, answers quickly under load, and can be updated or rolled back without downtime. The model is often the easy part; the service around it is what makes it dependable.
Ways to Serve a Model
| Option | Description |
|---|---|
| Your own API service | It is used to wrap the model in a web service such as FastAPI, running on a server or in containers |
| Serverless functions | It is used for light, bursty traffic; the cloud runs your code only when called |
| Model-serving tools | Dedicated servers such as vLLM, TGI or Triton for fast LLM and GPU serving |
| Hosted model APIs | It is used to call a provider's model, so there is no model to run yourself; see "Hosted, Open and Local Models" |
| On the device | It is used to run small models in a phone, browser or laptop app, for privacy and offline use |
Example: Campus Helper as a Web Service
The programs in this chapter need pip install fastapi httpx sentence-transformers scikit-learn torch transformers. Several use faq.json from "Semantic Search" and eval_set.json from "Building an Evaluation Set". Download and loading messages are left out of the output shown.
This program serves the semantic-search Campus Helper from "Semantic Search" with FastAPI, the framework from "Frontend, Backend and the Model". FastAPI's test client sends requests to it without starting a server.
import json
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
from sentence_transformers import SentenceTransformer
VERSION = "campus-helper 1.0 (all-MiniLM-L6-v2, threshold 0.35)"
DECLINE = "Sorry, I can only answer questions about this school. Please contact the school office."
# Load the model and the documents ONCE, when the service starts, not on every request
texts = [item["text"] for item in json.load(open("faq.json"))]
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
vectors = model.encode(texts, normalize_embeddings=True)
app = FastAPI(title="Campus Helper")
class Question(BaseModel):
question: str = Field(min_length=3, max_length=300) # reject empty or huge inputs
@app.get("/health")
def health():
return {"status": "ok", "version": VERSION, "documents": len(texts)}
@app.post("/ask")
def ask(q: Question):
scores = vectors @ model.encode(q.question, normalize_embeddings=True)
best = int(scores.argmax())
if scores[best] < 0.35:
return {"answer": DECLINE, "source": None, "score": round(float(scores[best]), 3)}
return {"answer": texts[best], "source": f"FAQ #{best + 1}", "score": round(float(scores[best]), 3)}
client = TestClient(app) # sends requests without starting a server
print(client.get("/health").json())
for question in ["How much is the library fee?", "Who won the game last night?"]:
r = client.post("/ask", json={"question": question})
print(r.status_code, r.json())
bad = client.post("/ask", json={"question": ""})
print(bad.status_code, bad.json()["detail"][0]["msg"]){'status': 'ok', 'version': 'campus-helper 1.0 (all-MiniLM-L6-v2, threshold 0.35)', 'documents': 50}
200 {'answer': 'The library fee is $15 a year and covers book loans and printing.', 'source': 'FAQ #3', 'score': 0.801}
200 {'answer': 'Sorry, I can only answer questions about this school. Please contact the school office.', 'source': None, 'score': 0.152}
422 String should have at least 3 charactersExplanation:
- The model and documents load once, when the service starts. Loading a model on every request would make each answer take seconds instead of milliseconds.
/healthreports that the service is up and which version is running, so monitoring tools and the team always know what is in production./askanswers with the closest FAQ entry, its source and the similarity score, or declines below 0.35. Returning the score helps monitoring spot weak answers later.Questionis a Pydantic model that validates input: an empty question is rejected with status 422 before it reaches the model. Limits likemax_length=300also block huge inputs that would waste money or memory.- To run it for real, save it as
app.pywithout the test-client lines and start it withuvicorn app:app.
Example: Batching and Caching
Two of the simplest ways to serve more requests on the same hardware are batching (processing many inputs in one call) and caching (remembering answers to repeated inputs). This program measures both, using the 50 questions in eval_set.json.
import json
import time
from functools import lru_cache
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
questions = [case["question"] for case in json.load(open("eval_set.json"))] # from "Building an Evaluation Set"
model.encode(questions[:2]) # warm up once, as a running service would be
start = time.perf_counter()
for q in questions:
model.encode(q) # one request at a time
one_by_one = time.perf_counter() - start
start = time.perf_counter()
model.encode(questions, batch_size=50) # all 50 in one batch
batched = time.perf_counter() - start
print(f"50 questions one by one: {one_by_one * 1000:6.1f} ms ({one_by_one / 50 * 1000:.2f} ms each)")
print(f"50 questions in a batch: {batched * 1000:6.1f} ms ({batched / 50 * 1000:.2f} ms each)")
print(f"Batching was {one_by_one / batched:.1f} times faster")
@lru_cache(maxsize=1000) # remember answers to repeated questions
def embed(question):
return model.encode(question)
popular = ["What time is lunch?"] * 30 + questions[:20] # many parents ask the same thing
start = time.perf_counter()
for q in popular:
embed(q)
cached = time.perf_counter() - start
info = embed.cache_info()
print(f"\n50 requests with a cache: {cached * 1000:.1f} ms, {info.hits} served from the cache, {info.misses} computed")50 questions one by one: 174.6 ms (3.49 ms each)
50 questions in a batch: 64.1 ms (1.28 ms each)
Batching was 2.7 times faster
50 requests with a cache: 62.3 ms, 29 served from the cache, 21 computedExplanation:
- One by one, each question took about 3.49 ms; in one batch of 50, about 1.28 ms each, 2.7 times faster. A model processes a batch with the same matrix operations it uses for one input, so the hardware stays busier. LLM servers do this constantly, combining requests from many users.
lru_cacheremembers results for up to 1,000 different questions. With 30 copies of "What time is lunch?" among 50 requests, 29 were served from the cache, and only 21 needed the model.- These timings are one run on this laptop; they change between runs and machines, but the pattern holds.
Releasing Safely
| Practice | What it does |
|---|---|
| Containers | Package the code, model and libraries together, so they run the same everywhere |
| Staging | Test a new version in a copy of production before real users see it |
| Canary or staged rollout | Send a few percent of traffic to the new version first; see "Launching AI Features: Pilots and Experiments" |
| Rollback | Keep the previous version ready, and switch back in minutes if quality drops |
| Rate limits and timeouts | Protect the service and your budget from floods of requests |
| Secrets management | Keep API keys in a secrets store, never in code; see "Tokens, Cost and Rate Limits" |
Common Mistakes
Loading the model inside the request handler. Every request pays the loading time.
No input limits. Huge or malformed inputs waste money and can crash the service.
Deploying without a version label. When users report a problem, you can't tell which version answered.
Testing only one request at a time. Real traffic arrives in bursts; test under realistic load.
Interview Corner
How would you deploy a model as an API?
Wrap it in a web service that loads the model once at startup, validates inputs, exposes prediction and health endpoints with the version, and runs in containers behind a load balancer. Release it with a staged rollout and keep the previous version ready for rollback.
How do batching and caching improve serving?
Batching processes several inputs in one model call, using the hardware more efficiently; caching returns stored results for repeated inputs without calling the model. Both raise throughput and cut cost, as long as cached answers are safe to share.
Practice
Exercise: a version endpoint and a limit. Add max_length=100 to Question, and send a 150-character question. What status and message come back? Then add a /version endpoint that returns only the version string.
Check your understanding:
- Why should the model load at startup instead of inside
/ask? - What did status 422 mean for the empty question?
- When would caching answers be unsafe?
Key Takeaways
Quick reference
| Need | Code or practice |
|---|---|
| An endpoint | @app.post("/ask") |
| Validate input | class Question(BaseModel): question: str = Field(min_length=3, max_length=300) |
| Test without a server | TestClient(app).post("/ask", json={...}) |
| Run for real | uvicorn app:app |
| Batch | model.encode(list_of_texts, batch_size=50) |
| Cache | @lru_cache(maxsize=1000) |
Was this tutorial helpful?