diff --git a/.github/workflows/combine_nb_to_docs_testing.sh b/.github/workflows/combine_nb_to_docs_testing.sh index 58f0df4fc..5b8873932 100755 --- a/.github/workflows/combine_nb_to_docs_testing.sh +++ b/.github/workflows/combine_nb_to_docs_testing.sh @@ -7,6 +7,12 @@ rm -rf alltools.ipynb # IF MOVING ANY IPYNB, MAKE SURE TO RE-SYMLINK. MANY IPYNB REFERENCED HERE LIVE IN OTHER PATHS nbmerge langchain_quickstart.ipynb logging.ipynb custom_feedback_functions.ipynb >> all_tools.ipynb +# Colab quickstarts +# IF MOVING ANY IPYNB, MAKE SURE TO RE-SYMLINK. MANY IPYNB REFERENCED HERE LIVE IN OTHER PATHS +nbmerge colab_dependencies.ipynb langchain_quickstart.ipynb >> langchain_quickstart_colab.ipynb +nbmerge colab_dependencies.ipynb llama_index_quickstart.ipynb >> llama_index_quickstart_colab.ipynb +nbmerge colab_dependencies.ipynb text2text_quickstart.ipynb >> text2text_quickstart_colab.ipynb + # Create pypi page documentation cat intro.md > README.md @@ -26,18 +32,18 @@ jupyter nbconvert --to script --output-dir=./py_script_quickstarts/ all_tools.ip SED=`which -a gsed sed | head -n1` # Fix nbmerge ids field invalid for ipynb -$SED -i '' "/id\"\:/d" all_tools.ipynb langchain_quickstart_colab.ipynb llama_index_quickstart_colab.ipynb text2text_quickstart_colab.ipynb +$SED -i "/id\"\:/d" all_tools.ipynb langchain_quickstart_colab.ipynb llama_index_quickstart_colab.ipynb text2text_quickstart_colab.ipynb ## Remove ipynb JSON calls -$SED -i '' "/JSON/d" ./py_script_quickstarts/langchain_quickstart.py ./py_script_quickstarts/llama_index_quickstart.py ./py_script_quickstarts/text2text_quickstart.py ./py_script_quickstarts/all_tools.py +$SED -i "/JSON/d" ./py_script_quickstarts/langchain_quickstart.py ./py_script_quickstarts/llama_index_quickstart.py ./py_script_quickstarts/text2text_quickstart.py ./py_script_quickstarts/all_tools.py ## Replace jupyter display with python print -$SED -i '' "s/display/print/g" ./py_script_quickstarts/langchain_quickstart.py ./py_script_quickstarts/llama_index_quickstart.py ./py_script_quickstarts/text2text_quickstart.py ./py_script_quickstarts/all_tools.py +$SED -i "s/display/print/g" ./py_script_quickstarts/langchain_quickstart.py ./py_script_quickstarts/llama_index_quickstart.py ./py_script_quickstarts/text2text_quickstart.py ./py_script_quickstarts/all_tools.py ## Remove cell metadata -$SED -i '' "/\# In\[/d" ./py_script_quickstarts/langchain_quickstart.py ./py_script_quickstarts/llama_index_quickstart.py ./py_script_quickstarts/text2text_quickstart.py ./py_script_quickstarts/all_tools.py +$SED -i "/\# In\[/d" ./py_script_quickstarts/langchain_quickstart.py ./py_script_quickstarts/llama_index_quickstart.py ./py_script_quickstarts/text2text_quickstart.py ./py_script_quickstarts/all_tools.py ## Remove single # lines -$SED -i '' "/\#$/d" ./py_script_quickstarts/langchain_quickstart.py ./py_script_quickstarts/llama_index_quickstart.py ./py_script_quickstarts/text2text_quickstart.py ./py_script_quickstarts/all_tools.py +$SED -i "/\#$/d" ./py_script_quickstarts/langchain_quickstart.py ./py_script_quickstarts/llama_index_quickstart.py ./py_script_quickstarts/text2text_quickstart.py ./py_script_quickstarts/all_tools.py ## Collapse multiple empty line from sed replacements with a single line -$SED -i '' -e "/./b" -e ":n" -e "N;s/\\n$//;tn" ./py_script_quickstarts/langchain_quickstart.py ./py_script_quickstarts/llama_index_quickstart.py ./py_script_quickstarts/text2text_quickstart.py ./py_script_quickstarts/all_tools.py +$SED -i -e "/./b" -e ":n" -e "N;s/\\n$//;tn" ./py_script_quickstarts/langchain_quickstart.py ./py_script_quickstarts/llama_index_quickstart.py ./py_script_quickstarts/text2text_quickstart.py ./py_script_quickstarts/all_tools.py # Move generated files to their end locations # EVERYTHING BELOW IS LINKED TO DOCUMENTATION OR TESTS; MAKE SURE YOU UPDATE LINKS IF YOU CHANGE # IF NAMES CHANGED; CHANGE THE LINK NAMES TOO @@ -49,7 +55,7 @@ mv TOP_README.md ../../README.md # Links are referenced in intro.md and gh_intro.md # There are symlinks from ../../trulens_eval/generated_files/ to these scripts for testing mkdir -p ../../trulens_eval/examples/quickstart/py_script_quickstarts/ -mv *.py ../../trulens_eval/examples/quickstart/py_script_quickstarts/ +mv ./py_script_quickstarts/*.py ../../trulens_eval/examples/quickstart/py_script_quickstarts/ # Trulens tests run off of these files -mv all_tools* ../../trulens_eval/generated_files/ \ No newline at end of file +mv all_tools* ../../trulens_eval/generated_files/ diff --git a/README.md b/README.md index 6144e8e9f..8396907b6 100644 --- a/README.md +++ b/README.md @@ -43,24 +43,24 @@ TruLens supports the evaluation of tracking for any LLM app framework. Choose a **Langchain** -[langchain_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/langchain_quickstart.ipynb). -[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/colab/quickstarts/langchain_quickstart_colab.ipynb) +[langchain_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/langchain_quickstart.ipynb). +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/colab/quickstarts/langchain_quickstart_colab.ipynb) -[langchain_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/py_script_quickstarts/langchain_quickstart.py). +[langchain_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/py_script_quickstarts/langchain_quickstart.py). **Llama-Index** -[llama_index_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/llama_index_quickstart.ipynb). -[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/colab/quickstarts/llama_index_quickstart_colab.ipynb) +[llama_index_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/llama_index_quickstart.ipynb). +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/colab/quickstarts/llama_index_quickstart_colab.ipynb) -[llama_index_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/py_script_quickstarts/llama_index_quickstart.py) +[llama_index_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/py_script_quickstarts/llama_index_quickstart.py) **No Framework** -[text2text_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/text2text_quickstart.ipynb). -[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/colab/quickstarts/text2text_quickstart_colab.ipynb) +[text2text_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/text2text_quickstart.ipynb). +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/colab/quickstarts/text2text_quickstart_colab.ipynb) -[text2text_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/py_script_quickstarts/text2text_quickstart.py) +[text2text_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/py_script_quickstarts/text2text_quickstart.py) ## TruLens-Explain diff --git a/docs/trulens_eval/py_script_quickstarts/all_tools.py b/docs/trulens_eval/py_script_quickstarts/all_tools.py deleted file mode 100644 index 3c01eb730..000000000 --- a/docs/trulens_eval/py_script_quickstarts/all_tools.py +++ /dev/null @@ -1,359 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -# # Langchain Quickstart -# -# In this quickstart you will create a simple LLM Chain and learn how to log it and get feedback on an LLM response. -# -# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/quickstart/langchain_quickstart.ipynb) - -# ## Setup -# ### Add API keys -# For this quickstart you will need Open AI and Huggingface keys - -# In[ ]: - -import os - -os.environ["OPENAI_API_KEY"] = "..." -os.environ["HUGGINGFACE_API_KEY"] = "..." - -# ### Import from LangChain and TruLens - -# In[ ]: - -from IPython.display import JSON - -# Imports main tools: -from trulens_eval import Feedback -from trulens_eval import Huggingface -from trulens_eval import Tru -from trulens_eval import TruChain - -tru = Tru() - -# Imports from langchain to build app. You may need to install langchain first -# with the following: -# ! pip install langchain>=0.0.170 -from langchain.chains import LLMChain -from langchain.llms import OpenAI -from langchain.prompts.chat import ChatPromptTemplate -from langchain.prompts.chat import HumanMessagePromptTemplate -from langchain.prompts.chat import PromptTemplate - -# ### Create Simple LLM Application -# -# This example uses a LangChain framework and OpenAI LLM - -# In[ ]: - -full_prompt = HumanMessagePromptTemplate( - prompt=PromptTemplate( - template= - "Provide a helpful response with relevant background information for the following: {prompt}", - input_variables=["prompt"], - ) -) - -chat_prompt_template = ChatPromptTemplate.from_messages([full_prompt]) - -llm = OpenAI(temperature=0.9, max_tokens=128) - -chain = LLMChain(llm=llm, prompt=chat_prompt_template, verbose=True) - -# ### Send your first request - -# In[ ]: - -prompt_input = '¿que hora es?' - -# In[ ]: - -llm_response = chain(prompt_input) - -display(llm_response) - -# ## Initialize Feedback Function(s) - -# In[ ]: - -# Initialize Huggingface-based feedback function collection class: -hugs = Huggingface() - -# Define a language match feedback function using HuggingFace. -f_lang_match = Feedback(hugs.language_match).on_input_output() -# By default this will check language match on the main app input and main app -# output. - -# ## Instrument chain for logging with TruLens - -# In[ ]: - -tru_recorder = TruChain( - chain, app_id='Chain1_ChatApplication', feedbacks=[f_lang_match] -) - -# In[ ]: - -with tru_recorder as recording: - llm_response = chain(prompt_input) - -display(llm_response) - -# ## Explore in a Dashboard - -# In[ ]: - -tru.run_dashboard() # open a local streamlit app to explore - -# tru.stop_dashboard() # stop if needed - -# Alternatively, you can run `trulens-eval` from a command line in the same folder to start the dashboard. - -# ### Chain Leaderboard -# -# Understand how your LLM application is performing at a glance. Once you've set up logging and evaluation in your application, you can view key performance statistics including cost and average feedback value across all of your LLM apps using the chain leaderboard. As you iterate new versions of your LLM application, you can compare their performance across all of the different quality metrics you've set up. -# -# Note: Average feedback values are returned and displayed in a range from 0 (worst) to 1 (best). -# -# ![Chain Leaderboard](https://www.trulens.org/Assets/image/Leaderboard.png) -# -# To dive deeper on a particular chain, click "Select Chain". -# -# ### Understand chain performance with Evaluations -# -# To learn more about the performance of a particular chain or LLM model, we can select it to view its evaluations at the record level. LLM quality is assessed through the use of feedback functions. Feedback functions are extensible methods for determining the quality of LLM responses and can be applied to any downstream LLM task. Out of the box we provide a number of feedback functions for assessing model agreement, sentiment, relevance and more. -# -# The evaluations tab provides record-level metadata and feedback on the quality of your LLM application. -# -# ![Evaluations](https://www.trulens.org/Assets/image/Leaderboard.png) -# -# ### Deep dive into full chain metadata -# -# Click on a record to dive deep into all of the details of your chain stack and underlying LLM, captured by tru_chain_recorder. -# -# ![Explore a Chain](https://www.trulens.org/Assets/image/Chain_Explore.png) -# -# If you prefer the raw format, you can quickly get it using the "Display full chain json" or "Display full record json" buttons at the bottom of the page. - -# Note: Feedback functions evaluated in the deferred manner can be seen in the "Progress" page of the TruLens dashboard. - -# ## Or view results directly in your notebook - -# In[ ]: - -tru.get_records_and_feedback(app_ids=[] - )[0] # pass an empty list of app_ids to get all - -# # Logging Methods -# -# ## Automatic Logging -# -# The simplest method for logging with TruLens is by wrapping with TruChain and including the tru argument, as shown in the quickstart. -# -# This is done like so: - -# In[ ]: - -truchain = TruChain(chain, app_id='Chain1_ChatApplication', tru=tru) -truchain("This will be automatically logged.") - -# Feedback functions can also be logged automatically by providing them in a list to the feedbacks arg. - -# In[ ]: - -truchain = TruChain( - chain, - app_id='Chain1_ChatApplication', - feedbacks=[f_lang_match], # feedback functions - tru=tru -) -truchain("This will be automatically logged.") - -# ## Manual Logging -# -# ### Wrap with TruChain to instrument your chain - -# In[ ]: - -tc = TruChain(chain, app_id='Chain1_ChatApplication') - -# ### Set up logging and instrumentation -# -# Making the first call to your wrapped LLM Application will now also produce a log or "record" of the chain execution. -# - -# In[ ]: - -prompt_input = 'que hora es?' -gpt3_response, record = tc.call_with_record(prompt_input) - -# We can log the records but first we need to log the chain itself. - -# In[ ]: - -tru.add_app(app=truchain) - -# Then we can log the record: - -# In[ ]: - -tru.add_record(record) - -# ### Log App Feedback -# Capturing app feedback such as user feedback of the responses can be added with one call. - -# In[ ]: - -thumb_result = True -tru.add_feedback( - name="👍 (1) or 👎 (0)", record_id=record.record_id, result=thumb_result -) - -# ### Evaluate Quality -# -# Following the request to your app, you can then evaluate LLM quality using feedback functions. This is completed in a sequential call to minimize latency for your application, and evaluations will also be logged to your local machine. -# -# To get feedback on the quality of your LLM, you can use any of the provided feedback functions or add your own. -# -# To assess your LLM quality, you can provide the feedback functions to `tru.run_feedback()` in a list provided to `feedback_functions`. -# - -# In[ ]: - -feedback_results = tru.run_feedback_functions( - record=record, feedback_functions=[f_lang_match] -) -display(feedback_results) - -# After capturing feedback, you can then log it to your local database. - -# In[ ]: - -tru.add_feedbacks(feedback_results) - -# ### Out-of-band Feedback evaluation -# -# In the above example, the feedback function evaluation is done in the same process as the chain evaluation. The alternative approach is the use the provided persistent evaluator started via `tru.start_deferred_feedback_evaluator`. Then specify the `feedback_mode` for `TruChain` as `deferred` to let the evaluator handle the feedback functions. -# -# For demonstration purposes, we start the evaluator here but it can be started in another process. - -# In[ ]: - -truchain: TruChain = TruChain( - chain, - app_id='Chain1_ChatApplication', - feedbacks=[f_lang_match], - tru=tru, - feedback_mode="deferred" -) - -tru.start_evaluator() -truchain("This will be logged by deferred evaluator.") -tru.stop_evaluator() - -# # Custom Functions -# -# Feedback functions are an extensible framework for evaluating LLMs. You can add your own feedback functions to evaluate the qualities required by your application by updating `trulens_eval/feedback.py`, or simply creating a new provider class and feedback function in youre notebook. If your contributions would be useful for others, we encourage you to contribute to TruLens! -# -# Feedback functions are organized by model provider into Provider classes. -# -# The process for adding new feedback functions is: -# 1. Create a new Provider class or locate an existing one that applies to your feedback function. If your feedback function does not rely on a model provider, you can create a standalone class. Add the new feedback function method to your selected class. Your new method can either take a single text (str) as a parameter or both prompt (str) and response (str). It should return a float between 0 (worst) and 1 (best). - -# In[ ]: - -from trulens_eval import Feedback -from trulens_eval import Provider -from trulens_eval import Select -from trulens_eval import Tru - - -class StandAlone(Provider): - - def custom_feedback(self, my_text_field: str) -> float: - """ - A dummy function of text inputs to float outputs. - - Parameters: - my_text_field (str): Text to evaluate. - - Returns: - float: square length of the text - """ - return 1.0 / (1.0 + len(my_text_field) * len(my_text_field)) - - -# 2. Instantiate your provider and feedback functions. The feedback function is wrapped by the trulens-eval Feedback class which helps specify what will get sent to your function parameters (For example: Select.RecordInput or Select.RecordOutput) - -# In[ ]: - -standalone = StandAlone() -f_custom_function = Feedback(standalone.custom_feedback - ).on(my_text_field=Select.RecordOutput) - -# 3. Your feedback function is now ready to use just like the out of the box feedback functions. Below is an example of it being used. - -# In[ ]: - -tru = Tru() -feedback_results = tru.run_feedback_functions( - record=record, feedback_functions=[f_custom_function] -) -tru.add_feedbacks(feedback_results) - -# ## Multi-Output Feedback functions -# Trulens also supports multi-output feedback functions. As a typical feedback function will output a float between 0 and 1, multi-output should output a dictionary of `output_key` to a float between 0 and 1. The feedbacks table will display the feedback with column `feedback_name:::outputkey` - -# In[ ]: - -multi_output_feedback = Feedback( - lambda input_param: { - 'output_key1': 0.1, - 'output_key2': 0.9 - }, name="multi" -).on(input_param=Select.RecordOutput) -feedback_results = tru.run_feedback_functions( - record=record, feedback_functions=[multi_output_feedback] -) -tru.add_feedbacks(feedback_results) - -# In[ ]: - -# Aggregators will run on the same dict keys. -import numpy as np - -multi_output_feedback = Feedback( - lambda input_param: { - 'output_key1': 0.1, - 'output_key2': 0.9 - }, - name="multi-agg" -).on(input_param=Select.RecordOutput).aggregate(np.mean) -feedback_results = tru.run_feedback_functions( - record=record, feedback_functions=[multi_output_feedback] -) -tru.add_feedbacks(feedback_results) - -# In[ ]: - - -# For multi-context chunking, an aggregator can operate on a list of multi output dictionaries. -def dict_aggregator(list_dict_input): - agg = 0 - for dict_input in list_dict_input: - agg += dict_input['output_key1'] - return agg - - -multi_output_feedback = Feedback( - lambda input_param: { - 'output_key1': 0.1, - 'output_key2': 0.9 - }, - name="multi-agg-dict" -).on(input_param=Select.RecordOutput).aggregate(dict_aggregator) -feedback_results = tru.run_feedback_functions( - record=record, feedback_functions=[multi_output_feedback] -) -tru.add_feedbacks(feedback_results) diff --git a/docs/trulens_eval/py_script_quickstarts/langchain_quickstart.py b/docs/trulens_eval/py_script_quickstarts/langchain_quickstart.py deleted file mode 100644 index bcbb8e95f..000000000 --- a/docs/trulens_eval/py_script_quickstarts/langchain_quickstart.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -# # Langchain Quickstart -# -# In this quickstart you will create a simple LLM Chain and learn how to log it and get feedback on an LLM response. -# -# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/quickstart/langchain_quickstart.ipynb) - -# ## Setup -# ### Add API keys -# For this quickstart you will need Open AI and Huggingface keys - -# In[ ]: - -import os - -os.environ["OPENAI_API_KEY"] = "..." -os.environ["HUGGINGFACE_API_KEY"] = "..." - -# ### Import from LangChain and TruLens - -# In[ ]: - -from IPython.display import JSON - -# Imports main tools: -from trulens_eval import Feedback -from trulens_eval import Huggingface -from trulens_eval import Tru -from trulens_eval import TruChain - -tru = Tru() - -# Imports from langchain to build app. You may need to install langchain first -# with the following: -# ! pip install langchain>=0.0.170 -from langchain.chains import LLMChain -from langchain.llms import OpenAI -from langchain.prompts.chat import ChatPromptTemplate -from langchain.prompts.chat import HumanMessagePromptTemplate -from langchain.prompts.chat import PromptTemplate - -# ### Create Simple LLM Application -# -# This example uses a LangChain framework and OpenAI LLM - -# In[ ]: - -full_prompt = HumanMessagePromptTemplate( - prompt=PromptTemplate( - template= - "Provide a helpful response with relevant background information for the following: {prompt}", - input_variables=["prompt"], - ) -) - -chat_prompt_template = ChatPromptTemplate.from_messages([full_prompt]) - -llm = OpenAI(temperature=0.9, max_tokens=128) - -chain = LLMChain(llm=llm, prompt=chat_prompt_template, verbose=True) - -# ### Send your first request - -# In[ ]: - -prompt_input = '¿que hora es?' - -# In[ ]: - -llm_response = chain(prompt_input) - -display(llm_response) - -# ## Initialize Feedback Function(s) - -# In[ ]: - -# Initialize Huggingface-based feedback function collection class: -hugs = Huggingface() - -# Define a language match feedback function using HuggingFace. -f_lang_match = Feedback(hugs.language_match).on_input_output() -# By default this will check language match on the main app input and main app -# output. - -# ## Instrument chain for logging with TruLens - -# In[ ]: - -tru_recorder = TruChain( - chain, app_id='Chain1_ChatApplication', feedbacks=[f_lang_match] -) - -# In[ ]: - -with tru_recorder as recording: - llm_response = chain(prompt_input) - -display(llm_response) - -# ## Explore in a Dashboard - -# In[ ]: - -tru.run_dashboard() # open a local streamlit app to explore - -# tru.stop_dashboard() # stop if needed - -# Alternatively, you can run `trulens-eval` from a command line in the same folder to start the dashboard. - -# ### Chain Leaderboard -# -# Understand how your LLM application is performing at a glance. Once you've set up logging and evaluation in your application, you can view key performance statistics including cost and average feedback value across all of your LLM apps using the chain leaderboard. As you iterate new versions of your LLM application, you can compare their performance across all of the different quality metrics you've set up. -# -# Note: Average feedback values are returned and displayed in a range from 0 (worst) to 1 (best). -# -# ![Chain Leaderboard](https://www.trulens.org/Assets/image/Leaderboard.png) -# -# To dive deeper on a particular chain, click "Select Chain". -# -# ### Understand chain performance with Evaluations -# -# To learn more about the performance of a particular chain or LLM model, we can select it to view its evaluations at the record level. LLM quality is assessed through the use of feedback functions. Feedback functions are extensible methods for determining the quality of LLM responses and can be applied to any downstream LLM task. Out of the box we provide a number of feedback functions for assessing model agreement, sentiment, relevance and more. -# -# The evaluations tab provides record-level metadata and feedback on the quality of your LLM application. -# -# ![Evaluations](https://www.trulens.org/Assets/image/Leaderboard.png) -# -# ### Deep dive into full chain metadata -# -# Click on a record to dive deep into all of the details of your chain stack and underlying LLM, captured by tru_chain_recorder. -# -# ![Explore a Chain](https://www.trulens.org/Assets/image/Chain_Explore.png) -# -# If you prefer the raw format, you can quickly get it using the "Display full chain json" or "Display full record json" buttons at the bottom of the page. - -# Note: Feedback functions evaluated in the deferred manner can be seen in the "Progress" page of the TruLens dashboard. - -# ## Or view results directly in your notebook - -# In[ ]: - -tru.get_records_and_feedback(app_ids=[] - )[0] # pass an empty list of app_ids to get all diff --git a/docs/trulens_eval/py_script_quickstarts/llama_index_quickstart.py b/docs/trulens_eval/py_script_quickstarts/llama_index_quickstart.py deleted file mode 100644 index fd9f9a3aa..000000000 --- a/docs/trulens_eval/py_script_quickstarts/llama_index_quickstart.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -# # Llama-Index Quickstart -# -# In this quickstart you will create a simple Llama Index App and learn how to log it and get feedback on an LLM response. -# -# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/quickstart/llama_index_quickstart.ipynb) - -# ## Setup -# -# ### Install dependencies -# Let's install some of the dependencies for this notebook if we don't have them already - -# In[ ]: - -#! pip install trulens-eval==0.13.0 llama_index>=0.8.29post1 html2text>=2020.1.16 - -# ### Add API keys -# For this quickstart, you will need Open AI and Huggingface keys. The OpenAI key is used for embeddings and GPT, and the Huggingface key is used for evaluation. - -# In[ ]: - -import os - -os.environ["OPENAI_API_KEY"] = "..." -os.environ["HUGGINGFACE_API_KEY"] = "..." - -# ### Import from LlamaIndex and TruLens - -# In[ ]: - -# Imports main tools: -from trulens_eval import Feedback -from trulens_eval import feedback -from trulens_eval import Tru -from trulens_eval import TruLlama - -tru = Tru() - -# ### Create Simple LLM Application -# -# This example uses LlamaIndex which internally uses an OpenAI LLM. - -# In[ ]: - -from llama_index import SimpleWebPageReader -from llama_index import VectorStoreIndex - -documents = SimpleWebPageReader(html_to_text=True).load_data( - ["http://paulgraham.com/worked.html"] -) -index = VectorStoreIndex.from_documents(documents) - -query_engine = index.as_query_engine() - -# ### Send your first request - -# In[ ]: - -response = query_engine.query("What did the author do growing up?") -print(response) - -# ## Initialize Feedback Function(s) - -# In[ ]: - -import numpy as np - -# Initialize Huggingface-based feedback function collection class: -hugs = feedback.Huggingface() -openai = feedback.OpenAI() - -# Define a language match feedback function using HuggingFace. -f_lang_match = Feedback(hugs.language_match).on_input_output() -# By default this will check language match on the main app input and main app -# output. - -# Question/answer relevance between overall question and answer. -f_qa_relevance = Feedback(openai.relevance).on_input_output() - -# Question/statement relevance between question and each context chunk. -f_qs_relevance = Feedback(openai.qs_relevance).on_input().on( - TruLlama.select_source_nodes().node.text -).aggregate(np.mean) - -# ## Instrument app for logging with TruLens - -# In[ ]: - -tru_query_engine_recorder = TruLlama( - query_engine, - app_id='LlamaIndex_App1', - feedbacks=[f_lang_match, f_qa_relevance, f_qs_relevance] -) - -# In[ ]: - -# or as context manager -with tru_query_engine_recorder as recording: - query_engine.query("What did the author do growing up?") - -# ## Explore in a Dashboard - -# In[ ]: - -tru.run_dashboard() # open a local streamlit app to explore - -# tru.stop_dashboard() # stop if needed - -# Alternatively, you can run `trulens-eval` from a command line in the same folder to start the dashboard. - -# ### Leaderboard -# -# Understand how your LLM application is performing at a glance. Once you've set up logging and evaluation in your application, you can view key performance statistics including cost and average feedback value across all of your LLM apps using the app leaderboard. As you iterate new versions of your LLM application, you can compare their performance across all of the different quality metrics you've set up. -# -# Note: Average feedback values are returned and displayed in a range from 0 (worst) to 1 (best). -# -# ![App Leaderboard](https://www.trulens.org/Assets/image/Leaderboard.png) -# -# To dive deeper on a particular app, click "Select App". -# -# ### Understand app performance with Evaluations -# -# To learn more about the performance of a particular app or LLM model, we can select it to view its evaluations at the record level. LLM quality is assessed through the use of feedback functions. Feedback functions are extensible methods for determining the quality of LLM responses and can be applied to any downstream LLM task. Out of the box we provide a number of feedback functions for assessing model agreement, sentiment, relevance and more. -# -# The evaluations tab provides record-level metadata and feedback on the quality of your LLM application. -# -# ![Evaluations](https://www.trulens.org/Assets/image/Leaderboard.png) -# -# ### Deep dive into full app metadata -# -# Click on a record to dive deep into all of the details of your app stack and underlying LLM, captured by tru_query_engine_recorder. -# -# ![Explore an App](https://www.trulens.org/Assets/image/Chain_Explore.png) -# -# If you prefer the raw format, you can quickly get it using the "Display full app json" or "Display full record json" buttons at the bottom of the page. - -# Note: Feedback functions evaluated in the deferred manner can be seen in the "Progress" page of the TruLens dashboard. - -# ## Or view results directly in your notebook - -# In[ ]: - -tru.get_records_and_feedback(app_ids=[] - )[0] # pass an empty list of app_ids to get all diff --git a/docs/trulens_eval/py_script_quickstarts/text2text_quickstart.py b/docs/trulens_eval/py_script_quickstarts/text2text_quickstart.py deleted file mode 100644 index 0809f9392..000000000 --- a/docs/trulens_eval/py_script_quickstarts/text2text_quickstart.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -# # Text to Text Quickstart -# -# In this quickstart you will create a simple text to text application and learn how to log it and get feedback. -# -# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/quickstart/text2text_quickstart.ipynb) - -# ## Setup -# ### Add API keys -# For this quickstart you will need Open AI and Huggingface keys - -# In[ ]: - -import os - -os.environ["OPENAI_API_KEY"] = "..." -os.environ["HUGGINGFACE_API_KEY"] = "..." - -# In[ ]: - -import openai - -openai.api_key = os.environ["OPENAI_API_KEY"] - -# ### Import from TruLens - -# In[ ]: - -from IPython.display import JSON - -# Imports main tools: -from trulens_eval import Feedback -from trulens_eval import Huggingface -from trulens_eval import Tru - -tru = Tru() - -# ### Create Simple Text to Text Application -# -# This example uses a bare bones OpenAI LLM, and a non-LLM just for demonstration purposes. - -# In[ ]: - - -def llm_standalone(prompt): - return openai.ChatCompletion.create( - model="gpt-3.5-turbo", - messages=[ - { - "role": - "system", - "content": - "You are a question and answer bot, and you answer super upbeat." - }, { - "role": "user", - "content": prompt - } - ] - )["choices"][0]["message"]["content"] - - -# In[ ]: - -import hashlib - - -def simple_hash_callable(prompt): - h = hashlib.shake_256(prompt.encode('utf-8')) - return str(h.hexdigest(20)) - - -# ### Send your first request - -# In[ ]: - -prompt_input = "How good is language AI?" -prompt_output = llm_standalone(prompt_input) -prompt_output - -# In[ ]: - -simple_hash_callable(prompt_input) - -# ## Initialize Feedback Function(s) - -# In[ ]: - -# Initialize Huggingface-based feedback function collection class: -hugs = Huggingface() - -# Define a sentiment feedback function using HuggingFace. -f_sentiment = Feedback(hugs.positive_sentiment).on_output() - -# ## Instrument the callable for logging with TruLens - -# In[ ]: - -from trulens_eval import TruBasicApp - -tru_llm_standalone_recorder = TruBasicApp( - llm_standalone, app_id="Happy Bot", feedbacks=[f_sentiment] -) -tru_simple_hash_callable_recorder = TruBasicApp( - simple_hash_callable, app_id="Hasher", feedbacks=[f_sentiment] -) - -# In[ ]: - -with tru_llm_standalone_recorder as recording: - tru_llm_standalone_recorder.app(prompt_input) - -# In[ ]: - -with tru_simple_hash_callable_recorder as recording: - tru_simple_hash_callable_recorder.app(prompt_input) - -# ## Explore in a Dashboard - -# In[ ]: - -tru.run_dashboard() # open a local streamlit app to explore - -# tru.stop_dashboard() # stop if needed - -# Alternatively, you can run `trulens-eval` from a command line in the same folder to start the dashboard. - -# ## Or view results directly in your notebook - -# In[ ]: - -tru.get_records_and_feedback(app_ids=[] - )[0] # pass an empty list of app_ids to get all diff --git a/trulens_eval/README.md b/trulens_eval/README.md index 4ec87489b..1779ee2f0 100644 --- a/trulens_eval/README.md +++ b/trulens_eval/README.md @@ -46,24 +46,24 @@ TruLens supports the evaluation of tracking for any LLM app framework. Choose a **Langchain** -[langchain_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/langchain_quickstart.ipynb). -[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/colab/quickstarts/langchain_quickstart_colab.ipynb) +[langchain_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/langchain_quickstart.ipynb). +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/colab/quickstarts/langchain_quickstart_colab.ipynb) -[langchain_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/py_script_quickstarts/langchain_quickstart.py). +[langchain_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/py_script_quickstarts/langchain_quickstart.py). **Llama-Index** -[llama_index_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/llama_index_quickstart.ipynb). -[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/colab/quickstarts/llama_index_quickstart_colab.ipynb) +[llama_index_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/llama_index_quickstart.ipynb). +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/colab/quickstarts/llama_index_quickstart_colab.ipynb) -[llama_index_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/py_script_quickstarts/llama_index_quickstart.py) +[llama_index_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/py_script_quickstarts/llama_index_quickstart.py) **No Framework** -[text2text_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/text2text_quickstart.ipynb). -[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/colab/quickstarts/text2text_quickstart_colab.ipynb) +[text2text_quickstart.ipynb](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/text2text_quickstart.ipynb). +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/colab/quickstarts/text2text_quickstart_colab.ipynb) -[text2text_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.13.0/trulens_eval/examples/quickstart/py_script_quickstarts/text2text_quickstart.py) +[text2text_quickstart.py](https://github.com/truera/trulens/blob/releases/rc-trulens-eval-0.14.0/trulens_eval/examples/quickstart/py_script_quickstarts/text2text_quickstart.py) ### 💡 Contributing diff --git a/trulens_eval/examples/quickstart/py_script_quickstarts/all_tools.py b/trulens_eval/examples/quickstart/py_script_quickstarts/all_tools.py index aa7ee1fab..2eb7c2ac8 100644 --- a/trulens_eval/examples/quickstart/py_script_quickstarts/all_tools.py +++ b/trulens_eval/examples/quickstart/py_script_quickstarts/all_tools.py @@ -2,28 +2,25 @@ # coding: utf-8 # # Langchain Quickstart -# +# # In this quickstart you will create a simple LLM Chain and learn how to log it and get feedback on an LLM response. -# -# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/langchain_quickstart.ipynb) +# +# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/quickstart/langchain_quickstart.ipynb) + +# ! pip install trulens_eval==0.14.0 langchain>=0.0.263 # ## Setup # ### Add API keys # For this quickstart you will need Open AI and Huggingface keys import os - os.environ["OPENAI_API_KEY"] = "..." os.environ["HUGGINGFACE_API_KEY"] = "..." # ### Import from LangChain and TruLens # Imports main tools: -from trulens_eval import Feedback -from trulens_eval import Huggingface -from trulens_eval import Tru -from trulens_eval import TruChain - +from trulens_eval import TruChain, Feedback, Huggingface, Tru tru = Tru() # Imports from langchain to build app. You may need to install langchain first @@ -31,12 +28,11 @@ # ! pip install langchain>=0.0.170 from langchain.chains import LLMChain from langchain.llms import OpenAI -from langchain.prompts.chat import ChatPromptTemplate +from langchain.prompts.chat import ChatPromptTemplate, PromptTemplate from langchain.prompts.chat import HumanMessagePromptTemplate -from langchain.prompts.chat import PromptTemplate # ### Create Simple LLM Application -# +# # This example uses a LangChain framework and OpenAI LLM full_prompt = HumanMessagePromptTemplate( @@ -73,118 +69,122 @@ # ## Instrument chain for logging with TruLens -tru_chain_recorder = TruChain( - chain, +tru_recorder = TruChain(chain, app_id='Chain1_ChatApplication', - feedbacks=[f_lang_match], - tags="prototype" -) + feedbacks=[f_lang_match]) -# or as a context manager -with tru_chain_recorder as recording: +with tru_recorder as recording: llm_response = chain(prompt_input) print(llm_response) # ## Explore in a Dashboard -tru.run_dashboard() # open a local streamlit app to explore +tru.run_dashboard() # open a local streamlit app to explore # tru.stop_dashboard() # stop if needed # Alternatively, you can run `trulens-eval` from a command line in the same folder to start the dashboard. # ### Chain Leaderboard -# +# # Understand how your LLM application is performing at a glance. Once you've set up logging and evaluation in your application, you can view key performance statistics including cost and average feedback value across all of your LLM apps using the chain leaderboard. As you iterate new versions of your LLM application, you can compare their performance across all of the different quality metrics you've set up. -# +# # Note: Average feedback values are returned and printed in a range from 0 (worst) to 1 (best). -# +# # ![Chain Leaderboard](https://www.trulens.org/Assets/image/Leaderboard.png) -# +# # To dive deeper on a particular chain, click "Select Chain". -# +# # ### Understand chain performance with Evaluations -# +# # To learn more about the performance of a particular chain or LLM model, we can select it to view its evaluations at the record level. LLM quality is assessed through the use of feedback functions. Feedback functions are extensible methods for determining the quality of LLM responses and can be applied to any downstream LLM task. Out of the box we provide a number of feedback functions for assessing model agreement, sentiment, relevance and more. -# +# # The evaluations tab provides record-level metadata and feedback on the quality of your LLM application. -# +# # ![Evaluations](https://www.trulens.org/Assets/image/Leaderboard.png) -# +# # ### Deep dive into full chain metadata -# +# # Click on a record to dive deep into all of the details of your chain stack and underlying LLM, captured by tru_chain_recorder. -# +# # ![Explore a Chain](https://www.trulens.org/Assets/image/Chain_Explore.png) -# +# # If you prefer the raw format, you can quickly get it using the "Display full chain json" or "Display full record json" buttons at the bottom of the page. # Note: Feedback functions evaluated in the deferred manner can be seen in the "Progress" page of the TruLens dashboard. # ## Or view results directly in your notebook -tru.get_records_and_feedback(app_ids=[] - )[0] # pass an empty list of app_ids to get all +tru.get_records_and_feedback(app_ids=[])[0] # pass an empty list of app_ids to get all # # Logging Methods -# +# # ## Automatic Logging -# +# # The simplest method for logging with TruLens is by wrapping with TruChain and including the tru argument, as shown in the quickstart. -# +# # This is done like so: -truchain_recorder = TruChain(chain, app_id='Chain1_ChatApplication', tru=tru) - -with truchain_recorder as recording: - chain("This will be automatically logged.") +truchain = TruChain( + chain, + app_id='Chain1_ChatApplication', + tru=tru +) +truchain("This will be automatically logged.") # Feedback functions can also be logged automatically by providing them in a list to the feedbacks arg. -truchain_recorder = TruChain( +truchain = TruChain( chain, app_id='Chain1_ChatApplication', - feedbacks=[f_lang_match], # feedback functions + feedbacks=[f_lang_match], # feedback functions tru=tru ) - -with truchain_recorder as recording: - chain("This will be automatically logged.") +truchain("This will be automatically logged.") # ## Manual Logging -# +# # ### Wrap with TruChain to instrument your chain -truchain_recorder = TruChain(chain, app_id='Chain1_ChatApplication') +tc = TruChain(chain, app_id='Chain1_ChatApplication') # ### Set up logging and instrumentation -# +# # Making the first call to your wrapped LLM Application will now also produce a log or "record" of the chain execution. -# +# prompt_input = 'que hora es?' -gpt3_response, record = truchain_recorder.with_record(chain, prompt_input) +gpt3_response, record = tc.call_with_record(prompt_input) + +# We can log the records but first we need to log the chain itself. + +tru.add_app(app=truchain) + +# Then we can log the record: + +tru.add_record(record) # ### Log App Feedback # Capturing app feedback such as user feedback of the responses can be added with one call. thumb_result = True -tru.add_feedback( - name="👍 (1) or 👎 (0)", record_id=record.record_id, result=thumb_result -) +tru.add_feedback(name="👍 (1) or 👎 (0)", + record_id=record.record_id, + result=thumb_result) # ### Evaluate Quality -# +# # Following the request to your app, you can then evaluate LLM quality using feedback functions. This is completed in a sequential call to minimize latency for your application, and evaluations will also be logged to your local machine. -# +# # To get feedback on the quality of your LLM, you can use any of the provided feedback functions or add your own. -# +# # To assess your LLM quality, you can provide the feedback functions to `tru.run_feedback()` in a list provided to `feedback_functions`. -# +# feedback_results = tru.run_feedback_functions( - record=record, feedback_functions=[f_lang_match] + record=record, + feedback_functions=[f_lang_match] ) print(feedback_results) @@ -193,12 +193,12 @@ tru.add_feedbacks(feedback_results) # ### Out-of-band Feedback evaluation -# +# # In the above example, the feedback function evaluation is done in the same process as the chain evaluation. The alternative approach is the use the provided persistent evaluator started via `tru.start_deferred_feedback_evaluator`. Then specify the `feedback_mode` for `TruChain` as `deferred` to let the evaluator handle the feedback functions. -# +# # For demonstration purposes, we start the evaluator here but it can be started in another process. -truchain_recorder: TruChain = TruChain( +truchain: TruChain = TruChain( chain, app_id='Chain1_ChatApplication', feedbacks=[f_lang_match], @@ -207,27 +207,21 @@ ) tru.start_evaluator() -with truchain_recorder as recording: - chain("This will be logged by deferred evaluator.") +truchain("This will be logged by deferred evaluator.") tru.stop_evaluator() # # Custom Functions -# +# # Feedback functions are an extensible framework for evaluating LLMs. You can add your own feedback functions to evaluate the qualities required by your application by updating `trulens_eval/feedback.py`, or simply creating a new provider class and feedback function in youre notebook. If your contributions would be useful for others, we encourage you to contribute to TruLens! -# +# # Feedback functions are organized by model provider into Provider classes. -# +# # The process for adding new feedback functions is: # 1. Create a new Provider class or locate an existing one that applies to your feedback function. If your feedback function does not rely on a model provider, you can create a standalone class. Add the new feedback function method to your selected class. Your new method can either take a single text (str) as a parameter or both prompt (str) and response (str). It should return a float between 0 (worst) and 1 (best). -from trulens_eval import Feedback -from trulens_eval import Provider -from trulens_eval import Select -from trulens_eval import Tru - +from trulens_eval import Provider, Feedback, Select, Tru class StandAlone(Provider): - def custom_feedback(self, my_text_field: str) -> float: """ A dummy function of text inputs to float outputs. @@ -240,67 +234,57 @@ def custom_feedback(self, my_text_field: str) -> float: """ return 1.0 / (1.0 + len(my_text_field) * len(my_text_field)) - # 2. Instantiate your provider and feedback functions. The feedback function is wrapped by the trulens-eval Feedback class which helps specify what will get sent to your function parameters (For example: Select.RecordInput or Select.RecordOutput) standalone = StandAlone() -f_custom_function = Feedback(standalone.custom_feedback - ).on(my_text_field=Select.RecordOutput) +f_custom_function = Feedback(standalone.custom_feedback).on( + my_text_field=Select.RecordOutput +) # 3. Your feedback function is now ready to use just like the out of the box feedback functions. Below is an example of it being used. tru = Tru() feedback_results = tru.run_feedback_functions( - record=record, feedback_functions=[f_custom_function] + record=record, + feedback_functions=[f_custom_function] ) tru.add_feedbacks(feedback_results) # ## Multi-Output Feedback functions # Trulens also supports multi-output feedback functions. As a typical feedback function will output a float between 0 and 1, multi-output should output a dictionary of `output_key` to a float between 0 and 1. The feedbacks table will print the feedback with column `feedback_name:::outputkey` -multi_output_feedback = Feedback( - lambda input_param: { - 'output_key1': 0.1, - 'output_key2': 0.9 - }, name="multi" -).on(input_param=Select.RecordOutput) +multi_output_feedback = Feedback(lambda input_param: {'output_key1': 0.1, 'output_key2': 0.9}, name="multi").on( + input_param=Select.RecordOutput +) feedback_results = tru.run_feedback_functions( - record=record, feedback_functions=[multi_output_feedback] + record=record, + feedback_functions=[multi_output_feedback] ) tru.add_feedbacks(feedback_results) # Aggregators will run on the same dict keys. import numpy as np - -multi_output_feedback = Feedback( - lambda input_param: { - 'output_key1': 0.1, - 'output_key2': 0.9 - }, - name="multi-agg" -).on(input_param=Select.RecordOutput).aggregate(np.mean) +multi_output_feedback = Feedback(lambda input_param: {'output_key1': 0.1, 'output_key2': 0.9}, name="multi-agg").on( + input_param=Select.RecordOutput +).aggregate(np.mean) feedback_results = tru.run_feedback_functions( - record=record, feedback_functions=[multi_output_feedback] + record=record, + feedback_functions=[multi_output_feedback] ) tru.add_feedbacks(feedback_results) - # For multi-context chunking, an aggregator can operate on a list of multi output dictionaries. def dict_aggregator(list_dict_input): agg = 0 for dict_input in list_dict_input: agg += dict_input['output_key1'] return agg - - -multi_output_feedback = Feedback( - lambda input_param: { - 'output_key1': 0.1, - 'output_key2': 0.9 - }, - name="multi-agg-dict" -).on(input_param=Select.RecordOutput).aggregate(dict_aggregator) +multi_output_feedback = Feedback(lambda input_param: {'output_key1': 0.1, 'output_key2': 0.9}, name="multi-agg-dict").on( + input_param=Select.RecordOutput +).aggregate(dict_aggregator) feedback_results = tru.run_feedback_functions( - record=record, feedback_functions=[multi_output_feedback] + record=record, + feedback_functions=[multi_output_feedback] ) tru.add_feedbacks(feedback_results) + diff --git a/trulens_eval/examples/quickstart/py_script_quickstarts/langchain_quickstart.py b/trulens_eval/examples/quickstart/py_script_quickstarts/langchain_quickstart.py index ceb890c78..7f778e072 100644 --- a/trulens_eval/examples/quickstart/py_script_quickstarts/langchain_quickstart.py +++ b/trulens_eval/examples/quickstart/py_script_quickstarts/langchain_quickstart.py @@ -2,28 +2,25 @@ # coding: utf-8 # # Langchain Quickstart -# +# # In this quickstart you will create a simple LLM Chain and learn how to log it and get feedback on an LLM response. -# -# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/langchain_quickstart.ipynb) +# +# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/quickstart/langchain_quickstart.ipynb) + +# ! pip install trulens_eval==0.14.0 langchain>=0.0.263 # ## Setup # ### Add API keys # For this quickstart you will need Open AI and Huggingface keys import os - os.environ["OPENAI_API_KEY"] = "..." os.environ["HUGGINGFACE_API_KEY"] = "..." # ### Import from LangChain and TruLens # Imports main tools: -from trulens_eval import Feedback -from trulens_eval import Huggingface -from trulens_eval import Tru -from trulens_eval import TruChain - +from trulens_eval import TruChain, Feedback, Huggingface, Tru tru = Tru() # Imports from langchain to build app. You may need to install langchain first @@ -31,12 +28,11 @@ # ! pip install langchain>=0.0.170 from langchain.chains import LLMChain from langchain.llms import OpenAI -from langchain.prompts.chat import ChatPromptTemplate +from langchain.prompts.chat import ChatPromptTemplate, PromptTemplate from langchain.prompts.chat import HumanMessagePromptTemplate -from langchain.prompts.chat import PromptTemplate # ### Create Simple LLM Application -# +# # This example uses a LangChain framework and OpenAI LLM full_prompt = HumanMessagePromptTemplate( @@ -73,56 +69,52 @@ # ## Instrument chain for logging with TruLens -tru_chain_recorder = TruChain( - chain, +tru_recorder = TruChain(chain, app_id='Chain1_ChatApplication', - feedbacks=[f_lang_match], - tags="prototype" -) + feedbacks=[f_lang_match]) -# or as a context manager -with tru_chain_recorder as recording: +with tru_recorder as recording: llm_response = chain(prompt_input) print(llm_response) # ## Explore in a Dashboard -tru.run_dashboard() # open a local streamlit app to explore +tru.run_dashboard() # open a local streamlit app to explore # tru.stop_dashboard() # stop if needed # Alternatively, you can run `trulens-eval` from a command line in the same folder to start the dashboard. # ### Chain Leaderboard -# +# # Understand how your LLM application is performing at a glance. Once you've set up logging and evaluation in your application, you can view key performance statistics including cost and average feedback value across all of your LLM apps using the chain leaderboard. As you iterate new versions of your LLM application, you can compare their performance across all of the different quality metrics you've set up. -# +# # Note: Average feedback values are returned and printed in a range from 0 (worst) to 1 (best). -# +# # ![Chain Leaderboard](https://www.trulens.org/Assets/image/Leaderboard.png) -# +# # To dive deeper on a particular chain, click "Select Chain". -# +# # ### Understand chain performance with Evaluations -# +# # To learn more about the performance of a particular chain or LLM model, we can select it to view its evaluations at the record level. LLM quality is assessed through the use of feedback functions. Feedback functions are extensible methods for determining the quality of LLM responses and can be applied to any downstream LLM task. Out of the box we provide a number of feedback functions for assessing model agreement, sentiment, relevance and more. -# +# # The evaluations tab provides record-level metadata and feedback on the quality of your LLM application. -# +# # ![Evaluations](https://www.trulens.org/Assets/image/Leaderboard.png) -# +# # ### Deep dive into full chain metadata -# +# # Click on a record to dive deep into all of the details of your chain stack and underlying LLM, captured by tru_chain_recorder. -# +# # ![Explore a Chain](https://www.trulens.org/Assets/image/Chain_Explore.png) -# +# # If you prefer the raw format, you can quickly get it using the "Display full chain json" or "Display full record json" buttons at the bottom of the page. # Note: Feedback functions evaluated in the deferred manner can be seen in the "Progress" page of the TruLens dashboard. # ## Or view results directly in your notebook -tru.get_records_and_feedback(app_ids=[] - )[0] # pass an empty list of app_ids to get all +tru.get_records_and_feedback(app_ids=[])[0] # pass an empty list of app_ids to get all + diff --git a/trulens_eval/examples/quickstart/py_script_quickstarts/llama_index_quickstart.py b/trulens_eval/examples/quickstart/py_script_quickstarts/llama_index_quickstart.py index 401a3b67e..05fc84f55 100644 --- a/trulens_eval/examples/quickstart/py_script_quickstarts/llama_index_quickstart.py +++ b/trulens_eval/examples/quickstart/py_script_quickstarts/llama_index_quickstart.py @@ -2,46 +2,40 @@ # coding: utf-8 # # Llama-Index Quickstart -# +# # In this quickstart you will create a simple Llama Index App and learn how to log it and get feedback on an LLM response. -# -# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/frameworks/llama_index/llama_index_quickstart.ipynb) +# +# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/quickstart/llama_index_quickstart.ipynb) # ## Setup -# +# # ### Install dependencies # Let's install some of the dependencies for this notebook if we don't have them already -#! pip install trulens-eval==0.12.0 llama_index==0.8.29post1 html2text==2020.1.16 +#! pip install trulens-eval==0.14.0 llama_index>=0.8.29post1 html2text>=2020.1.16 # ### Add API keys # For this quickstart, you will need Open AI and Huggingface keys. The OpenAI key is used for embeddings and GPT, and the Huggingface key is used for evaluation. import os - os.environ["OPENAI_API_KEY"] = "..." os.environ["HUGGINGFACE_API_KEY"] = "..." # ### Import from LlamaIndex and TruLens # Imports main tools: -from trulens_eval import Feedback -from trulens_eval import feedback -from trulens_eval import Tru -from trulens_eval import TruLlama - +from trulens_eval import TruLlama, Feedback, Tru, feedback tru = Tru() # ### Create Simple LLM Application -# +# # This example uses LlamaIndex which internally uses an OpenAI LLM. -from llama_index import SimpleWebPageReader -from llama_index import VectorStoreIndex +from llama_index import VectorStoreIndex, SimpleWebPageReader -documents = SimpleWebPageReader(html_to_text=True).load_data( - ["http://paulgraham.com/worked.html"] -) +documents = SimpleWebPageReader( + html_to_text=True +).load_data(["http://paulgraham.com/worked.html"]) index = VectorStoreIndex.from_documents(documents) query_engine = index.as_query_engine() @@ -74,11 +68,9 @@ # ## Instrument app for logging with TruLens -tru_query_engine_recorder = TruLlama( - query_engine, +tru_query_engine_recorder = TruLlama(query_engine, app_id='LlamaIndex_App1', - feedbacks=[f_lang_match, f_qa_relevance, f_qs_relevance] -) + feedbacks=[f_lang_match, f_qa_relevance, f_qs_relevance]) # or as context manager with tru_query_engine_recorder as recording: @@ -86,41 +78,41 @@ # ## Explore in a Dashboard -tru.run_dashboard() # open a local streamlit app to explore +tru.run_dashboard() # open a local streamlit app to explore # tru.stop_dashboard() # stop if needed # Alternatively, you can run `trulens-eval` from a command line in the same folder to start the dashboard. # ### Leaderboard -# +# # Understand how your LLM application is performing at a glance. Once you've set up logging and evaluation in your application, you can view key performance statistics including cost and average feedback value across all of your LLM apps using the app leaderboard. As you iterate new versions of your LLM application, you can compare their performance across all of the different quality metrics you've set up. -# +# # Note: Average feedback values are returned and printed in a range from 0 (worst) to 1 (best). -# +# # ![App Leaderboard](https://www.trulens.org/Assets/image/Leaderboard.png) -# +# # To dive deeper on a particular app, click "Select App". -# +# # ### Understand app performance with Evaluations -# +# # To learn more about the performance of a particular app or LLM model, we can select it to view its evaluations at the record level. LLM quality is assessed through the use of feedback functions. Feedback functions are extensible methods for determining the quality of LLM responses and can be applied to any downstream LLM task. Out of the box we provide a number of feedback functions for assessing model agreement, sentiment, relevance and more. -# +# # The evaluations tab provides record-level metadata and feedback on the quality of your LLM application. -# +# # ![Evaluations](https://www.trulens.org/Assets/image/Leaderboard.png) -# +# # ### Deep dive into full app metadata -# +# # Click on a record to dive deep into all of the details of your app stack and underlying LLM, captured by tru_query_engine_recorder. -# +# # ![Explore an App](https://www.trulens.org/Assets/image/Chain_Explore.png) -# +# # If you prefer the raw format, you can quickly get it using the "Display full app json" or "Display full record json" buttons at the bottom of the page. # Note: Feedback functions evaluated in the deferred manner can be seen in the "Progress" page of the TruLens dashboard. # ## Or view results directly in your notebook -tru.get_records_and_feedback(app_ids=[] - )[0] # pass an empty list of app_ids to get all +tru.get_records_and_feedback(app_ids=[])[0] # pass an empty list of app_ids to get all + diff --git a/trulens_eval/examples/quickstart/py_script_quickstarts/text2text_quickstart.py b/trulens_eval/examples/quickstart/py_script_quickstarts/text2text_quickstart.py index a37512878..796d3d8db 100644 --- a/trulens_eval/examples/quickstart/py_script_quickstarts/text2text_quickstart.py +++ b/trulens_eval/examples/quickstart/py_script_quickstarts/text2text_quickstart.py @@ -1,67 +1,50 @@ #!/usr/bin/env python # coding: utf-8 -# # No Framework Quickstart -# +# # Text to Text Quickstart +# # In this quickstart you will create a simple text to text application and learn how to log it and get feedback. -# -# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/no_framework_quickstart.ipynb) +# +# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/quickstart/text2text_quickstart.ipynb) # ## Setup # ### Add API keys # For this quickstart you will need Open AI and Huggingface keys import os - os.environ["OPENAI_API_KEY"] = "..." os.environ["HUGGINGFACE_API_KEY"] = "..." import openai - openai.api_key = os.environ["OPENAI_API_KEY"] # ### Import from TruLens # Imports main tools: -from trulens_eval import Feedback -from trulens_eval import Huggingface -from trulens_eval import Tru - +from trulens_eval import Feedback, Huggingface, Tru tru = Tru() # ### Create Simple Text to Text Application -# +# # This example uses a bare bones OpenAI LLM, and a non-LLM just for demonstration purposes. - def llm_standalone(prompt): return openai.ChatCompletion.create( - model="gpt-3.5-turbo", - messages=[ - { - "role": - "system", - "content": - "You are a question and answer bot, and you answer super upbeat." - }, { - "role": "user", - "content": prompt - } + model="gpt-3.5-turbo", + messages=[ + {"role": "system", "content": "You are a question and answer bot, and you answer super upbeat."}, + {"role": "user", "content": prompt} ] )["choices"][0]["message"]["content"] - import hashlib - - def simple_hash_callable(prompt): h = hashlib.shake_256(prompt.encode('utf-8')) return str(h.hexdigest(20)) - # ### Send your first request -prompt_input = "How good is language AI?" +prompt_input="How good is language AI?" prompt_output = llm_standalone(prompt_input) prompt_output @@ -78,23 +61,18 @@ def simple_hash_callable(prompt): # ## Instrument the callable for logging with TruLens from trulens_eval import TruBasicApp - -tru_llm_standalone_recorder = TruBasicApp( - llm_standalone, app_id="Happy Bot", feedbacks=[f_sentiment] -) -tru_simple_hash_callable_recorder = TruBasicApp( - simple_hash_callable, app_id="Hasher", feedbacks=[f_sentiment] -) +tru_llm_standalone_recorder = TruBasicApp(llm_standalone, app_id="Happy Bot", feedbacks=[f_sentiment]) +tru_simple_hash_callable_recorder = TruBasicApp(simple_hash_callable, app_id="Hasher", feedbacks=[f_sentiment]) with tru_llm_standalone_recorder as recording: - llm_standalone(prompt_input) + tru_llm_standalone_recorder.app(prompt_input) with tru_simple_hash_callable_recorder as recording: - simple_hash_callable(prompt_input) + tru_simple_hash_callable_recorder.app(prompt_input) # ## Explore in a Dashboard -tru.run_dashboard() # open a local streamlit app to explore +tru.run_dashboard() # open a local streamlit app to explore # tru.stop_dashboard() # stop if needed @@ -102,5 +80,5 @@ def simple_hash_callable(prompt): # ## Or view results directly in your notebook -tru.get_records_and_feedback(app_ids=[] - )[0] # pass an empty list of app_ids to get all +tru.get_records_and_feedback(app_ids=[])[0] # pass an empty list of app_ids to get all + diff --git a/trulens_eval/generated_files/all_tools.ipynb b/trulens_eval/generated_files/all_tools.ipynb index 010b9193b..82d530ee7 100644 --- a/trulens_eval/generated_files/all_tools.ipynb +++ b/trulens_eval/generated_files/all_tools.ipynb @@ -12,6 +12,15 @@ "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/truera/trulens/blob/main/trulens_eval/examples/quickstart/langchain_quickstart.ipynb)" ] }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# ! pip install trulens_eval==0.14.0 langchain>=0.0.263" + ] + }, { "attachments": {}, "cell_type": "markdown", @@ -261,7 +270,6 @@ }, { "cell_type": "markdown", - "id": "454903c2", "metadata": {}, "source": [ "# Logging Methods\n", @@ -276,7 +284,6 @@ { "cell_type": "code", "execution_count": null, - "id": "26fa21b6", "metadata": {}, "outputs": [], "source": [ @@ -290,7 +297,6 @@ }, { "cell_type": "markdown", - "id": "3d382033", "metadata": {}, "source": [ "Feedback functions can also be logged automatically by providing them in a list to the feedbacks arg." @@ -299,7 +305,6 @@ { "cell_type": "code", "execution_count": null, - "id": "f9152cae", "metadata": {}, "outputs": [], "source": [ @@ -314,7 +319,6 @@ }, { "cell_type": "markdown", - "id": "3a562298", "metadata": {}, "source": [ "## Manual Logging\n", @@ -325,7 +329,6 @@ { "cell_type": "code", "execution_count": null, - "id": "de9b7589", "metadata": {}, "outputs": [], "source": [ @@ -334,7 +337,6 @@ }, { "cell_type": "markdown", - "id": "4e25e0f9", "metadata": {}, "source": [ "### Set up logging and instrumentation\n", @@ -345,7 +347,6 @@ { "cell_type": "code", "execution_count": null, - "id": "c67a07d6", "metadata": {}, "outputs": [], "source": [ @@ -355,7 +356,6 @@ }, { "cell_type": "markdown", - "id": "7a8a9435", "metadata": {}, "source": [ "We can log the records but first we need to log the chain itself." @@ -364,7 +364,6 @@ { "cell_type": "code", "execution_count": null, - "id": "c8b2c12a", "metadata": {}, "outputs": [], "source": [ @@ -373,7 +372,6 @@ }, { "cell_type": "markdown", - "id": "e381d0f1", "metadata": {}, "source": [ "Then we can log the record:" @@ -382,7 +380,6 @@ { "cell_type": "code", "execution_count": null, - "id": "15cf1da6", "metadata": {}, "outputs": [], "source": [ @@ -391,7 +388,6 @@ }, { "cell_type": "markdown", - "id": "211d94f6", "metadata": {}, "source": [ "### Log App Feedback\n", @@ -401,7 +397,6 @@ { "cell_type": "code", "execution_count": null, - "id": "b9a1393f", "metadata": {}, "outputs": [], "source": [ @@ -413,7 +408,6 @@ }, { "cell_type": "markdown", - "id": "dfa0b62c", "metadata": {}, "source": [ "### Evaluate Quality\n", @@ -428,7 +422,6 @@ { "cell_type": "code", "execution_count": null, - "id": "e8db8fc2", "metadata": {}, "outputs": [], "source": [ @@ -441,7 +434,6 @@ }, { "cell_type": "markdown", - "id": "997ace16", "metadata": {}, "source": [ "After capturing feedback, you can then log it to your local database." @@ -450,7 +442,6 @@ { "cell_type": "code", "execution_count": null, - "id": "75a23831", "metadata": {}, "outputs": [], "source": [ @@ -459,7 +450,6 @@ }, { "cell_type": "markdown", - "id": "b0ecdc2b", "metadata": {}, "source": [ "### Out-of-band Feedback evaluation\n", @@ -472,7 +462,6 @@ { "cell_type": "code", "execution_count": null, - "id": "0e5c2ea7", "metadata": {}, "outputs": [], "source": [ @@ -492,7 +481,6 @@ { "attachments": {}, "cell_type": "markdown", - "id": "691ec232", "metadata": {}, "source": [ "# Custom Functions\n", @@ -508,7 +496,6 @@ { "cell_type": "code", "execution_count": null, - "id": "b32ec934", "metadata": {}, "outputs": [], "source": [ @@ -531,7 +518,6 @@ { "attachments": {}, "cell_type": "markdown", - "id": "4056c677", "metadata": {}, "source": [ "2. Instantiate your provider and feedback functions. The feedback function is wrapped by the trulens-eval Feedback class which helps specify what will get sent to your function parameters (For example: Select.RecordInput or Select.RecordOutput)" @@ -540,7 +526,6 @@ { "cell_type": "code", "execution_count": null, - "id": "db77781f", "metadata": {}, "outputs": [], "source": [ @@ -553,7 +538,6 @@ { "attachments": {}, "cell_type": "markdown", - "id": "66987343", "metadata": {}, "source": [ "3. Your feedback function is now ready to use just like the out of the box feedback functions. Below is an example of it being used." @@ -562,7 +546,6 @@ { "cell_type": "code", "execution_count": null, - "id": "8db425de", "metadata": {}, "outputs": [], "source": [ @@ -576,7 +559,6 @@ }, { "cell_type": "markdown", - "id": "0383846e", "metadata": {}, "source": [ "## Multi-Output Feedback functions\n", @@ -586,7 +568,6 @@ { "cell_type": "code", "execution_count": null, - "id": "5e6d785b", "metadata": {}, "outputs": [], "source": [ @@ -603,7 +584,6 @@ { "cell_type": "code", "execution_count": null, - "id": "a8f9fb6c", "metadata": {}, "outputs": [], "source": [ @@ -622,7 +602,6 @@ { "cell_type": "code", "execution_count": null, - "id": "d18c9331", "metadata": {}, "outputs": [], "source": [