Real-Time Production Evaluation
Validate every LLM interaction in a live FastAPI service — correctness, hallucination, and your own policy metrics — with zero added latency.
Once your assistant is serving real traffic, you want every reply validated — not a nightly sample. This cookbook wires Prisma into a production FastAPI service so each LLM call is traced and validated server-side, off the request path: the caller gets their response immediately while correctness, hallucination, and a custom tone metric run in the background.
What you'll build
A FastAPI chatbot that initializes Prisma in its lifespan, instruments the OpenAI client, and serves a /chat endpoint whose every call is validated by three evaluators — with a /health check and a live-reconfiguration endpoint that adds an evaluator without a restart.
Before you start
- Python 3.10+, a Prisma API key (
pq_prisma_sk_…), and an OpenAI API key. PALQEE_PRISMA_API_KEY,PALQEE_PRISMA_BASE_URL, andOPENAI_API_KEYset — see Installation & Setup.
pip install palqee-prisma-ai openai openinference-instrumentation-openai fastapi uvicornStep 1 — Define a custom evaluator
Alongside the built-in correctness and hallucination checks, define a tone policy metric for customer-facing replies. It uses the 4-prompt pattern: the re-evaluation prompt pulls prior expert decisions through {context}, and score_assignments turns each label into a trackable number.
from palqee_prisma_ai import Evaluators
tone = Evaluators.custom(
name="tone",
evaluation_options=["professional", "acceptable", "unprofessional"],
score_assignments={"professional": 1.0, "acceptable": 0.5, "unprofessional": 0.0},
evaluation_system_prompt=(
"You are a customer-support quality auditor for a financial-services firm. "
"Judge whether the agent response is empathetic, clear, and appropriate for "
"customer-facing communication. Classify it as one of: {evaluation_options}."
),
evaluation_human_prompt=(
"Customer: {query}\n"
"Agent: {response}\n\n"
"Classify the tone. Choose one of {evaluation_options}."
),
reeval_system_prompt=(
"You are a senior quality auditor re-reviewing a borderline tone case, "
"guided by prior expert decisions. Classify as one of: {evaluation_options}."
),
reeval_human_prompt=(
"Customer: {query}\n"
"Agent: {response}\n"
"Relevant prior expert decisions:\n{context}\n\n"
"Give your final classification: {evaluation_options}."
),
)Step 2 — Initialize Prisma in the FastAPI lifespan
The lifespan context manager is the right place to start and stop Prisma. init() is synchronous and safe to call here; on shutdown, session.end() flushes any spans still in the buffer so nothing is lost.
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from openinference.instrumentation.openai import OpenAIInstrumentor
import palqee_prisma_ai
from palqee_prisma_ai import EvaluationConfig, get_session
logger = logging.getLogger("chatbot")
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: create the project + run and configure tracing.
palqee_prisma_ai.init(
"customer-support-chatbot",
run_name="production",
evaluators=["correctness", "hallucination", tone],
)
OpenAIInstrumentor().instrument()
session = get_session()
if session:
logger.info("Prisma initialized — project=%s run=%s", session.project_id, session.run_id)
yield
# Shutdown: flush pending spans.
session = get_session()
if session:
session.end()
logger.info("Prisma session ended, spans flushed")
app = FastAPI(title="Customer Support Chatbot", lifespan=lifespan)init() creates the project and the run with all three evaluators attached; OpenAIInstrumentor().instrument() patches the client so every completion becomes a span. get_session() hands back the active PrismaSession for health checks and logging.
Step 3 — Serve the chat endpoint
A standard FastAPI handler. The OpenAI call is traced automatically — your endpoint code doesn't reference Prisma at all, and validation happens server-side, so the response returns with no added latency.
from openai import AsyncOpenAI
from pydantic import BaseModel
oai = AsyncOpenAI()
SYSTEM_PROMPT = (
"You are a support assistant for a financial-services firm. Be professional, "
"empathetic, and concise. If you don't know the answer, say so rather than guessing."
)
class ChatRequest(BaseModel):
message: str
class ChatResponse(BaseModel):
reply: str
@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest) -> ChatResponse:
response = await oai.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": request.message},
],
temperature=0.3,
)
return ChatResponse(reply=response.choices[0].message.content or "")Step 4 — Instrument more frameworks (optional)
If you use more than one LLM library, instrument each — every traced call flows to the same run and is validated by the same evaluators.
OpenAIInstrumentor().instrument()
# pip install openinference-instrumentation-langchain
# from openinference.instrumentation.langchain import LangChainInstrumentor
# LangChainInstrumentor().instrument()Anthropic (openinference-instrumentation-anthropic), Bedrock, and LlamaIndex follow the same .instrument() pattern — see Instrumentation & Tracing.
Step 5 — Expose a health check
Use get_session() to confirm Prisma is live:
@app.get("/health")
async def health():
session = get_session()
if session is None:
return {"status": "degraded", "prisma": "not initialized"}
return {"status": "healthy", "project_id": session.project_id, "run_id": session.run_id}Aggregate pass rates, ambiguous counts, and cost appear in the project Overview within seconds of traffic arriving — see Real-Time Monitoring.
Step 6 — Update evaluators without a restart
session.update_evaluation_config() swaps the run's evaluators live — useful for rolling out a new check or responding to an incident. New interactions are validated against the update; in-flight ones keep the config that was active when they arrived.
Protect admin endpoints
This example omits auth for brevity. In production, put authentication middleware in front of any endpoint that reconfigures evaluation.
from palqee_prisma_ai import Evaluators
pii = Evaluators.custom(
name="pii-detection",
evaluation_options=["clean", "contains_pii"],
score_assignments={"clean": 1.0, "contains_pii": 0.0},
evaluation_system_prompt=(
"You are a data-privacy auditor. Determine whether the agent response exposes "
"personally identifiable information (names, emails, phone numbers, addresses, "
"account numbers). Classify it as one of: {evaluation_options}."
),
evaluation_human_prompt=(
"Customer: {query}\n"
"Agent: {response}\n\n"
"Does the response contain PII? Choose one of {evaluation_options}."
),
reeval_system_prompt=(
"You are a senior data-privacy auditor re-reviewing a borderline PII case, "
"guided by prior expert decisions. Classify as one of: {evaluation_options}."
),
reeval_human_prompt=(
"Customer: {query}\n"
"Agent: {response}\n"
"Relevant prior expert decisions:\n{context}\n\n"
"Give your final classification: {evaluation_options}."
),
)
@app.post("/admin/update-evaluators")
async def update_evaluators():
session = get_session()
if session is None:
return {"error": "Prisma session not active"}
session.update_evaluation_config(
EvaluationConfig(evaluators=["correctness", "hallucination", tone, pii])
)
return {"status": "evaluators updated — PII detection added"}Step 7 — Production notes
- Span batching. The OTEL SDK batches spans, so validations appear a few seconds after traffic — no per-request overhead.
- Graceful shutdown.
session.end()in the lifespan flush is what saves the spans generated in the final seconds before exit. A hardSIGKILLstill drops whatever is buffered. - Environment-specific evaluators. Run heavier checks in staging, the critical ones in production:
import os
evaluators = ["correctness", "hallucination", tone]
if os.getenv("APP_ENV") == "production":
evaluators = ["correctness", "hallucination"]Complete example
"""Real-time validation of production LLM traffic with Prisma."""
import logging
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI
from openai import AsyncOpenAI
from openinference.instrumentation.openai import OpenAIInstrumentor
from pydantic import BaseModel
import palqee_prisma_ai
from palqee_prisma_ai import Evaluators, get_session
logger = logging.getLogger("chatbot")
# -- Custom tone metric -------------------------------------------------------
tone = Evaluators.custom(
name="tone",
evaluation_options=["professional", "acceptable", "unprofessional"],
score_assignments={"professional": 1.0, "acceptable": 0.5, "unprofessional": 0.0},
evaluation_system_prompt=(
"You are a customer-support quality auditor for a financial-services firm. "
"Judge whether the agent response is empathetic, clear, and appropriate for "
"customer-facing communication. Classify it as one of: {evaluation_options}."
),
evaluation_human_prompt=(
"Customer: {query}\nAgent: {response}\n\n"
"Classify the tone. Choose one of {evaluation_options}."
),
reeval_system_prompt=(
"You are a senior quality auditor re-reviewing a borderline tone case, "
"guided by prior expert decisions. Classify as one of: {evaluation_options}."
),
reeval_human_prompt=(
"Customer: {query}\nAgent: {response}\n"
"Relevant prior expert decisions:\n{context}\n\n"
"Give your final classification: {evaluation_options}."
),
)
# -- Lifespan -----------------------------------------------------------------
environment = os.getenv("APP_ENV", "production")
evaluators = ["correctness", "hallucination", tone]
if environment == "production":
evaluators = ["correctness", "hallucination", tone]
@asynccontextmanager
async def lifespan(app: FastAPI):
palqee_prisma_ai.init(
"customer-support-chatbot",
run_name=environment,
evaluators=evaluators,
)
OpenAIInstrumentor().instrument()
session = get_session()
if session:
logger.info("Prisma initialized — project=%s run=%s", session.project_id, session.run_id)
yield
session = get_session()
if session:
session.end()
logger.info("Prisma session ended, spans flushed")
app = FastAPI(title="Customer Support Chatbot", lifespan=lifespan)
# -- Chat endpoint ------------------------------------------------------------
oai = AsyncOpenAI()
SYSTEM_PROMPT = (
"You are a support assistant for a financial-services firm. Be professional, "
"empathetic, and concise. If you don't know the answer, say so rather than guessing."
)
class ChatRequest(BaseModel):
message: str
class ChatResponse(BaseModel):
reply: str
@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest) -> ChatResponse:
response = await oai.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": request.message},
],
temperature=0.3,
)
return ChatResponse(reply=response.choices[0].message.content or "")
@app.get("/health")
async def health():
session = get_session()
if session is None:
return {"status": "degraded", "prisma": "not initialized"}
return {"status": "healthy", "project_id": session.project_id, "run_id": session.run_id}Run it and send a request:
uvicorn app:app --host 0.0.0.0 --port 8000
curl -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-d '{"message": "I can not log in to my account. Can you help?"}'The reply returns immediately; the trace is batched, sent, and validated server-side by all three evaluators within seconds.
Extend it
- Route the ambiguous cases. Wire the Human Review queue so experts settle borderline calls and feed the flywheel.
- Alert on the rate. Push a webhook when a violation rate climbs — see Real-Time Monitoring.
Next steps
- Real-Time Monitoring — watch and alert on live validations
- Human Review — settle ambiguous cases and sharpen the metrics
- Policy Metrics — author more checks like
toneandpii-detection
Call Center QA
Validate a backlog of contact-center transcripts against correctness, hallucination, and a custom policy metric — at full-population coverage.
CI/CD Quality Gates
Catch LLM regressions before they ship — generate fresh answers on every pull request, validate them with Prisma, and block the merge when quality drops.

