Arize Phoenix Tutorial: Comprehensive LLM Observability and Evaluation
Arize Phoenix is an open-source platform for observability, evaluation, and tracing of LLM applications. With Phoenix, you can trace every step of your AI pipeline execution, evaluate the quality of model responses, and detect performance issues in real-time. This tutorial will guide you from installation to advanced usage of Phoenix for building reliable AI applications.
Why Arize Phoenix?
Building LLM-powered applications goes far beyond calling a model API. The real challenges emerge after deployment: ensuring response quality remains high, identifying failing queries, and optimizing token costs. Phoenix provides comprehensive tooling to address these challenges:
- Tracing: Track every execution step from input to output, including retrieval, reranking, and generation
- Evaluation: Assess response quality using LLM-as-judge or custom metrics
- Dataset Management: Manage evaluation datasets for regression testing
- Experiment Tracking: Compare performance across prompt or model versions
Phoenix integrates with OpenTelemetry, so the traces it produces follow industry standards and can be exported to other observability backends.
Installation
Basic Installation
pip install arize-phoenix
Installation with Evaluation Dependencies
pip install "arize-phoenix[evals]"
Installation with OpenAI Instrumentation
pip install arize-phoenix openinference-instrumentation-openai openai
Full Installation for This Tutorial
pip install "arize-phoenix[evals]" \
openinference-instrumentation-openai \
openinference-instrumentation-langchain \
openinference-instrumentation-llamaindex \
openai langchain langchain-openai
Starting the Phoenix Server
Phoenix provides a UI dashboard that runs as a local server:
import phoenix as px
session = px.launchapp()
print(f"Phoenix UI: {session.url}")
The server runs at http://localhost:6006 by default. You can also start it from the command line:
phoenix serve
Basic Usage: Tracing OpenAI Applications
Setting Up Instrumentation
The first step is connecting Phoenix with the OpenAI client so that every API call is automatically recorded:
import phoenix as px
from openinference.instrumentation.openai import OpenAIInstrumentor
from phoenix.otel import register
session = px.launchapp()
tracerprovider = register(projectname="my-llm-app")
OpenAIInstrumentor().instrument(tracerprovider=tracerprovider)
Making Traced Calls
Once instrumentation is active, every OpenAI call is automatically traced:
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain what machine learning is in 3 sentences."}
],
temperature=0.7,
maxtokens=200
)
print(response.choices[0].message.content)
Open the Phoenix UI in your browser, and you will see the complete trace including:
- Input messages
- Model used
- Token count (input and output)
- Latency
- Response content
Adding Metadata to Traces
You can add additional context using OpenTelemetry attributes:
from opentelemetry import trace
tracer = trace.gettracer(name)
with tracer.startascurrentspan("customer-support-query") as span:
span.setattribute("user.id", "user-123")
span.setattribute("session.id", "session-456")
span.setattribute("query.category", "billing")
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a customer support agent."},
{"role": "user", "content": "How do I cancel my subscription?"}
]
)
span.setattribute("response.tokens", response.usage.totaltokens)
Tracing a RAG Pipeline
Phoenix is particularly valuable for observing Retrieval-Augmented Generation (RAG) pipelines. Here is a complete RAG pipeline tracing example:
import phoenix as px
from openinference.instrumentation.openai import OpenAIInstrumentor
from phoenix.otel import register
from openai import OpenAI
from opentelemetry import trace
px.launchapp()
tracerprovider = register(projectname="rag-pipeline")
OpenAIInstrumentor().instrument(tracerprovider=tracerprovider)
client = OpenAI()
tracer = trace.gettracer(name)
documents = [
{"id": 1, "text": "Python is a programming language created by Guido van Rossum in 1991."},
{"id": 2, "text": "Machine learning is a subset of AI that enables systems to learn from data."},
{"id": 3, "text": "Docker is a containerization platform that simplifies application deployment."},
{"id": 4, "text": "PostgreSQL is a powerful open-source relational database."},
]
def retrievedocuments(query, topk=2):
with tracer.startascurrentspan("retrieval") as span:
span.setattribute("retrieval.query", query)
span.setattribute("retrieval.topk", topk)
results = documents[:topk]
span.setattribute("retrieval.numresults", len(results))
for i, doc in enumerate(results):
span.setattribute(f"retrieval.document.{i}.id", doc["id"])
span.setattribute(f"retrieval.document.{i}.score", 0.95 - (i 0.1))
return results
def generateresponse(query, contextdocs):
context = "\n".join([doc["text"] for doc in contextdocs])
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": f"Answer based on the following context:\n{context}"},
{"role": "user", "content": query}
]
)
return response.choices[0].message.content
def ragquery(query):
with tracer.startascurrentspan("rag-pipeline") as span:
span.setattribute("input.query", query)
docs = retrievedocuments(query)
answer = generateresponse(query, docs)
span.setattribute("output.answer", answer)
return answer
result = ragquery("What is Python?")
print(result)
In the Phoenix UI, you will see a clear span hierarchy: rag-pipeline > retrieval > openai.chat, making it easy to identify bottlenecks at each stage.
Evaluation with LLM-as-Judge
Phoenix provides built-in evaluation modules that use LLMs to automatically assess response quality:
Setting Up the Evaluator
from phoenix.evals import (
OpenAIModel,
llmclassify,
runevals,
)
import pandas as pd
evalmodel = OpenAIModel(model="gpt-4o-mini")
Relevance Evaluation
from phoenix.evals import RelevanceEvaluator
relevanceevaluator = RelevanceEvaluator(evalmodel)
evaldata = pd.DataFrame({
"input": [
"What is Python?",
"How do I cook fried rice?",
],
"reference": [
"Python is a programming language.",
"Python is a programming language.",
],
"output": [
"Python is a programming language created by Guido van Rossum.",
"Fried rice is a popular dish made by stir-frying cooked rice with various ingredients.",
],
})
relevanceresults = relevanceevaluator.evaluate(evaldata)
print(relevanceresults)
Hallucination Detection
from phoenix.evals import HallucinationEvaluator
hallucinationevaluator = HallucinationEvaluator(evalmodel)
evaldata = pd.DataFrame({
"input": ["Who created Python?"],
"reference": ["Python was created by Guido van Rossum in 1991."],
"output": [
"Python was created by Guido van Rossum in 1991 in the Netherlands. "
"The language was named after the TV show Monty Python's Flying Circus."
],
})
hallucinationresults = hallucinationevaluator.evaluate(evaldata)
print(hallucinationresults)
Custom Evaluator
You can also create custom evaluators tailored to your specific needs:
from phoenix.evals import llmclassify
customtemplate = """
Evaluate whether the following response uses professional and polite language.
Query: {input}
Response: {output}
Provide a label:
- "professional" if the language is professional and polite
- "unprofessional" if there is inappropriate or overly casual language
Label:
"""
evaldata = pd.DataFrame({
"input": ["Explain about AI"],
"output": ["AI is like super cool stuff bro, it's totally awesome dude!"],
})
results = llmclassify(
dataframe=evaldata,
template=customtemplate,
model=evalmodel,
rails=["professional", "unprofessional"],
)
print(results)
LangChain Instrumentation
Phoenix also supports instrumentation for popular frameworks like LangChain:
import phoenix as px
from openinference.instrumentation.langchain import LangChainInstrumentor
from phoenix.otel import register
px.launchapp()
tracerprovider = register(projectname="langchain-app")
LangChainInstrumentor().instrument(tracerprovider=tracerprovider)
from langchainopenai import ChatOpenAI
from langchaincore.prompts import ChatPromptTemplate
from langchaincore.outputparsers import StrOutputParser
prompt = ChatPromptTemplate.frommessages([
("system", "You are a professional translator. Translate the following text to {language}."),
("user", "{text}")
])
model = ChatOpenAI(model="gpt-4o-mini")
parser = StrOutputParser()
chain = prompt | model | parser
result = chain.invoke({
"language": "Japanese",
"text": "Good morning, how are you today?"
})
print(result)
Each component of the chain (prompt template, model call, output parser) will appear as a separate span in the Phoenix UI.
LlamaIndex Instrumentation
import phoenix as px
from openinference.instrumentation.llamaindex import LlamaIndexInstrumentor
from phoenix.otel import register
px.launchapp()
tracerprovider = register(projectname="llamaindex-app")
LlamaIndexInstrumentor().instrument(tracerprovider=tracerprovider)
from llamaindex.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llamaindex.llms.openai import OpenAI
Settings.llm = OpenAI(model="gpt-4o-mini")
documents = SimpleDirectoryReader("data").loaddata()
index = VectorStoreIndex.fromdocuments(documents)
queryengine = index.asqueryengine()
response = queryengine.query("What are the main points of this document?")
print(response)
Advanced Usage
Dataset Management for Regression Testing
Phoenix allows you to store evaluation datasets for regression testing:
import phoenix as px
from phoenix.experiments import runexperiment
import pandas as pd
pxclient = px.Client()
dataset = pxclient.uploaddataset(
datasetname="customer-support-eval",
dataframe=pd.DataFrame({
"input": [
"How do I reset my password?",
"What is the price of the premium plan?",
"Is there a free trial?",
],
"expectedoutput": [
"Click 'Forgot Password' on the login page, enter your email, and follow the instructions.",
"The premium plan starts at $9.99/month.",
"Yes, a 14-day free trial is available without a credit card.",
],
}),
)
Running Experiments
from openai import OpenAI
client = OpenAI()
def runtask(example):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful customer support agent."},
{"role": "user", "content": example["input"]}
]
)
return response.choices[0].message.content
def evalrelevance(example, taskoutput):
return "reset" in taskoutput.lower() if "reset" in example["input"].lower() else True
experiment = runexperiment(
dataset=dataset,
task=runtask,
evaluators=[evalrelevance],
experimentname="cs-bot-v1",
)
Production Monitoring
For production monitoring, you can send traces to a separately running Phoenix server:
from phoenix.otel import register
tracerprovider = register(
projectname="production-app",
endpoint="http://phoenix-server:6006/v1/traces",
)
Exporting Traces to DataFrame
Phoenix allows you to export traces to a pandas DataFrame for further analysis:
import phoenix as px
pxclient = px.Client()
spansdf = pxclient.getspansdataframe()
print(f"Total traces: {len(spansdf)}")
print(f"Average latency: {spansdf['latencyms'].mean():.2f} ms")
print(f"Total tokens: {spansdf['llm.tokencount.total'].sum()}")
slowqueries = spansdf[spansdf['latencyms'] > 5000]
print(f"\nSlow queries (>5s): {len(slowqueries)}")
Filtering and Grouping Traces
errortraces = spansdf[spansdf['statuscode'] == 'ERROR']
print(f"Error rate: {len(errortraces)/len(spansdf)100:.1f}%")
bymodel = spansdf.groupby('llm.modelname').agg({
'latencyms': 'mean',
'llm.tokencount.total': 'sum',
}).round(2)
print("\nPerformance by model:")
print(bymodel)
Best Practices
1. Good Project Organization
Use descriptive and consistent project names for easy navigation in the Phoenix UI:
tracerprovider = register(projectname="chatbot-production-v2")
2. Add Meaningful Metadata
Metadata helps you filter and analyze traces effectively:
span.setattribute("user.tier", "premium")
span.set
attribute("feature.name", "document-qa")
span.setattribute("prompt.version", "v2.1")
3. Use Layered Evaluation
Combine multiple evaluators for a comprehensive quality assessment:
evaluators = [
RelevanceEvaluator(evalmodel),
HallucinationEvaluator(evalmodel),
ToxicityEvaluator(evalmodel),
]
4. Set Up Alerting for Production
Monitor key metrics and set up alerts for anomalies:
spansdf = pxclient.getspansdataframe()
avglatency = spansdf['latencyms'].mean()
errorrate = len(spansdf[spansdf['statuscode'] == 'ERROR']) / len(spansdf)
if avglatency > 3000:
print(f"ALERT: High latency detected: {avglatency:.0f}ms")
if errorrate > 0.05:
print(f"ALERT: High error rate: {errorrate:.1%}")
5. Regression Testing with Datasets
Run evaluations periodically against fixed datasets to detect regressions:
experimentv1 = runexperiment(
dataset=evaldataset,
task=runtaskv1,
evaluators=evaluators,
experimentname="prompt-v1",
)
experimentv2 = runexperiment(
dataset=evaldataset,
task=runtaskv2,
evaluators=evaluators,
experimentname="prompt-v2",
)
6. Deploying Phoenix for Teams
For team use, deploy Phoenix as a shared service:
docker run -d \
--name phoenix \
-p 6006:6006 \
-v phoenix-data:/data \
arizephoenix/phoenix:latest
All team members can then send traces to the same server:
tracerprovider = register(
project
name="team-project",
endpoint="http://phoenix.internal:6006/v1/traces",
)
Conclusion
Arize Phoenix provides a solid foundation for LLM application observability. With OpenTelemetry-based tracing, automated evaluation using LLM-as-judge, and dataset management for regression testing, Phoenix helps you build and maintain AI applications with confidence.
Key takeaways:
By applying these practices, you can identify and fix quality issues before they impact users, optimize token usage costs, and continuously improve the performance of your AI applications.