Hello! Welcome to the final lesson of your course, Deploying AI Models as Services. This lesson also marks the culmination of your journey from the fundamentals of AI to deploying advanced LLM applications.
In our last session, you instrumented your FastAPI service with structured logging, giving you the power to trace and debug individual requests. This is the first pillar of observability. Today, we build the second pillar: metrics.
Your learning outcome is to set up a monitoring dashboard to visualize key health and performance metrics of a deployed AI service. While logs tell you what happened for a specific event, metrics tell you how your system is performing in aggregate. For real-time monitoring, dashboards, and alerting, a dedicated metrics system is the industry standard.
We will use the powerful and popular open-source stack of Prometheus and Grafana to achieve this. Your experience as a backend developer and your familiarity with Docker will be a great asset as we assemble these components.
1. The Observability Stack: Prometheus & Grafana
Before diving into code, let's understand the architecture. Monitoring a service like ours involves three key components:
- Your Application (The Target): Your FastAPI service will be instrumented to expose its internal metrics (like request latency, error counts, etc.) on a special HTTP endpoint, typically
/metrics. - Prometheus (The Scraper & Database): A time-series database that periodically "scrapes" (pulls) the data from your application's
/metricsendpoint. It stores this data efficiently, indexed by time. - Grafana (The Visualizer): A dashboarding tool that connects to Prometheus as a data source. You use it to query the metrics stored in Prometheus and build powerful, interactive visualizations and dashboards.
This "pull-based" architecture is extremely common in modern cloud-native systems.

