%pip install -q validmind
Summarization of financial data using a large language model (LLM)
Document a large language model (LLM) using the ValidMind Developer Framework. The use case is a summarization of financial news based on a dataset containing just over 300k unique news articles as written by journalists at CNN and the Daily Mail.
This interactive notebook shows you how to set up the ValidMind Developer Framework, initialize the client library, and load the dataset, followed by running the model validation tests provided by the framework to quickly generate documentation about the data and model.
Before you begin
For access to all features available in this notebook, create a free ValidMind account.
Signing up is FREE — Sign up nowThis notebook requires an OpenAI API secret key to run. If you don’t have one, visit API keys on OpenAI’s site to create a new key for yourself. Note that API usage charges may apply.
If you encounter errors due to missing modules in your Python environment, install the modules with pip install
, and then re-run the notebook. For more help, refer to Installing Python Modules.
About ValidMind
ValidMind’s platform enables organizations to identify, document, and manage model risks for all types of models, including AI/ML models, LLMs, and statistical models. As a model developer, you use the ValidMind Developer Framework to automate documentation and validation tests, and then use the ValidMind AI Risk Platform UI to collaborate on model documentation, these products simplify model risk management, facilitate compliance with regulations and institutional standards, and enhance collaboration between yourself and model validators.
If this is your first time trying out ValidMind, we recommend going through the following resources first:
- Get started — The basics, including key concepts, and how our products work
- Get started with the ValidMind Developer Framework — The path for developers, more code samples, and our developer reference
Install the client library
The client library provides Python support for the ValidMind Developer Framework. To install it:
# Replace with your code snippet
import validmind as vm
vm.init(="https://api.prod.validmind.ai/api/v1/tracking",
api_host="...",
api_key="...",
api_secret="...",
project )
Preview the documentation template
A template predefines sections for your model documentation and provides a general outline to follow, making the documentation process much easier.
You will upload documentation and test results into this template later on. For now, take a look at the structure that the template provides with the vm.preview_template()
function from the ValidMind library and note the empty sections:
vm.preview_template()
Helper functions
Let’s define the following functions to help visualize datasets with long text fields:
import textwrap
from IPython.display import display, HTML
from tabulate import tabulate
def _format_cell_text(text, width=50):
"""Private function to format a cell's text."""
return "\n".join([textwrap.fill(line, width=width) for line in text.split("\n")])
def _format_dataframe_for_tabulate(df):
"""Private function to format the entire DataFrame for tabulation."""
= df.copy()
df_out
# Format all string columns
for column in df_out.columns:
# Check if column is of type object (likely strings)
if df_out[column].dtype == object:
= df_out[column].apply(_format_cell_text)
df_out[column] return df_out
def _dataframe_to_html_table(df):
"""Private function to convert a DataFrame to an HTML table."""
= df.columns.tolist()
headers = df.values.tolist()
table_data return tabulate(table_data, headers=headers, tablefmt="html")
def display_formatted_dataframe(df, num_rows=None):
"""Primary function to format and display a DataFrame."""
if num_rows is not None:
= df.head(num_rows)
df = _format_dataframe_for_tabulate(df)
formatted_df = _dataframe_to_html_table(formatted_df)
html_table display(HTML(html_table))
Load the dataset
The CNN Dailymail Dataset is an English-language dataset containing just over 300k unique news articles as written by journalists at CNN and the Daily Mail (https://huggingface.co/datasets/cnn_dailymail). The current version supports both extractive and abstractive summarization, though the original version was created for machine reading and comprehension and abstractive question answering.
import pandas as pd
= pd.read_csv("./datasets/cnn_dailymail_100_with_predictions.csv")
df =5) display_formatted_dataframe(df, num_rows
Get ready to run the analysis
Import the ValidMind FoundationModel
and Prompt
classes needed for the sentiment analysis later on:
from validmind.models import FoundationModel, Prompt
Check your access to the OpenAI API:
import os
import dotenv
dotenv.load_dotenv()
if os.getenv("OPENAI_API_KEY") is None:
raise Exception("OPENAI_API_KEY not found")
from openai import OpenAI
= OpenAI()
model
def call_model(prompt):
return (
model.chat.completions.create(="gpt-3.5-turbo",
model=[
messages"role": "user", "content": prompt},
{
],
)0]
.choices[
.message.content )
Set the prompt guidelines for the sentiment analysis:
= """
prompt_template You are an AI with expertise in summarizing financial news.
Your task is to provide a concise summary of the specific news article provided below.
Before proceeding, take a moment to understand the context and nuances of the financial terminology used in the article.
Article to Summarize:
```
{article}
```
Please respond with a concise summary of the article's main points.
Ensure that your summary is based on the content of the article and not on external information or assumptions.
""".strip()
= ["article"] prompt_variables
= vm.init_dataset(
vm_test_ds =df,
dataset="test_dataset",
input_id="article",
text_column="highlights",
target_column
)
= vm.init_model(
vm_model =FoundationModel(
model=call_model,
predict_fn=Prompt(
prompt=prompt_template,
template=prompt_variables,
variables
),
),="gpt_35_model",
input_id
)
# Assign model predictions to the test dataset
="gpt_35_prediction") vm_test_ds.assign_predictions(vm_model, prediction_column
Run model validation tests
It’s possible to run a subset of tests on the documentation template by passing a section
parameter to run_documentation_tests()
. Let’s run the tests that evaluate the model’s overall performance (including summarization metrics), by selecting the “model development” section of the template:
= vm.run_documentation_tests(
summarization_results ="model_development",
section={
inputs"dataset": vm_test_ds,
"model": vm_model,
}, )
Next steps
You can look at the results of this test suite right in the notebook where you ran the code, as you would expect. But there is a better way: view the prompt validation test results as part of your model documentation in the ValidMind Platform UI:
In the Platform UI, go to the Documentation page for the model you registered earlier.
Expand 2. Data Preparation or 3. Model Development to review all test results.
What you can see now is a more easily consumable version of the prompt validation testing you just performed, along with other parts of your model documentation that still need to be completed.
If you want to learn more about where you are in the model documentation process, take a look at Get started with the ValidMind Developer Framework.