{ "cells": [ { "cell_type": "code", "execution_count": 2, "id": "c95ab233", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Adding package root to sys.path: /home/mafzaal/source/lets-talk/py-src\n", "Current notebook directory: /home/mafzaal/source/lets-talk/py-src/notebooks\n", "Project root: /home/mafzaal/source/lets-talk\n" ] } ], "source": [ "import sys\n", "import os\n", "\n", "# Add the project root to the Python path\n", "package_root = os.path.abspath(os.path.join(os.getcwd(), \"../\"))\n", "print(f\"Adding package root to sys.path: {package_root}\")\n", "if package_root not in sys.path:\n", "\tsys.path.append(package_root)\n", "\n", "\n", "notebook_dir = os.getcwd()\n", "print(f\"Current notebook directory: {notebook_dir}\")\n", "# change to the directory to the root of the project\n", "project_root = os.path.abspath(os.path.join(os.getcwd(), \"../../\"))\n", "print(f\"Project root: {project_root}\")\n", "os.chdir(project_root)" ] }, { "cell_type": "code", "execution_count": 3, "id": "15e97530", "metadata": {}, "outputs": [], "source": [ "import nest_asyncio\n", "nest_asyncio.apply()" ] }, { "cell_type": "code", "execution_count": 5, "id": "b4f2ddc0", "metadata": {}, "outputs": [], "source": [ "import lets_talk.utils.blog as blog\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "123779af", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 14/14 [00:00<00:00, 3317.53it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Loaded 14 documents from data/\n", "Split 14 documents into 162 chunks\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "docs = blog.load_blog_posts()\n", "docs = blog.update_document_metadata(docs)\n", "split_docs = blog.split_documents(docs)" ] }, { "cell_type": "code", "execution_count": 7, "id": "0b742838", "metadata": {}, "outputs": [], "source": [ "from langchain_core.prompts import ChatPromptTemplate\n", "from langchain_openai import ChatOpenAI\n", "\n", "qa_chat_model = ChatOpenAI(\n", " model=\"gpt-4.1\",\n", " temperature=0,\n", ")\n", "\n", "qa_prompt = \"\"\"\\\n", "Given the following context, you must generate questions based on only the provided context.\n", "You are to generate {n_questions} questions which should be provided in the following format:\n", "\n", "1. QUESTION #1\n", "2. QUESTION #2\n", "...\n", "\n", "Context:\n", "{context}\n", "\"\"\"\n", "\n", "qa_prompt_template = ChatPromptTemplate.from_template(qa_prompt)\n", "\n", "question_generation_chain = qa_prompt_template | qa_chat_model" ] }, { "cell_type": "code", "execution_count": 18, "id": "5488c3d3", "metadata": {}, "outputs": [], "source": [ "import tqdm\n", "import asyncio\n", "\n", "\n", "def extract_questions(response_text,n_questions):\n", " # Split the response text into lines\n", " lines = response_text.strip().split('\\n')\n", "\n", " # Extract questions (format: \"1. QUESTION\")\n", " extracted_questions = []\n", " for line in lines:\n", " line = line.strip()\n", " if line and any(line.startswith(f\"{i}.\") for i in range(1, n_questions+1)):\n", " # Remove the number prefix and get just the question\n", " question = line.split('.', 1)[1].strip()\n", " extracted_questions.append(question)\n", "\n", " return extracted_questions\n", "\n", "def create_questions(documents, n_questions, chain):\n", " question_set = []\n", " \n", " for doc in tqdm.tqdm(documents):\n", " \n", " context = doc.page_content\n", "\n", " # Generate questions using the question generation chain\n", " response = chain.invoke({\n", " \"context\": context,\n", " \"n_questions\": n_questions\n", " })\n", "\n", " questions = extract_questions(response.content,n_questions)\n", " \n", " for i, question in enumerate(questions):\n", " question_set.append({\"question\":question, \"context\": context})\n", " \n", " return question_set" ] }, { "cell_type": "code", "execution_count": 19, "id": "b1ece53b", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 162/162 [07:23<00:00, 2.74s/it]\n" ] } ], "source": [ "ds = create_questions(documents=split_docs, n_questions=2, chain=question_generation_chain)" ] }, { "cell_type": "code", "execution_count": 20, "id": "965cf609", "metadata": {}, "outputs": [ { "data": { "application/vnd.microsoft.datawrangler.viewer.v0+json": { "columns": [ { "name": "index", "rawType": "int64", "type": "integer" }, { "name": "question", "rawType": "object", "type": "string" }, { "name": "context", "rawType": "object", "type": "string" } ], "conversionMethod": "pd.DataFrame", "ref": "f0615b27-42e5-4774-a436-51ec88bb4498", "rows": [ [ "0", "What role does Ragas play in evaluating the performance of applications that use Large Language Models (LLMs)?", "---\ntitle: \"Part 1: Introduction to Ragas: The Essential Evaluation Framework for LLM Applications\"\ndate: 2025-04-26T18:00:00-06:00\nlayout: blog\ndescription: \"Explore the essential evaluation framework for LLM applications with Ragas. Learn how to assess performance, ensure accuracy, and improve reliability in Retrieval-Augmented Generation systems.\"\ncategories: [\"AI\", \"RAG\", \"Evaluation\",\"Ragas\"]\ncoverImage: \"https://images.unsplash.com/photo-1593642634367-d91a135587b5?q=80&w=1770&auto=format&fit=crop&ixlib=rb-4.0.3\"\nreadingTime: 7\npublished: true\n---\n\nAs Large Language Models (LLMs) become fundamental components of modern applications, effectively evaluating their performance becomes increasingly critical. Whether you're building a question-answering system, a document retrieval tool, or a conversational agent, you need reliable metrics to assess how well your application performs. This is where Ragas steps in.\n\n## What is Ragas?" ], [ "1", "Why is it important to have reliable metrics when building systems like question-answering tools or conversational agents with LLMs?", "---\ntitle: \"Part 1: Introduction to Ragas: The Essential Evaluation Framework for LLM Applications\"\ndate: 2025-04-26T18:00:00-06:00\nlayout: blog\ndescription: \"Explore the essential evaluation framework for LLM applications with Ragas. Learn how to assess performance, ensure accuracy, and improve reliability in Retrieval-Augmented Generation systems.\"\ncategories: [\"AI\", \"RAG\", \"Evaluation\",\"Ragas\"]\ncoverImage: \"https://images.unsplash.com/photo-1593642634367-d91a135587b5?q=80&w=1770&auto=format&fit=crop&ixlib=rb-4.0.3\"\nreadingTime: 7\npublished: true\n---\n\nAs Large Language Models (LLMs) become fundamental components of modern applications, effectively evaluating their performance becomes increasingly critical. Whether you're building a question-answering system, a document retrieval tool, or a conversational agent, you need reliable metrics to assess how well your application performs. This is where Ragas steps in.\n\n## What is Ragas?" ], [ "2", "What are some of the key questions that Ragas helps answer when evaluating LLM applications?", "## What is Ragas?\n\n[Ragas](https://docs.ragas.io/en/stable/) is an open-source evaluation framework specifically designed for LLM applications, with particular strengths in Retrieval-Augmented Generation (RAG) systems. Unlike traditional NLP evaluation methods, Ragas provides specialized metrics that address the unique challenges of LLM-powered systems.\n\nAt its core, Ragas helps answer crucial questions:\n- Is my application retrieving the right information?\n- Are the responses factually accurate and consistent with the retrieved context?\n- Does the system appropriately address the user's query?\n- How well does my application handle multi-turn conversations?\n\n## Why Evaluate LLM Applications?\n\nLLMs are powerful but imperfect. They can hallucinate facts, misinterpret queries, or generate convincing but incorrect responses. For applications where accuracy and reliability matter—like healthcare, finance, or education—proper evaluation is non-negotiable." ], [ "3", "Why is proper evaluation especially important for LLM applications in fields like healthcare, finance, or education?", "## What is Ragas?\n\n[Ragas](https://docs.ragas.io/en/stable/) is an open-source evaluation framework specifically designed for LLM applications, with particular strengths in Retrieval-Augmented Generation (RAG) systems. Unlike traditional NLP evaluation methods, Ragas provides specialized metrics that address the unique challenges of LLM-powered systems.\n\nAt its core, Ragas helps answer crucial questions:\n- Is my application retrieving the right information?\n- Are the responses factually accurate and consistent with the retrieved context?\n- Does the system appropriately address the user's query?\n- How well does my application handle multi-turn conversations?\n\n## Why Evaluate LLM Applications?\n\nLLMs are powerful but imperfect. They can hallucinate facts, misinterpret queries, or generate convincing but incorrect responses. For applications where accuracy and reliability matter—like healthcare, finance, or education—proper evaluation is non-negotiable." ], [ "4", "What are the main purposes of evaluation as described in the context?", "Evaluation serves several key purposes:\n- **Quality assurance**: Identify and fix issues before they reach users\n- **Performance tracking**: Monitor how changes impact system performance\n- **Benchmarking**: Compare different approaches objectively\n- **Continuous improvement**: Build feedback loops to enhance your application\n\n## Key Features of Ragas\n\n### 🎯 Specialized Metrics\nRagas offers both LLM-based and computational metrics tailored to evaluate different aspects of LLM applications:\n\n- **Faithfulness**: Measures if the response is factually consistent with the retrieved context\n- **Context Relevancy**: Evaluates if the retrieved information is relevant to the query\n- **Answer Relevancy**: Assesses if the response addresses the user's question\n- **Topic Adherence**: Gauges how well multi-turn conversations stay on topic" ], [ "5", "Which specialized metrics does Ragas provide for evaluating LLM applications, and what does each metric measure?", "Evaluation serves several key purposes:\n- **Quality assurance**: Identify and fix issues before they reach users\n- **Performance tracking**: Monitor how changes impact system performance\n- **Benchmarking**: Compare different approaches objectively\n- **Continuous improvement**: Build feedback loops to enhance your application\n\n## Key Features of Ragas\n\n### 🎯 Specialized Metrics\nRagas offers both LLM-based and computational metrics tailored to evaluate different aspects of LLM applications:\n\n- **Faithfulness**: Measures if the response is factually consistent with the retrieved context\n- **Context Relevancy**: Evaluates if the retrieved information is relevant to the query\n- **Answer Relevancy**: Assesses if the response addresses the user's question\n- **Topic Adherence**: Gauges how well multi-turn conversations stay on topic" ], [ "6", "How does Ragas assist in the process of test data generation for evaluation?", "### 🧪 Test Data Generation\nCreating high-quality test data is often a bottleneck in evaluation. Ragas helps you generate comprehensive test datasets automatically, saving time and ensuring thorough coverage.\n\n### 🔗 Seamless Integrations\nRagas works with popular LLM frameworks and tools:\n- [LangChain](https://www.langchain.com/)\n- [LlamaIndex](https://www.llamaindex.ai/)\n- [Haystack](https://haystack.deepset.ai/)\n- [OpenAI](https://openai.com/)\n\nObservability platforms \n- [Phoenix](https://phoenix.arize.com/)\n- [LangSmith](https://python.langchain.com/docs/introduction/)\n- [Langfuse](https://www.langfuse.com/)\n\n### 📊 Comprehensive Analysis\nBeyond simple scores, Ragas provides detailed insights into your application's strengths and weaknesses, enabling targeted improvements.\n\n## Getting Started with Ragas\n\nInstalling Ragas is straightforward:\n\n```bash\nuv init && uv add ragas\n```\n\nHere's a simple example of evaluating a response using Ragas:" ], [ "7", "Which popular LLM frameworks and observability platforms does Ragas integrate with?", "### 🧪 Test Data Generation\nCreating high-quality test data is often a bottleneck in evaluation. Ragas helps you generate comprehensive test datasets automatically, saving time and ensuring thorough coverage.\n\n### 🔗 Seamless Integrations\nRagas works with popular LLM frameworks and tools:\n- [LangChain](https://www.langchain.com/)\n- [LlamaIndex](https://www.llamaindex.ai/)\n- [Haystack](https://haystack.deepset.ai/)\n- [OpenAI](https://openai.com/)\n\nObservability platforms \n- [Phoenix](https://phoenix.arize.com/)\n- [LangSmith](https://python.langchain.com/docs/introduction/)\n- [Langfuse](https://www.langfuse.com/)\n\n### 📊 Comprehensive Analysis\nBeyond simple scores, Ragas provides detailed insights into your application's strengths and weaknesses, enabling targeted improvements.\n\n## Getting Started with Ragas\n\nInstalling Ragas is straightforward:\n\n```bash\nuv init && uv add ragas\n```\n\nHere's a simple example of evaluating a response using Ragas:" ], [ "8", "What command is used to install Ragas according to the provided context?", "## Getting Started with Ragas\n\nInstalling Ragas is straightforward:\n\n```bash\nuv init && uv add ragas\n```\n\nHere's a simple example of evaluating a response using Ragas:\n\n```python\nfrom ragas.metrics import Faithfulness\nfrom ragas.evaluation import EvaluationDataset\nfrom ragas.dataset_schema import SingleTurnSample\nfrom langchain_openai import ChatOpenAI\nfrom ragas.llms import LangchainLLMWrapper\nfrom langchain_openai import ChatOpenAI\n\n# Initialize the LLM, you are going to new OPENAI API key\nevaluator_llm = LangchainLLMWrapper(ChatOpenAI(model=\"gpt-4o\")) \n\n# Your evaluation data\ntest_data = {\n \"user_input\": \"What is the capital of France?\",\n \"retrieved_contexts\": [\"Paris is the capital and most populous city of France.\"],\n \"response\": \"The capital of France is Paris.\"\n}\n\n# Create a sample\nsample = SingleTurnSample(**test_data) # Unpack the dictionary into the constructor" ], [ "9", "In the example, which class is used to wrap the ChatOpenAI model for evaluation purposes?", "## Getting Started with Ragas\n\nInstalling Ragas is straightforward:\n\n```bash\nuv init && uv add ragas\n```\n\nHere's a simple example of evaluating a response using Ragas:\n\n```python\nfrom ragas.metrics import Faithfulness\nfrom ragas.evaluation import EvaluationDataset\nfrom ragas.dataset_schema import SingleTurnSample\nfrom langchain_openai import ChatOpenAI\nfrom ragas.llms import LangchainLLMWrapper\nfrom langchain_openai import ChatOpenAI\n\n# Initialize the LLM, you are going to new OPENAI API key\nevaluator_llm = LangchainLLMWrapper(ChatOpenAI(model=\"gpt-4o\")) \n\n# Your evaluation data\ntest_data = {\n \"user_input\": \"What is the capital of France?\",\n \"retrieved_contexts\": [\"Paris is the capital and most populous city of France.\"],\n \"response\": \"The capital of France is Paris.\"\n}\n\n# Create a sample\nsample = SingleTurnSample(**test_data) # Unpack the dictionary into the constructor" ] ], "shape": { "columns": 2, "rows": 10 } }, "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
questioncontext
0What role does Ragas play in evaluating the pe...---\\ntitle: \"Part 1: Introduction to Ragas: Th...
1Why is it important to have reliable metrics w...---\\ntitle: \"Part 1: Introduction to Ragas: Th...
2What are some of the key questions that Ragas ...## What is Ragas?\\n\\n[Ragas](https://docs.raga...
3Why is proper evaluation especially important ...## What is Ragas?\\n\\n[Ragas](https://docs.raga...
4What are the main purposes of evaluation as de...Evaluation serves several key purposes:\\n- **Q...
5Which specialized metrics does Ragas provide f...Evaluation serves several key purposes:\\n- **Q...
6How does Ragas assist in the process of test d...### 🧪 Test Data Generation\\nCreating high-qual...
7Which popular LLM frameworks and observability...### 🧪 Test Data Generation\\nCreating high-qual...
8What command is used to install Ragas accordin...## Getting Started with Ragas\\n\\nInstalling Ra...
9In the example, which class is used to wrap th...## Getting Started with Ragas\\n\\nInstalling Ra...
\n", "
" ], "text/plain": [ " question \\\n", "0 What role does Ragas play in evaluating the pe... \n", "1 Why is it important to have reliable metrics w... \n", "2 What are some of the key questions that Ragas ... \n", "3 Why is proper evaluation especially important ... \n", "4 What are the main purposes of evaluation as de... \n", "5 Which specialized metrics does Ragas provide f... \n", "6 How does Ragas assist in the process of test d... \n", "7 Which popular LLM frameworks and observability... \n", "8 What command is used to install Ragas accordin... \n", "9 In the example, which class is used to wrap th... \n", "\n", " context \n", "0 ---\\ntitle: \"Part 1: Introduction to Ragas: Th... \n", "1 ---\\ntitle: \"Part 1: Introduction to Ragas: Th... \n", "2 ## What is Ragas?\\n\\n[Ragas](https://docs.raga... \n", "3 ## What is Ragas?\\n\\n[Ragas](https://docs.raga... \n", "4 Evaluation serves several key purposes:\\n- **Q... \n", "5 Evaluation serves several key purposes:\\n- **Q... \n", "6 ### 🧪 Test Data Generation\\nCreating high-qual... \n", "7 ### 🧪 Test Data Generation\\nCreating high-qual... \n", "8 ## Getting Started with Ragas\\n\\nInstalling Ra... \n", "9 ## Getting Started with Ragas\\n\\nInstalling Ra... " ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "df = pd.DataFrame(ds)\n", "df.head(10)" ] }, { "cell_type": "code", "execution_count": 21, "id": "b8c025fa", "metadata": {}, "outputs": [], "source": [ "df.to_csv(\"evals/ft_questions.csv\", index=False)" ] }, { "cell_type": "code", "execution_count": null, "id": "eca8e3c8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Dataset has 324 examples\n", "Dataset features: {'question': Value(dtype='string', id=None), 'context': Value(dtype='string', id=None)}\n", "\n", "Sample examples:\n" ] }, { "data": { "application/vnd.microsoft.datawrangler.viewer.v0+json": { "columns": [ { "name": "index", "rawType": "int64", "type": "integer" }, { "name": "question", "rawType": "object", "type": "string" }, { "name": "context", "rawType": "object", "type": "string" } ], "conversionMethod": "pd.DataFrame", "ref": "c895ca53-ec90-48b0-a20e-13957de25913", "rows": [ [ "0", "What role does Ragas play in evaluating the performance of applications that use Large Language Models (LLMs)?", "---\ntitle: \"Part 1: Introduction to Ragas: The Essential Evaluation Framework for LLM Applications\"\ndate: 2025-04-26T18:00:00-06:00\nlayout: blog\ndescription: \"Explore the essential evaluation framework for LLM applications with Ragas. Learn how to assess performance, ensure accuracy, and improve reliability in Retrieval-Augmented Generation systems.\"\ncategories: [\"AI\", \"RAG\", \"Evaluation\",\"Ragas\"]\ncoverImage: \"https://images.unsplash.com/photo-1593642634367-d91a135587b5?q=80&w=1770&auto=format&fit=crop&ixlib=rb-4.0.3\"\nreadingTime: 7\npublished: true\n---\n\nAs Large Language Models (LLMs) become fundamental components of modern applications, effectively evaluating their performance becomes increasingly critical. Whether you're building a question-answering system, a document retrieval tool, or a conversational agent, you need reliable metrics to assess how well your application performs. This is where Ragas steps in.\n\n## What is Ragas?" ], [ "1", "Why is it important to have reliable metrics when building systems like question-answering tools or conversational agents with LLMs?", "---\ntitle: \"Part 1: Introduction to Ragas: The Essential Evaluation Framework for LLM Applications\"\ndate: 2025-04-26T18:00:00-06:00\nlayout: blog\ndescription: \"Explore the essential evaluation framework for LLM applications with Ragas. Learn how to assess performance, ensure accuracy, and improve reliability in Retrieval-Augmented Generation systems.\"\ncategories: [\"AI\", \"RAG\", \"Evaluation\",\"Ragas\"]\ncoverImage: \"https://images.unsplash.com/photo-1593642634367-d91a135587b5?q=80&w=1770&auto=format&fit=crop&ixlib=rb-4.0.3\"\nreadingTime: 7\npublished: true\n---\n\nAs Large Language Models (LLMs) become fundamental components of modern applications, effectively evaluating their performance becomes increasingly critical. Whether you're building a question-answering system, a document retrieval tool, or a conversational agent, you need reliable metrics to assess how well your application performs. This is where Ragas steps in.\n\n## What is Ragas?" ], [ "2", "What are some of the key questions that Ragas helps answer when evaluating LLM applications?", "## What is Ragas?\n\n[Ragas](https://docs.ragas.io/en/stable/) is an open-source evaluation framework specifically designed for LLM applications, with particular strengths in Retrieval-Augmented Generation (RAG) systems. Unlike traditional NLP evaluation methods, Ragas provides specialized metrics that address the unique challenges of LLM-powered systems.\n\nAt its core, Ragas helps answer crucial questions:\n- Is my application retrieving the right information?\n- Are the responses factually accurate and consistent with the retrieved context?\n- Does the system appropriately address the user's query?\n- How well does my application handle multi-turn conversations?\n\n## Why Evaluate LLM Applications?\n\nLLMs are powerful but imperfect. They can hallucinate facts, misinterpret queries, or generate convincing but incorrect responses. For applications where accuracy and reliability matter—like healthcare, finance, or education—proper evaluation is non-negotiable." ] ], "shape": { "columns": 2, "rows": 3 } }, "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
questioncontext
0What role does Ragas play in evaluating the pe...---\\ntitle: \"Part 1: Introduction to Ragas: Th...
1Why is it important to have reliable metrics w...---\\ntitle: \"Part 1: Introduction to Ragas: Th...
2What are some of the key questions that Ragas ...## What is Ragas?\\n\\n[Ragas](https://docs.raga...
\n", "
" ], "text/plain": [ " question \\\n", "0 What role does Ragas play in evaluating the pe... \n", "1 Why is it important to have reliable metrics w... \n", "2 What are some of the key questions that Ragas ... \n", "\n", " context \n", "0 ---\\ntitle: \"Part 1: Introduction to Ragas: Th... \n", "1 ---\\ntitle: \"Part 1: Introduction to Ragas: Th... \n", "2 ## What is Ragas?\\n\\n[Ragas](https://docs.raga... " ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "dddd54d430094f5a906d9483abf892e4", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Saving the dataset (0/1 shards): 0%| | 0/324 [00:00