Files
wehub-resource-sync 5a558eb09e
TypeScript SDK Compatibility V1.x E2E Tests / Select Node version matrix (push) Has been cancelled
TypeScript SDK Compatibility V1.x E2E Tests / TypeScript SDK Compatibility V1.x E2E Tests Node ${{matrix.node_version}} (push) Has been cancelled
TypeScript SDK E2E Tests / TypeScript SDK E2E Tests Node ${{matrix.node_version}} (push) Has been cancelled
Opik Optimizer - E2E Tests / build-opik (push) Has been cancelled
TypeScript SDK Compatibility V1.x E2E Tests / build-opik (push) Has been cancelled
Python SDK E2E Tests / Select Python version matrix (push) Has been cancelled
Python SDK E2E Tests / Python SDK E2E Tests ${{matrix.python_version}} (push) Has been cancelled
Python SDK E2E Tests / build-opik (push) Has been cancelled
Python SDK Compatibility V1.x E2E Tests / Select Python version matrix (push) Has been cancelled
Python SDK Compatibility V1.x E2E Tests / Python SDK Compatibility V1.x E2E Tests ${{matrix.python_version}} (push) Has been cancelled
Python SDK Compatibility V1.x E2E Tests / build-opik (push) Has been cancelled
TypeScript SDK E2E Tests / Select Node version matrix (push) Has been cancelled
TypeScript SDK E2E Tests / build-opik (push) Has been cancelled
Opik Optimizer - E2E Tests / Opik Optimizer E2E Tests Python ${{matrix.python_version}} (push) Has been cancelled
Opik Optimizer - E2E Tests / Opik Optimizer Integration Smoke Tests (push) Has been cancelled
🐙 Code Quality / detect (push) Has been cancelled
🐙 Code Quality / lint (${{ matrix.leg.name }}) (push) Has been cancelled
🐙 Code Quality / summary (push) Has been cancelled
TypeScript SDK Library Integration Tests / Check Secrets (push) Has been cancelled
TypeScript SDK Library Integration Tests / opik-vercel (Vercel AI SDK / eve) (push) Has been cancelled
SDK Library Integration Tests Runner / Check Secrets (push) Has been cancelled
SDK Library Integration Tests Runner / Missed OpenAI API Key Warning (push) Has been cancelled
SDK Library Integration Tests Runner / Build (push) Has been cancelled
SDK Library Integration Tests Runner / openai_tests (push) Has been cancelled
SDK Library Integration Tests Runner / langchain_tests (push) Has been cancelled
SDK Library Integration Tests Runner / langchain_legacy_tests (push) Has been cancelled
SDK Library Integration Tests Runner / llama_index_tests (push) Has been cancelled
SDK Library Integration Tests Runner / anthropic_tests (push) Has been cancelled
SDK Library Integration Tests Runner / mistral_tests (push) Has been cancelled
SDK Library Integration Tests Runner / groq_tests (push) Has been cancelled
SDK Library Integration Tests Runner / aisuite_tests (push) Has been cancelled
SDK Library Integration Tests Runner / haystack_tests (push) Has been cancelled
SDK Library Integration Tests Runner / dspy_tests (push) Has been cancelled
SDK Library Integration Tests Runner / crewai_v0_tests (push) Has been cancelled
SDK Library Integration Tests Runner / crewai_v1_tests (push) Has been cancelled
SDK Library Integration Tests Runner / genai_tests (push) Has been cancelled
SDK Library Integration Tests Runner / adk_tests (push) Has been cancelled
SDK Library Integration Tests Runner / adk_legacy_1_3_0_tests (push) Has been cancelled
SDK Library Integration Tests Runner / evaluation_metrics_tests (push) Has been cancelled
SDK Library Integration Tests Runner / bedrock_tests (push) Has been cancelled
SDK Library Integration Tests Runner / litellm_tests (push) Has been cancelled
SDK Library Integration Tests Runner / harbor_tests (push) Has been cancelled
SDK Library Integration Tests Runner / Slack Notification (push) Has been cancelled
Lint Opik Helm Chart / render-equality (push) Has been cancelled
Opik Optimizer - Unit Tests / Opik Optimizer Unit Tests Python ${{matrix.python_version}} (push) Has been cancelled
Python BE E2E Tests / Python BE E2E (push) Has been cancelled
Python Backend Tests / run-python-backend-tests (push) Has been cancelled
Python SDK Unit Tests / Python SDK Unit Tests ${{matrix.python_version}} (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
SDK E2E Libraries Integration Tests / Check Secrets (push) Has been cancelled
SDK E2E Libraries Integration Tests / Missed OpenAI API Key Warning (push) Has been cancelled
SDK E2E Libraries Integration Tests / build-opik (push) Has been cancelled
SDK E2E Libraries Integration Tests / E2E Lib Integration Python ${{matrix.python_version}} (push) Has been cancelled
TypeScript SDK Integration Build & Publish / build-and-publish (opik-gemini) (push) Has been cancelled
TypeScript SDK Integration Build & Publish / build-and-publish (opik-langchain) (push) Has been cancelled
TypeScript SDK Integration Build & Publish / build-and-publish (opik-openai) (push) Has been cancelled
TypeScript SDK Integration Build & Publish / build-and-publish (opik-otel) (push) Has been cancelled
TypeScript SDK Integration Build & Publish / build-and-publish (opik-vercel) (push) Has been cancelled
TypeScript SDK Build & Publish / build-and-publish (push) Has been cancelled
TypeScript SDK Unit Tests / Test on Node ${{ matrix.node-version }} (push) Has been cancelled
Backend Tests / discover-tests (push) Has been cancelled
Backend Tests / ${{ matrix.name }} (push) Has been cancelled
Build and Publish SDK / build-and-publish (push) Has been cancelled
Build Opik Docker Images / set-version (push) Has been cancelled
Build Opik Docker Images / build-backend (push) Has been cancelled
Build Opik Docker Images / build-sandbox-executor-python (push) Has been cancelled
Build Opik Docker Images / build-python-backend (push) Has been cancelled
Build Opik Docker Images / build-frontend (push) Has been cancelled
Build Opik Docker Images / create-git-tag (push) Has been cancelled
ClickHouse Migration Cluster Check / validate-clickhouse-migrations (push) Has been cancelled
Docs - Publish / run (push) Has been cancelled
E2E Tests - Post Merge (v2) / 🧪 E2E v2 Tests (${{ github.event.inputs.tier || 't1' }}) (push) Has been cancelled
E2E Tests - Post Merge (v2) / 📢 Slack Notification (push) Has been cancelled
Frontend Unit Tests / Test on Node 20 (push) Has been cancelled
Guardrails E2E Tests / Select Python version matrix (push) Has been cancelled
Guardrails E2E Tests / Guardrails E2E Tests ${{matrix.python_version}} (push) Has been cancelled
Guardrails E2E Tests / 📢 Slack Notification (push) Has been cancelled
Guardrails Backend Unit Tests / Guardrails Backend Unit Tests (push) Has been cancelled
Guardrails Backend Unit Tests / 📢 Slack Notification (push) Has been cancelled
Lint Opik Helm Chart / lint-helm-chart (Helm v3.21.0) (push) Has been cancelled
Lint Opik Helm Chart / lint-helm-chart (Helm v4.2.0) (push) Has been cancelled
Lint Opik Helm Chart / unittest-helm-chart (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 13:25:44 +08:00

652 lines
25 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Quickstart notebook - Summarization\n",
"\n",
"In this notebook, we will look at how you can use Opik to track your LLM calls, chains and agents. We will introduce the concept of tracing and how to automate the evaluation of your LLM workflows.\n",
"\n",
"We will be using a technique called Chain of Density Summarization to summarize Arxiv papers. You can learn more about this technique in the [From Sparse to Dense: GPT-4 Summarization with Chain of Density Prompting](https://arxiv.org/abs/2309.04269) paper."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Getting started\n",
"\n",
"We will first install the required dependencies and configure both Opik and OpenAI."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install -U opik openai requests PyPDF2 --quiet"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"[Comet](https://www.comet.com/site?from=llm&utm_source=opik&utm_medium=colab&utm_content=langchain&utm_campaign=opik) provides a hosted version of the Opik platform, [simply create an account](https://www.comet.com/signup?from=llm&utm_source=opik&utm_medium=colab&utm_content=langchain&utm_campaign=opik) and grab your API Key.\n",
"\n",
"> You can also run the Opik platform locally, see the [installation guide](https://www.comet.com/docs/opik/self-host/overview/?from=llm&utm_source=opik&utm_medium=colab&utm_content=langchain&utm_campaign=opik) for more information."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import opik\n",
"\n",
"# Configure Opik\n",
"opik.configure()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Implementing Chain of Density Summarization\n",
"\n",
"The idea behind this approach is to first generate a sparse candidate summary and then iteratively refine it with missing information without making it longer. We will start by defining two prompts:\n",
"\n",
"1. Iteration summary prompt: This prompt is used to generate and refine a candidate summary.\n",
"2. Final summary prompt: This prompt is used to generate the final summary from the sparse set of candidate summaries."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import opik\n",
"\n",
"ITERATION_SUMMARY_PROMPT = opik.Prompt(\n",
" name=\"Iteration Summary Prompt\",\n",
" prompt=\"\"\"\n",
"Document: {{document}}\n",
"Current summary: {{current_summary}}\n",
"Instruction to focus on: {{instruction}}\n",
"\n",
"Generate a concise, entity-dense, and highly technical summary from the provided Document that specifically addresses the given Instruction.\n",
"\n",
"Guidelines:\n",
"- Make every word count: If there is a current summary re-write it to improve flow, density and conciseness.\n",
"- Remove uninformative phrases like \"the article discusses\".\n",
"- The summary should become highly dense and concise yet self-contained, e.g. , easily understood without the Document.\n",
"- Make sure that the summary specifically addresses the given Instruction\n",
"\"\"\".rstrip().lstrip(),\n",
")\n",
"\n",
"FINAL_SUMMARY_PROMPT = opik.Prompt(\n",
" name=\"Final Summary Prompt\",\n",
" prompt=\"\"\"\n",
"Given this summary: {{current_summary}}\n",
"And this instruction to focus on: {{instruction}}\n",
"Create an extremely dense, final summary that captures all key technical information in the most concise form possible, while specifically addressing the given instruction.\n",
"\"\"\".rstrip().lstrip(),\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now define the summarization chain by combining the two prompts. In order to track the LLM calls, we will use Opik's integration with OpenAI through the `track_openai` function and we will add the `@opik.track` decorator to each function so we can track the full chain and not just individual LLM calls:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from opik.integrations.openai import track_openai\n",
"from openai import OpenAI\n",
"import opik\n",
"\n",
"# Use a dedicated quickstart endpoint, replace with your own OpenAI API Key in your own code\n",
"openai_client = track_openai(\n",
" OpenAI(\n",
" api_key=\"YOUR_OPENAI_API_KEY_HERE\",\n",
" )\n",
")\n",
"\n",
"\n",
"@opik.track\n",
"def summarize_current_summary(\n",
" document: str,\n",
" instruction: str,\n",
" current_summary: str,\n",
" model: str = \"gpt-4o-mini\",\n",
"):\n",
" prompt = ITERATION_SUMMARY_PROMPT.format(\n",
" document=document, current_summary=current_summary, instruction=instruction\n",
" )\n",
"\n",
" response = openai_client.chat.completions.create(\n",
" model=model, max_tokens=4096, messages=[{\"role\": \"user\", \"content\": prompt}]\n",
" )\n",
"\n",
" return response.choices[0].message.content\n",
"\n",
"\n",
"@opik.track\n",
"def iterative_density_summarization(\n",
" document: str,\n",
" instruction: str,\n",
" density_iterations: int,\n",
" model: str = \"gpt-4o-mini\",\n",
"):\n",
" summary = \"\"\n",
" for iteration in range(1, density_iterations + 1):\n",
" summary = summarize_current_summary(document, instruction, summary, model)\n",
" return summary\n",
"\n",
"\n",
"@opik.track\n",
"def final_summary(instruction: str, current_summary: str, model: str = \"gpt-4o-mini\"):\n",
" prompt = FINAL_SUMMARY_PROMPT.format(\n",
" current_summary=current_summary, instruction=instruction\n",
" )\n",
"\n",
" return (\n",
" openai_client.chat.completions.create(\n",
" model=model, max_tokens=4096, messages=[{\"role\": \"user\", \"content\": prompt}]\n",
" )\n",
" .choices[0]\n",
" .message.content\n",
" )\n",
"\n",
"\n",
"@opik.track(project_name=\"Chain of Density Summarization\")\n",
"def chain_of_density_summarization(\n",
" document: str,\n",
" instruction: str,\n",
" model: str = \"gpt-4o-mini\",\n",
" density_iterations: int = 2,\n",
"):\n",
" summary = iterative_density_summarization(\n",
" document, instruction, density_iterations, model\n",
" )\n",
" final_summary_text = final_summary(instruction, summary, model)\n",
"\n",
" return final_summary_text"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's call the summarization chain with a sample document:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import textwrap\n",
"\n",
"document = \"\"\"\n",
"Artificial intelligence (AI) is transforming industries, revolutionizing healthcare, finance, education, and even creative fields. AI systems\n",
"today are capable of performing tasks that previously required human intelligence, such as language processing, visual perception, and\n",
"decision-making. In healthcare, AI assists in diagnosing diseases, predicting patient outcomes, and even developing personalized treatment plans.\n",
"In finance, it helps in fraud detection, algorithmic trading, and risk management. Education systems leverage AI for personalized learning, adaptive\n",
"testing, and educational content generation. Despite these advancements, ethical concerns such as data privacy, bias, and the impact of AI on employment\n",
"remain. The future of AI holds immense potential, but also significant challenges.\n",
"\"\"\"\n",
"\n",
"instruction = \"Summarize the main contributions of AI to different industries, and highlight both its potential and associated challenges.\"\n",
"\n",
"summary = chain_of_density_summarization(document, instruction)\n",
"\n",
"print(\"\\n\".join(textwrap.wrap(summary, width=80)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Thanks to the `@opik.track` decorator and Opik's integration with OpenAI, we can now track the entire chain and all the LLM calls in the Opik UI:\n",
"\n",
"![Trace UI](https://raw.githubusercontent.com/comet-ml/opik/main/apps/opik-documentation/documentation/static/img/cookbook/chain_density_trace_cookbook.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Automatting the evaluation process\n",
"\n",
"### Defining a dataset\n",
"Now that we have a working chain, we can automate the evaluation process. We will start by defining a dataset of documents and instructions:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import opik\n",
"\n",
"dataset_items = [\n",
" {\n",
" \"pdf_url\": \"https://arxiv.org/pdf/2301.00234\",\n",
" \"title\": \"A Survey on In-context Learning\",\n",
" \"instruction\": \"Summarize the key findings on the impact of prompt engineering in in-context learning.\",\n",
" },\n",
" {\n",
" \"pdf_url\": \"https://arxiv.org/pdf/2301.03728\",\n",
" \"title\": \"Scaling Laws for Generative Mixed-Modal Language Models\",\n",
" \"instruction\": \"How do scaling laws apply to generative mixed-modal models according to the paper?\",\n",
" },\n",
" {\n",
" \"pdf_url\": \"https://arxiv.org/pdf/2308.10792\",\n",
" \"title\": \"Instruction Tuning for Large Language Models: A Survey\",\n",
" \"instruction\": \"What are the major challenges in instruction tuning for large language models identified in the paper?\",\n",
" },\n",
" {\n",
" \"pdf_url\": \"https://arxiv.org/pdf/2302.08575\",\n",
" \"title\": \"Foundation Models in Natural Language Processing: A Survey\",\n",
" \"instruction\": \"Explain the role of foundation models in the current natural language processing landscape.\",\n",
" },\n",
" {\n",
" \"pdf_url\": \"https://arxiv.org/pdf/2306.13398\",\n",
" \"title\": \"Large-scale Multi-Modal Pre-trained Models: A Comprehensive Survey\",\n",
" \"instruction\": \"What are the cutting edge techniques used in multi-modal pre-training models?\",\n",
" },\n",
" {\n",
" \"pdf_url\": \"https://arxiv.org/pdf/2103.07492\",\n",
" \"title\": \"Continual Learning in Neural Networks: An Empirical Evaluation\",\n",
" \"instruction\": \"What are the main challenges of continual learning for neural networks according to the paper?\",\n",
" },\n",
" {\n",
" \"pdf_url\": \"https://arxiv.org/pdf/2304.00685v2\",\n",
" \"title\": \"Vision-Language Models for Vision Tasks: A Survey\",\n",
" \"instruction\": \"What are the most widely used vision-language models?\",\n",
" },\n",
" {\n",
" \"pdf_url\": \"https://arxiv.org/pdf/2303.08774\",\n",
" \"title\": \"GPT-4 Technical Report\",\n",
" \"instruction\": \"What are the main differences between GPT-4 and GPT-3.5?\",\n",
" },\n",
" {\n",
" \"pdf_url\": \"https://arxiv.org/pdf/2406.04744\",\n",
" \"title\": \"CRAG -- Comprehensive RAG Benchmark\",\n",
" \"instruction\": \"What was the approach to experimenting with different data mixtures?\",\n",
" },\n",
"]\n",
"\n",
"client = opik.Opik()\n",
"DATASET_NAME = \"arXiv Papers\"\n",
"dataset = client.get_or_create_dataset(name=DATASET_NAME)\n",
"dataset.insert(dataset_items)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"*Note:* Opik automatically deduplicates dataset items to make it easier to iterate on your dataset.\n",
"\n",
"### Defining the evaluation metrics\n",
"\n",
"Opik includes a [library of evaluation metrics](https://www.comet.com/docs/opik/evaluation/metrics/overview) that you can use to evaluate your chains. For this particular example, we will be using a custom metric that evaluates the relevance, conciseness and technical accuracy of each summary"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from opik.evaluation.metrics import base_metric, score_result\n",
"import json\n",
"\n",
"# We will define the response format so the output has the correct schema. You can also use structured outputs with Pydantic models for this.\n",
"json_schema = {\n",
" \"type\": \"json_schema\",\n",
" \"json_schema\": {\n",
" \"name\": \"summary_evaluation_schema\",\n",
" \"schema\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"relevance\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"score\": {\n",
" \"type\": \"integer\",\n",
" \"minimum\": 1,\n",
" \"maximum\": 5,\n",
" \"description\": \"Score between 1-5 for how well the summary addresses the instruction\",\n",
" },\n",
" \"explanation\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Brief explanation of the relevance score\",\n",
" },\n",
" },\n",
" \"required\": [\"score\", \"explanation\"],\n",
" },\n",
" \"conciseness\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"score\": {\n",
" \"type\": \"integer\",\n",
" \"minimum\": 1,\n",
" \"maximum\": 5,\n",
" \"description\": \"Score between 1-5 for how concise the summary is while retaining key information\",\n",
" },\n",
" \"explanation\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Brief explanation of the conciseness score\",\n",
" },\n",
" },\n",
" \"required\": [\"score\", \"explanation\"],\n",
" },\n",
" \"technical_accuracy\": {\n",
" \"type\": \"object\",\n",
" \"properties\": {\n",
" \"score\": {\n",
" \"type\": \"integer\",\n",
" \"minimum\": 1,\n",
" \"maximum\": 5,\n",
" \"description\": \"Score between 1-5 for how accurately the summary conveys technical details\",\n",
" },\n",
" \"explanation\": {\n",
" \"type\": \"string\",\n",
" \"description\": \"Brief explanation of the technical accuracy score\",\n",
" },\n",
" },\n",
" \"required\": [\"score\", \"explanation\"],\n",
" },\n",
" },\n",
" \"required\": [\"relevance\", \"conciseness\", \"technical_accuracy\"],\n",
" \"additionalProperties\": False,\n",
" },\n",
" },\n",
"}\n",
"\n",
"\n",
"# Custom Metric: One template/prompt to extract 4 scores/results\n",
"class EvaluateSummary(base_metric.BaseMetric):\n",
" # Constructor\n",
" def __init__(self, name: str):\n",
" self.name = name\n",
"\n",
" def score(\n",
" self, summary: str, instruction: str, model: str = \"gpt-4o-mini\", **kwargs\n",
" ):\n",
" prompt = f\"\"\"\n",
" Summary: {summary}\n",
" Instruction: {instruction}\n",
"\n",
" Evaluate the summary based on the following criteria:\n",
" 1. Relevance (1-5): How well does the summary address the given instruction?\n",
" 2. Conciseness (1-5): How concise is the summary while retaining key information?\n",
" 3. Technical Accuracy (1-5): How accurately does the summary convey technical details?\n",
"\n",
" Your response MUST be in the following JSON format:\n",
" {{\n",
" \"relevance\": {{\n",
" \"score\": <int>,\n",
" \"explanation\": \"<string>\"\n",
" }},\n",
" \"conciseness\": {{\n",
" \"score\": <int>,\n",
" \"explanation\": \"<string>\"\n",
" }},\n",
" \"technical_accuracy\": {{\n",
" \"score\": <int>,\n",
" \"explanation\": \"<string>\"\n",
" }}\n",
" }}\n",
"\n",
" Ensure that the scores are integers between 1 and 5, and that the explanations are concise.\n",
" \"\"\"\n",
"\n",
" response = openai_client.chat.completions.create(\n",
" model=model,\n",
" max_tokens=1000,\n",
" messages=[{\"role\": \"user\", \"content\": prompt}],\n",
" response_format=json_schema,\n",
" )\n",
"\n",
" eval_dict = json.loads(response.choices[0].message.content)\n",
"\n",
" return [\n",
" score_result.ScoreResult(\n",
" name=\"summary_relevance\",\n",
" value=eval_dict[\"relevance\"][\"score\"],\n",
" reason=eval_dict[\"relevance\"][\"explanation\"],\n",
" ),\n",
" score_result.ScoreResult(\n",
" name=\"summary_conciseness\",\n",
" value=eval_dict[\"conciseness\"][\"score\"],\n",
" reason=eval_dict[\"conciseness\"][\"explanation\"],\n",
" ),\n",
" score_result.ScoreResult(\n",
" name=\"summary_technical_accuracy\",\n",
" value=eval_dict[\"technical_accuracy\"][\"score\"],\n",
" reason=eval_dict[\"technical_accuracy\"][\"explanation\"],\n",
" ),\n",
" score_result.ScoreResult(\n",
" name=\"summary_average_score\",\n",
" value=round(sum(eval_dict[k][\"score\"] for k in eval_dict) / 3, 2),\n",
" reason=\"The average of the 3 summary evaluation metrics\",\n",
" ),\n",
" ]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create the task we want to evaluate\n",
"\n",
"We can now create the task we want to evaluate. In this case, we will have the dataset item as an input and return a dictionary containing the summary and the instruction so that we can use this in the evaluation metrics:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"import io\n",
"from PyPDF2 import PdfReader\n",
"from typing import Dict\n",
"\n",
"\n",
"# Load and extract text from PDFs\n",
"@opik.track\n",
"def load_pdf(pdf_url: str) -> str:\n",
" # Download the PDF\n",
" response = requests.get(pdf_url)\n",
" pdf_file = io.BytesIO(response.content)\n",
"\n",
" # Read the PDF\n",
" pdf_reader = PdfReader(pdf_file)\n",
"\n",
" # Extract text from all pages\n",
" text = \"\"\n",
" for page in pdf_reader.pages:\n",
" text += page.extract_text()\n",
"\n",
" # Truncate the text to 100000 characters as this is the maximum supported by OpenAI\n",
" text = text[:100000]\n",
" return text\n",
"\n",
"\n",
"def evaluation_task(x: Dict):\n",
" text = load_pdf(x[\"pdf_url\"])\n",
" instruction = x[\"instruction\"]\n",
" model = MODEL\n",
" density_iterations = DENSITY_ITERATIONS\n",
"\n",
" result = chain_of_density_summarization(\n",
" document=text,\n",
" instruction=instruction,\n",
" model=model,\n",
" density_iterations=density_iterations,\n",
" )\n",
"\n",
" return {\"summary\": result}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Run the automated evaluation"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now use the `evaluate` method to evaluate the summaries in our dataset:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from opik.evaluation import evaluate\n",
"\n",
"MODEL = \"gpt-4o-mini\"\n",
"DENSITY_ITERATIONS = 2\n",
"\n",
"experiment_config = {\n",
" \"model\": MODEL,\n",
" \"density_iterations\": DENSITY_ITERATIONS,\n",
"}\n",
"\n",
"res = evaluate(\n",
" dataset=dataset,\n",
" experiment_config=experiment_config,\n",
" task=evaluation_task,\n",
" scoring_metrics=[EvaluateSummary(name=\"summary-metrics\")],\n",
" prompts=[ITERATION_SUMMARY_PROMPT, FINAL_SUMMARY_PROMPT],\n",
" project_name=\"Chain of Density Summarization - Experiments\",\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The experiment results are now available in the Opik UI:\n",
"\n",
"![Trace UI](https://raw.githubusercontent.com/comet-ml/opik/main/apps/opik-documentation/documentation/static/img/cookbook/chain_density_experiment_cookbook.png)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Comparing prompt templates\n",
"\n",
"We will update the iteration summary prompt and evaluate its impact on the evaluation metrics."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import opik\n",
"\n",
"ITERATION_SUMMARY_PROMPT = opik.Prompt(\n",
" name=\"Iteration Summary Prompt\",\n",
" prompt=\"\"\"Document: {{document}}\n",
"Current summary: {{current_summary}}\n",
"Instruction to focus on: {{instruction}}\n",
"\n",
"Generate a concise, entity-dense, and highly technical summary from the provided Document that specifically addresses the given Instruction.\n",
"\n",
"Guidelines:\n",
"1. **Maximize Clarity and Density**: Revise the current summary to enhance flow, density, and conciseness.\n",
"2. **Eliminate Redundant Language**: Avoid uninformative phrases such as \"the article discusses.\"\n",
"3. **Ensure Self-Containment**: The summary should be dense and concise, easily understandable without referring back to the document.\n",
"4. **Align with Instruction**: Make sure the summary specifically addresses the given instruction.\n",
"\n",
"\"\"\".rstrip().lstrip(),\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from opik.evaluation import evaluate\n",
"\n",
"MODEL = \"gpt-4o-mini\"\n",
"DENSITY_ITERATIONS = 2\n",
"\n",
"experiment_config = {\n",
" \"model\": MODEL,\n",
" \"density_iterations\": DENSITY_ITERATIONS,\n",
"}\n",
"\n",
"res = evaluate(\n",
" dataset=dataset,\n",
" experiment_config=experiment_config,\n",
" task=evaluation_task,\n",
" scoring_metrics=[EvaluateSummary(name=\"summary-metrics\")],\n",
" prompts=[ITERATION_SUMMARY_PROMPT, FINAL_SUMMARY_PROMPT],\n",
" project_name=\"Chain of Density Summarization - Experiments\",\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can now compare the results between the two experiments in the Opik UI:\n",
"\n",
"![Trace UI](https://raw.githubusercontent.com/comet-ml/opik/main/apps/opik-documentation/documentation/static/img/cookbook/chain_density_trace_comparison_cookbook.png)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "py312_llm_eval",
"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.12.4"
}
},
"nbformat": 4,
"nbformat_minor": 4
}