Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
114 changes: 114 additions & 0 deletions docs/howtos/customizations/metrics/_cost.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Understand Cost and Usage of Operations

When using LLMs for evaluation and test set generation, cost will be an important factor. Ragas provides you some tools to help you with that.

## Understanding `TokenUsageParser`

By default Ragas does not calculate the usage of tokens for `evaluate()`. This is because langchain's LLMs do not always return information about token usage in a uniform way. So in order to get the usage data, we have to implement a `TokenUsageParser`.

A `TokenUsageParser` is function that parses the `LLMResult` or `ChatResult` from langchain models `generate_prompt()` function and outputs `TokenUsage` which Ragas expects.

For an example here is one that will parse OpenAI by using a parser we have defined.


```python
import os
os.environ["OPENAI_API_KEY"] = "your-api-key"
```


```python
from langchain_openai.chat_models import ChatOpenAI
from langchain_core.prompt_values import StringPromptValue

gpt4o = ChatOpenAI(model="gpt-4o")
p = StringPromptValue(text="hai there")
llm_result = gpt4o.generate_prompt([p])

# lets import a parser for OpenAI
from ragas.cost import get_token_usage_for_openai

get_token_usage_for_openai(llm_result)
```

/opt/homebrew/Caskroom/miniforge/base/envs/ragas/lib/python3.9/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
from .autonotebook import tqdm as notebook_tqdm





TokenUsage(input_tokens=9, output_tokens=9, model='')



You can define your own or import parsers if they are defined. If you would like to suggest parser for LLM providers or contribute your own ones please check out this [issue](https://github.com/explodinggradients/ragas/issues/1151) 🙂.

You can use it for evaluations as so. Using example from [get started](get-started-evaluation) here.


```python
from datasets import load_dataset
from ragas import EvaluationDataset
from ragas.metrics._aspect_critic import AspectCriticWithReference

dataset = load_dataset("explodinggradients/amnesty_qa", "english_v3")


eval_dataset = EvaluationDataset.from_hf_dataset(dataset["eval"])

metric = AspectCriticWithReference(
name="answer_correctness",
definition="is the response correct compared to reference",
)


```

Repo card metadata block was not found. Setting CardData to empty.



```python
from ragas import evaluate
from ragas.cost import get_token_usage_for_openai

results = evaluate(eval_dataset[:5], metrics=[metric], llm=gpt4o,
token_usage_parser=get_token_usage_for_openai,)
```

Evaluating: 100%|██████████| 5/5 [00:01<00:00, 2.81it/s]



```python
results.total_tokens()
```




TokenUsage(input_tokens=5463, output_tokens=355, model='')



You can compute the cost for each run by passing in the cost per token to `Result.total_cost()` function.

In this case GPT-4o costs $5 for 1M input tokens and $15 for 1M output tokens.


```python
results.total_cost(cost_per_input_token=5 / 1e6, cost_per_output_token=15 / 1e6)
```




0.03264




```python

```
211 changes: 211 additions & 0 deletions docs/howtos/customizations/metrics/cost.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Understand Cost and Usage of Operations\n",
"\n",
"When using LLMs for evaluation and test set generation, cost will be an important factor. Ragas provides you some tools to help you with that."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Understanding `TokenUsageParser`\n",
"\n",
"By default Ragas does not calculate the usage of tokens for `evaluate()`. This is because langchain's LLMs do not always return information about token usage in a uniform way. So in order to get the usage data, we have to implement a `TokenUsageParser`. \n",
"\n",
"A `TokenUsageParser` is function that parses the `LLMResult` or `ChatResult` from langchain models `generate_prompt()` function and outputs `TokenUsage` which Ragas expects.\n",
"\n",
"For an example here is one that will parse OpenAI by using a parser we have defined."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"os.environ[\"OPENAI_API_KEY\"] = \"your-api-key\""
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/opt/homebrew/Caskroom/miniforge/base/envs/ragas/lib/python3.9/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
" from .autonotebook import tqdm as notebook_tqdm\n"
]
},
{
"data": {
"text/plain": [
"TokenUsage(input_tokens=9, output_tokens=9, model='')"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from langchain_openai.chat_models import ChatOpenAI\n",
"from langchain_core.prompt_values import StringPromptValue\n",
"\n",
"gpt4o = ChatOpenAI(model=\"gpt-4o\")\n",
"p = StringPromptValue(text=\"hai there\")\n",
"llm_result = gpt4o.generate_prompt([p])\n",
"\n",
"# lets import a parser for OpenAI\n",
"from ragas.cost import get_token_usage_for_openai\n",
"\n",
"get_token_usage_for_openai(llm_result)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can define your own or import parsers if they are defined. If you would like to suggest parser for LLM providers or contribute your own ones please check out this [issue](https://github.com/explodinggradients/ragas/issues/1151) 🙂.\n",
"\n",
"You can use it for evaluations as so. Using example from [get started](get-started-evaluation) here."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Repo card metadata block was not found. Setting CardData to empty.\n"
]
}
],
"source": [
"from datasets import load_dataset\n",
"from ragas import EvaluationDataset\n",
"from ragas.metrics._aspect_critic import AspectCriticWithReference\n",
"\n",
"dataset = load_dataset(\"explodinggradients/amnesty_qa\", \"english_v3\")\n",
"\n",
"\n",
"eval_dataset = EvaluationDataset.from_hf_dataset(dataset[\"eval\"])\n",
"\n",
"metric = AspectCriticWithReference(\n",
" name=\"answer_correctness\",\n",
" definition=\"is the response correct compared to reference\",\n",
")\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Evaluating: 100%|██████████| 5/5 [00:01<00:00, 2.81it/s]\n"
]
}
],
"source": [
"from ragas import evaluate\n",
"from ragas.cost import get_token_usage_for_openai\n",
"\n",
"results = evaluate(eval_dataset[:5], metrics=[metric], llm=gpt4o,\n",
" token_usage_parser=get_token_usage_for_openai,)"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"TokenUsage(input_tokens=5463, output_tokens=355, model='')"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"results.total_tokens()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can compute the cost for each run by passing in the cost per token to `Result.total_cost()` function.\n",
"\n",
"In this case GPT-4o costs $5 for 1M input tokens and $15 for 1M output tokens."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.03264"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"results.total_cost(cost_per_input_token=5 / 1e6, cost_per_output_token=15 / 1e6)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.20"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Loading