2. Identifying Key Metrics for an LLM Service
What should we measure? For a service that serves an LLM, some metrics are crucial for monitoring both performance and cost.
Setting Up Prometheus and Grafana to Monitor AI API Usage
The article 'Setting Up Prometheus and Grafana to Monitor AI API Usage' provides an excellent starting list of essential metrics. Let's review them.
Read 'Step 1: What Should You Monitor?'. Pay attention to the 'Why It Matters' column, as it connects each metric to a business or operational concern like cost management or performance.
Based on this, we'll focus on tracking:
- API Latency: How long do requests take? We'll use a
Histogramto track the distribution of response times. - Request/Error Count: How many requests are we serving, and how many are failing? We'll use a
Counter. - Token Usage: How many tokens are being processed? This is critical for cost management. We'll simulate this with another
Counter.
3. Instrumenting Your FastAPI Application
Now, let's get practical. We need to add the prometheus-client library to our application to create and expose these metrics.
First, add it to your project:
pip install prometheus-client
Remember to add prometheus-client to your requirements.txt file as well.
Next, we'll modify main.py to define our metrics and update them. The best place to handle request-wide metrics like latency and errors is in middleware, a concept you're already familiar with from our logging lesson.
Setting Up Prometheus and Grafana to Monitor AI API Usage
The same article provides a fantastic FastAPI middleware implementation for Prometheus. We will adapt this code for our application.
Review the code in 'Step 2: Expose Metrics via FastAPI + Prometheus'. Focus on how Counter and Histogram are defined and how they are updated within the middleware (.inc() and .observe()).
Here is the updated main.py incorporating these ideas.
# main.py
import time
import os
# ... other imports
from fastapi import FastAPI, Request, Depends, HTTPException, status
from fastapi.responses import StreamingResponse, Response
from fastapi.security import APIKeyHeader
# Import Prometheus client library
from prometheus_client import Counter, Histogram, generate_latest
# --- Metrics Definitions ---
# Use a Histogram for latency, as it allows calculating quantiles (e.g., p95, p99)
API_LATENCY = Histogram("api_latency_seconds", "Latency of API responses", ["http_path"])
# Use a Counter for total requests and errors
API_REQUESTS = Counter("api_requests_total", "Total number of API requests", ["http_path", "http_status_code"])
# Counter for token usage (critical for LLMs)
TOKEN_USAGE = Counter("api_token_usage_total", "Total tokens used", ["model"])
# ... your existing app and logging setup
# --- Middleware for Metrics ---
@app.middleware("http")
async def track_metrics(request: Request, call_next):
start_time = time.monotonic()
try:
response = await call_next(request)
# This block executes after the endpoint has processed the request
duration = time.monotonic() - start_time
# Observe latency
API_LATENCY.labels(http_path=request.url.path).observe(duration)
# Increment request counter
API_REQUESTS.labels(http_path=request.url.path, http_status_code=response.status_code).inc()
return response
except Exception as e:
# If an unhandled exception occurs, we can still log metrics
duration = time.monotonic() - start_time
API_LATENCY.labels(http_path=request.url.path).observe(duration)
API_REQUESTS.labels(http_path=request.url.path, http_status_code=500).inc()
raise e # Re-raise the exception
# --- Metrics Endpoint ---
@app.get("/metrics")
def metrics():
return Response(content=generate_latest(), media_type="text/plain")
# --- Security and API Endpoint ---
# ... your existing get_api_key function
# Update your streaming endpoint to track token usage
@app.post("/query-stream/")
async def query_stream(query: str, api_key: str = Depends(get_api_key)):
logger.info("Received query for streaming response", query=query)
# --- Simulate Token Counting ---
# In a real application, you would get token counts from your LLM provider's response.
# For this exercise, we'll simulate it by incrementing the counter.
# This logic belongs in the endpoint itself, as it's specific to the model's work.
model_name = "simulated_llm_v1"
simulated_prompt_tokens = len(query.split())
simulated_completion_tokens = 150 # Assume an average completion length
TOKEN_USAGE.labels(model=model_name).inc(simulated_prompt_tokens + simulated_completion_tokens)
try:
# Replace this with your actual LLM client call
async def fake_llm_stream():
for word in "This is a streamed response from our AI model.".split():
yield f"data: {word}\n\n"
time.sleep(0.1)
return StreamingResponse(fake_llm_stream(), media_type="text/event-stream")
except Exception as e:
logger.exception("Error during streaming query", query=query)
raise HTTPException(status_code=500, detail="Internal error")
Notice we added a /metrics endpoint. This is what Prometheus will connect to.
4. Running the Stack with Docker Compose
We now have three services to run: our FastAPI app, Prometheus, and Grafana. Managing them individually is tedious. As a backend engineer, you know that docker-compose is the right tool for this job. It allows us to define and run a multi-container application with a single command.
Create a prometheus.yml file. This tells Prometheus where to find your application.
# prometheus.yml
global:
scrape_interval: 15s # How often to scrape targets
scrape_configs:
- job_name: 'fastapi-app'
metrics_path: /metrics
static_configs:
- targets: ['app:8000'] # 'app' is the service name in docker-compose
Note: We use app:8000 because Docker Compose creates a network where services can reach each other by their service name.
Now, create a docker-compose.yml file in your project's root directory:
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "8000:8000"
env_file:
- .env
volumes:
- .:/app # Mounts current directory for live code reloading during development
prometheus:
image: prom/prometheus:latest
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
command:
- '--config.file=/etc/prometheus/prometheus.yml'
depends_on:
- app
grafana:
image: grafana/grafana-oss:latest
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin # Default password, change in production
depends_on:
- prometheus
You can now launch the entire stack with one command:
docker-compose up --build
5. Building Your First Dashboard
With everything running, it's time for the final piece: visualization.
- Access Grafana: Open your browser and go to
http://localhost:3000. Log in with useradminand the password you set (admin). - Add Data Source:
- Navigate to the gear icon (Configuration) > Data Sources.
- Click "Add data source" and select "Prometheus".
- For the "Prometheus server URL", enter
http://prometheus:9090. (Again, using the service name). - Click "Save & Test". You should see a green checkmark.
- Generate Some Traffic: Use
curlor another tool to send a few requests to your API athttp://localhost:8000/query-stream/to generate some metrics. - Create a Dashboard:
- Click the
+icon in the left sidebar and select "Dashboard". - Click "Add visualization".
- In the query editor, make sure your Prometheus data source is selected.
- Click the
Now, let's write some queries using PromQL (Prometheus Query Language).
Setting Up Prometheus and Grafana to Monitor AI API Usage
The article 'Setting Up Prometheus and Grafana' provides several ready-to-use PromQL queries that are perfect for our dashboard.
Look at the queries under 'Step 5: Build Useful Dashboards'. We will implement a few of these in Grafana.
Panel 1: API Request Rate
This shows the number of requests per second. The rate() function is perfect for this.
- Query:
rate(api_requests_total[1m]) - Legend:
{{http_path}} - {{http_status_code}} - Visualization: Time series
Panel 2: 95th Percentile Latency (p95)
This is a critical metric. It tells you that 95% of your requests are faster than this value. It's more robust than an average, as it's less sensitive to extreme outliers.
- Query:
histogram_quantile(0.95, sum(rate(api_latency_seconds_bucket[5m])) by (le, http_path)) - Visualization: Time series or a Gauge for the current value.
Panel 3: Total Token Usage
This is a simple sum of our token counter, essential for cost tracking.
- Query:
sum by (model) (api_token_usage_total) - Visualization: A Stat or Gauge panel is good for this.
Go ahead and create these panels. Arrange them on your dashboard. You have now built a real-time monitoring system!

