Package: arize-phoenix
Phoenix provides MLOps and LLMOps insights at lightning speed with zero-config observability. Phoenix provides a notebook-first experience for monitoring your models and LLM Applications by providing:LLM Traces- Trace through the execution of your LLM Application to understand the internals of your LLM Application and to troubleshoot problems related to things like retrieval and tool execution.LLM Evals- Leverage the power of large language models to evaluate your generative model or application's relevance, toxicity, and more.Embedding Analysis- Explore embedding point-clouds and identify clusters of high drift and performance degradation.RAG Analysis- Visualize your generative application's search and retrieval process to solve improve your retrieval-augmented generation.Structured Data Analysis- Statistically analyze your structured data by performing A/B analysis, temporal drift analysis, and more.Table of ContentsInstallationLLM TracesTracing with LlamaIndexTracing with LangChainLLM EvalsEmbedding AnalysisUMAP-based Exploratory Data AnalysisCluster-driven Drift and Performance AnalysisExportable ClustersRetrieval-Augmented Generation AnalysisStructured Data AnalysisDeploying PhoenixBreaking ChangesCommunityThanksCopyright, Patent, and LicenseInstallationInstall Phoenix viapipor orcondaas well as any of its subpackages.pipinstallarize-phoenixSome functionality such as LLM evals are under theexperimentalsubpackage.pipinstallarize-phoenix[experimental]LLM TracesWith the advent of powerful LLMs, it is now possible to build LLM Applications that can perform complex tasks like summarization, translation, question and answering, and more. However, these applications are often difficult to debug and troubleshoot as they have an extensive surface area: search and retrieval via vector stores, embedding generation, usage of external tools and so on. Phoenix provides a tracing framework that allows you to trace through the execution of your LLM Application hierarchically. This allows you to understand the internals of your LLM Application and to troubleshoot the complex components of your applicaition. Phoenix is built on top of the OpenInference tracing standard and uses it to trace, export, and collect critical information about your LLM Application in the form ofspans. For more details on the OpenInference tracing standard, see theOpenInference SpecificationTracing with LlamaIndexTo extract traces from your LlamaIndex application, you will have to add Phoenix'sOpenInferenceTraceCallbackto your LlamaIndex application. A callback (in this case an OpenInferenceTracer) is a class that automatically accumulatesspansthat trac your application as it executes. The OpenInferenceTraceris a tracer that is specifically designed to work with Phoenix and by default exports the traces to a locally running phoenix server.# Install phoenix as well as llama_index and your LLM of choicepipinstallarize-phoenixllama-indexopenaiLaunch Phoenix in a notebook and view the traces of your LlamaIndex application in the Phoenix UI.importphoenixaspx# To view traces in Phoenix, you will first have to start a Phoenix server. You can do this by running the following:session=px.launch_app()# Once you have started a Phoenix server, you can start your LlamaIndex application with the `OpenInferenceTraceCallback` as a callback. To do this, you will have to add the callback to the initialization of your LlamaIndex application:fromphoenix.trace.llama_indeximport(OpenInferenceTraceCallbackHandler,)# Initialize the callback handlercallback_handler=OpenInferenceTraceCallbackHandler()# LlamaIndex application initialization may vary# depending on your applicationservice_context=ServiceContext.from_defaults(llm_predictor=LLMPredictor(llm=ChatOpenAI(model_name="gpt-3.5-turbo",temperature=0)),embed_model=OpenAIEmbedding(model="text-embedding-ada-002"),callback_manager=CallbackManager(handlers=[callback_handler]),)index=load_index_from_storage(storage_context,service_context=service_context,)query_engine=index.as_query_engine()# Query your LlamaIndex applicationquery_engine.query("What is the meaning of life?")query_engine.query("Why did the cow jump over the moon?")# View the traces in the Phoenix UIpx.active_session().urlTracing with LangChainTo extract traces from your LangChain application, you will have to add Phoenix's OpenInference Tracer to your LangChain application. A tracer is a class that automatically accumulates traces as your application executes. The OpenInference Tracer is a tracer that is specifically designed to work with Phoenix and by default exports the traces to a locally running phoenix server.# Install phoenix as well as langchain and your LLM of choicepipinstallarize-phoenixlangchainopenaiLaunch Phoenix in a notebook and view the traces of your LangChain application in the Phoenix UI.importphoenixaspximportpandasaspdimportnumpyasnp# Launch phoenixsession=px.launch_app()# Once you have started a Phoenix server, you can start your LangChain application with the OpenInferenceTracer as a callback. To do this, you will have to instrument your LangChain application with the tracer:fromphoenix.trace.langchainimportOpenInferenceTracer,LangChainInstrumentor# By default, the traces will be exported to the locally running Phoenix server.LangChainInstrumentor().instrument()# Initialize your LangChain applicationfromlangchain.chainsimportRetrievalQAfromlangchain.chat_modelsimportChatOpenAIfromlangchain.embeddingsimportOpenAIEmbeddingsfromlangchain.retrieversimportKNNRetrieverembeddings=OpenAIEmbeddings(model="text-embedding-ada-002")documents_df=pd.read_parquet("http://storage.googleapis.com/arize-assets/phoenix/datasets/unstructured/llm/context-retrieval/langchain-pinecone/database.parquet")knn_retriever=KNNRetriever(index=np.stack(documents_df["text_vector"]),texts=documents_df["text"].tolist(),embeddings=OpenAIEmbeddings(),)chain_type="stuff"# stuff, refine, map_reduce, and map_rerankchat_model_name="gpt-3.5-turbo"llm=ChatOpenAI(model_name=chat_model_name)chain=RetrievalQA.from_chain_type(llm=llm,chain_type=chain_type,retriever=knn_retriever,)# Instrument the execution of the runs with the tracer. By default the tracer uses an HTTPExporterquery="What is euclidean distance?"response=chain.run(query,callbacks=[tracer])# By adding the tracer to the callbacks of LangChain, we've created a one-way data connection between your LLM application and Phoenix.# To view the traces in Phoenix, simply open the UI in your browser.session.urlLLM Evals🚧 LLM Evals is still under construction under a sub-modulearize-phoenix[experimental]Phoenix provides tooling to evaluate LLM applications, including tools to determine the relevance or irrelevance of documents retrieved by retrieval-augmented generation (RAG) application, whether or not the response is toxic, and much more.Phoenix's approach to LLM evals is notable for the following reasons:Includes pre-tested templates and convenience functions for a set of common Eval “tasks”Data science rigor applied to the testing of model and template combinationsDesigned to run as fast as possible on batches of dataIncludes benchmark datasets and tests for each eval functionHere is an example of running the RAG relevance eval on a dataset of Wikipedia questions and answers:# Install phoenix as well as the experimental subpackagepipinstallarize-phoenix[experimental]ipythonmatplotlibopenaipycmscikit-learnfromphoenix.experimental.evalsimport(RAG_RELEVANCY_PROMPT_TEMPLATE,RAG_RELEVANCY_PROMPT_RAILS_MAP,OpenAIModel,download_benchmark_dataset,llm_classify,)fromsklearn.metricsimportprecision_recall_fscore_support,confusion_matrix,ConfusionMatrixDisplay# Download the benchmark golden datasetdf=download_benchmark_dataset(task="binary-relevance-classification",dataset_name="wiki_qa-train")# Sample and re-name the columns to match the templatedf=df.sample(100)df=df.rename(columns={"query_text":"input","document_text":"reference",},)model=OpenAIModel(model="gpt-4",temperature=0.0,)rails=list(RAG_RELEVANCY_PROMPT_RAILS_MAP.values())df[["eval_relevance"]]=llm_classify(df,model,RAG_RELEVANCY_PROMPT_TEMPLATE,rails)#Golden dataset has True/False map to -> "irrelevant" / "relevant"#we can then scikit compare to output of template - same formaty_true=df["relevant"].map({True:"relevant",False:"irrelevant"})y_pred=df["eval_relevance"]# Compute Per-Class Precision, Recall, F1 Score, Supportprecision,recall,f1,support=precision_recall_fscore_support(y_true,y_pred)To learn more about LLM Evals, see theLLM Evals documentation.Embedding AnalysisExplore UMAP point-clouds at times of high drift and performance degredation and identify clusters of problematic data.Embedding analysis is critical for understanding the behavior of you NLP, CV, and LLM Apps that use embeddings. Phoenix provides an A/B testing framework to help you understand how your embeddings are changing over time and how they are changing between different versions of your model (prodvstrain,championvschallenger).# Import libraries.fromdataclassesimportreplaceimportpandasaspdimportphoenixaspx# Download curated datasets and load them into pandas DataFrames.train_df=pd.read_parquet("https://storage.googleapis.com/arize-assets/phoenix/datasets/unstructured/cv/human-actions/human_actions_training.parquet")prod_df=pd.read_parquet("https://storage.googleapis.com/arize-assets/phoenix/datasets/unstructured/cv/human-actions/human_actions_production.parquet")# Define schemas that tell Phoenix which columns of your DataFrames correspond to features, predictions, actuals (i.e., ground truth), embeddings, etc.train_schema=px.Schema(prediction_id_column_name="prediction_id",timestamp_column_name="prediction_ts",prediction_label_column_name="predicted_action",actual_label_column_name="actual_action",embedding_feature_column_names={"image_embedding":px.EmbeddingColumnNames(vector_column_name="image_vector",link_to_data_column_name="url",),},)prod_schema=replace(train_schema,actual_label_column_name=None)# Define your production and training datasets.prod_ds=px.Dataset(prod_df,prod_schema)train_ds=px.Dataset(train_df,train_schema)# Launch Phoenix.session=px.launch_app(prod_ds,train_ds)# View the Phoenix UI in the browsersession.urlUMAP-based Exploratory Data AnalysisColor your UMAP point-clouds by your model's dimensions, drift, and performance to identify problematic cohorts.Cluster-driven Drift and Performance AnalysisBreak-apart your data into clusters of high drift or bad performance using HDBSCANExportable ClustersExport your clusters toparquetfiles or dataframes for further analysis and fine-tuning.Retrieval-Augmented Generation AnalysisSearch and retrieval is a critical component of many LLM Applications as it allows you to extend the LLM's capabilities to encompass knowledge about private data. This process is known as RAG (retrieval-augmented generation) and often times a vector store is leveraged to store chunks of documents encoded as embeddings so that they can be retrieved at inference time.To help you better understand your RAG application, Phoenix allows you to upload a corpus of your knowledge base along with your LLM application's inferences to help you troubleshoot hard to find bugs with retrieval.Structured Data AnalysisPhoenix provides a suite of tools for analyzing structured data. These tools allow you to perform A/B analysis, temporal drift analysis, and more.importpandasaspdimportphoenixaspx# Perform A/B analysis on your training and production datasetstrain_df=pd.read_parquet("http://storage.googleapis.com/arize-assets/phoenix/datasets/structured/credit-card-fraud/credit_card_fraud_train.parquet",)prod_df=pd.read_parquet("http://storage.googleapis.com/arize-assets/phoenix/datasets/structured/credit-card-fraud/credit_card_fraud_production.parquet",)# Describe the data for analysisschema=px.Schema(prediction_id_column_name="prediction_id",prediction_label_column_name="predicted_label",prediction_score_column_name="predicted_score",actual_label_column_name="actual_label",timestamp_column_name="prediction_timestamp",feature_column_names=feature_column_names,tag_column_names=["age"],)# Define your production and training datasets.prod_ds=px.Dataset(dataframe=prod_df,schema=schema,name="production")train_ds=px.Dataset(dataframe=train_df,schema=schema,name="training")# Launch Phoenix for analysissession=px.launch_app(primary=prod_ds,reference=train_ds)Deploying PhoenixPhoenix's notebook-first approach to observability makes it a great tool to utilize during experimentation and pre-production. However at some point you are going to want to ship your application to production and continue to monitor your application as it runs. Phoenix is made up of two components that can be deployed independently:Trace Instrumentation: These are a set of plugins that can be added to your application's startup process. These plugins (known as instrumentations) automatically collect spans for your application and export them for collection and visualization. For phoenix, all the instrumentors are managed via a single repository calledOpenInferenceTrace Collector: The Phoenix server acts as a trace collector and application that helps you troubleshoot your application in real time. You can pull the latest images of Phoenix from theDocker HubIn order to run Phoenix tracing in production, you will have to follow these following steps:Setup a Server: your LLM application to run on a server (examples)Instrument: AddOpenInferenceInstrumentation to your serverObserve: Run the Phoenix server as a side-car or a standalone instance and point your tracing instrumentation to the phoenix serverFor more information on deploying Phoenix, see thePhoenix Deployment Guide.Breaking Changessee themigration guidefor a list of breaking changes.CommunityJoin our community to connect with thousands of machine learning practitioners and ML observability enthusiasts.🌍 Join ourSlack community.💡 Ask questions and provide feedback in the#phoenix-supportchannel.🌟 Leave a star on ourGitHub.🐞 Report bugs withGitHub Issues.🐣 Follow us ontwitter.💌️ Sign up for ourmailing list.🗺️ Check out ourroadmapto see where we're heading next.🎓 Learn the fundamentals of ML observability with ourintroductoryandadvancedcourses.ThanksUMAPFor unlocking the ability to visualize and reason about embeddingsHDBSCANFor providing a clustering algorithm to aid in the discovery of drift and performance degradationCopyright, Patent, and LicenseCopyright 2023 Arize AI, Inc. All Rights Reserved.Portions of this code are patent protected by one or more U.S. Patents. SeeIP_NOTICE.This software is licensed under the terms of the Elastic License 2.0 (ELv2). SeeLICENSE.