Test your understanding!
How would you write a PromQL query to show the rate of server-side errors (HTTP status code 5xx) over the last 5 minutes for the /query-stream/ endpoint only?
Show answer
You would use the rate() function combined with label selectors to filter the metrics.
The query would be:rate(api_requests_total{http_path="/query-stream/", http_status_code=~"5.."}[5m])
api_requests_total{...}selects the metric.http_path="/query-stream/"filters for the specific endpoint.http_status_code=~"5.."uses a regex (=~) to match any status code that starts with '5'.[5m]specifies the time window for the rate calculation.
Conclusion and Course Wrap-Up
Congratulations! You have successfully built a monitoring dashboard for a deployed AI service. You've connected instrumentation, data collection, and visualization into a complete observability pipeline.
Lesson Takeaways:
- Metrics are for Aggregates: They are essential for understanding system health, performance trends, and for triggering alerts.
- Prometheus & Grafana form a powerful, open-source stack for collecting and visualizing time-series data.
- Instrumentation is Key: An application must be instrumented using a client library (like
prometheus-client) to expose its metrics. - PromQL is the language you use to query Prometheus and turn raw data into meaningful insights.
A Journey Completed
This lesson marks the end of our course. Look back at how far you've come. You started with the mathematical foundations of AI, mastered the Python tools of the trade, and then dove deep into model training and deep learning with PyTorch.
You then tackled the architecture that powers modern generative AI—Transformers—and learned to wield LLMs through prompt engineering. You built sophisticated systems with Retrieval-Augmented Generation (RAG), customized models with fine-tuning, and gave them agency with AI agents.
Finally, you took your creations to the world, learning to optimize, deploy, and monitor them as production-grade services. You've bridged the gap from software engineering to AI engineering.
Your goal was to pivot your career. You now possess a comprehensive, practical skill set that is in high demand.
What's Next?
Your learning journey doesn't stop here. The field of AI evolves rapidly.
- Build a Portfolio: Apply what you've learned to a unique project that interests you. A deployed, monitored AI agent or a fine-tuned RAG system makes for a powerful portfolio piece.
- Go Deeper: Pick an area that fascinated you—be it agent architectures, quantization, or prompt engineering—and explore it further.
- Stay Current: Follow key researchers on social media, read papers on arXiv, and experiment with new models and techniques as they are released.
- Contribute: Consider contributing to open-source AI projects. It's a fantastic way to learn and network.
You have the foundation. You have the skills. Go build the future. It has been a pleasure being your tutor on this journey.