instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Help me add docstrings to my project
import asyncio import importlib.util import sys import traceback from collections import Counter from pathlib import Path from typing import Any, Dict, Optional import typer from rich.live import Live from rich.panel import Panel from rich.spinner import Spinner from rich.table import Table from rich.text import Text...
--- +++ @@ -1,3 +1,6 @@+""" +Ragas CLI for running experiments from command line. +""" import asyncio import importlib.util @@ -23,29 +26,35 @@ # Create a callback for the main app to make it a group @app.callback() def main(): + """Ragas CLI for running LLM evaluations""" pass # Rich utility functio...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/cli.py
Improve my code by adding docstrings
import asyncio import logging import typing as t logger = logging.getLogger(__name__) def is_event_loop_running() -> bool: try: loop = asyncio.get_running_loop() except RuntimeError: return False else: return loop.is_running() def apply_nest_asyncio() -> bool: if not is_eve...
--- +++ @@ -1,3 +1,4 @@+"""Async utils.""" import asyncio import logging @@ -7,6 +8,9 @@ def is_event_loop_running() -> bool: + """ + Check if an event loop is currently running. + """ try: loop = asyncio.get_running_loop() except RuntimeError: @@ -16,6 +20,12 @@ def apply_nest_a...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/async_utils.py
Write docstrings that follow conventions
import csv import typing as t from pathlib import Path from pydantic import BaseModel from .base import BaseBackend class LocalCSVBackend(BaseBackend): def __init__( self, root_dir: str, ): self.root_dir = Path(root_dir) def _get_data_dir(self, data_type: str) -> Path: ...
--- +++ @@ -1,3 +1,4 @@+"""Local CSV backend implementation for projects and datasets.""" import csv import typing as t @@ -9,6 +10,34 @@ class LocalCSVBackend(BaseBackend): + """File-based backend using CSV format for local storage. + + Stores datasets and experiments as CSV files in separate subdirector...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/backends/local_csv.py
Add docstrings for production code
import json import logging import os import typing as t from pydantic import BaseModel try: from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials as UserCredentials from google.oauth2.service_account import Credentials from google_auth_oauthlib.flow impo...
--- +++ @@ -1,3 +1,4 @@+"""Google Drive backend for storing datasets and experiments in Google Sheets.""" import json import logging @@ -35,6 +36,36 @@ class GDriveBackend(BaseBackend): + """Backend for storing datasets and experiments in Google Drive using Google Sheets. + + This backend stores datasets ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/backends/gdrive_backend.py
Can you add docstrings to this Python file?
import logging import typing as t from importlib import metadata from .base import BaseBackend logger = logging.getLogger(__name__) class BackendRegistry: _instance = None _backends: t.Dict[str, t.Type[BaseBackend]] = {} _aliases: t.Dict[str, str] = {} _discovered = False def __new__(cls): ...
--- +++ @@ -1,3 +1,4 @@+"""Backend registry for managing and discovering project backends.""" import logging import typing as t @@ -9,6 +10,7 @@ class BackendRegistry: + """Registry for managing project backends with plugin support.""" _instance = None _backends: t.Dict[str, t.Type[BaseBackend]] ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/backends/registry.py
Write docstrings including parameters and return values
import typing as t from abc import ABC, abstractmethod from pydantic import BaseModel class BaseBackend(ABC): @abstractmethod def load_dataset(self, name: str) -> t.List[t.Dict[str, t.Any]]: pass @abstractmethod def load_experiment(self, name: str) -> t.List[t.Dict[str, t.Any]]: pa...
--- +++ @@ -1,3 +1,4 @@+"""Base classes for project and dataset backends.""" import typing as t from abc import ABC, abstractmethod @@ -6,13 +7,79 @@ class BaseBackend(ABC): + """Abstract base class for dataset and experiment storage backends. + + Backends provide persistent storage for datasets and exper...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/backends/base.py
Add clean documentation to messy code
from __future__ import annotations class RagasException(Exception): def __init__(self, message: str): self.message = message super().__init__(message) class ExceptionInRunner(RagasException): def __init__(self): msg = "The runner thread which was running the jobs raised an execepti...
--- +++ @@ -2,6 +2,9 @@ class RagasException(Exception): + """ + Base exception class for ragas. + """ def __init__(self, message: str): self.message = message @@ -9,6 +12,9 @@ class ExceptionInRunner(RagasException): + """ + Exception raised when an exception is raised in the exe...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/exceptions.py
Document functions with clear intent
import typing as t from ragas._analytics import EmbeddingUsageEvent, track from ragas.cache import CacheInterface from .base import BaseRagasEmbedding from .utils import validate_texts class OpenAIEmbeddings(BaseRagasEmbedding): PROVIDER_NAME = "openai" REQUIRES_CLIENT = True DEFAULT_MODEL = "text-embe...
--- +++ @@ -8,6 +8,11 @@ class OpenAIEmbeddings(BaseRagasEmbedding): + """OpenAI embeddings implementation with batch optimization. + + Supports both sync and async OpenAI clients with automatic detection. + Provides optimized batch processing for better performance. + """ PROVIDER_NAME = "openai...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/embeddings/openai_provider.py
Generate consistent documentation across files
import sys import typing as t from ragas.cache import CacheInterface from .base import BaseRagasEmbedding from .utils import run_sync_in_async, validate_texts class GoogleEmbeddings(BaseRagasEmbedding): PROVIDER_NAME = "google" REQUIRES_CLIENT = False # Client is optional for Gemini (can auto-import) ...
--- +++ @@ -1,3 +1,4 @@+"""Google embeddings implementation supporting both Vertex AI and Google AI (Gemini).""" import sys import typing as t @@ -9,6 +10,37 @@ class GoogleEmbeddings(BaseRagasEmbedding): + """Google embeddings using Vertex AI or Google AI (Gemini). + + Supports both Vertex AI and Google ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/embeddings/google_provider.py
Add concise docstrings to each method
from __future__ import annotations import atexit import json import logging import os import time import typing as t import uuid from functools import lru_cache, wraps from threading import Lock, Thread from typing import List import requests from appdirs import user_data_dir from pydantic import BaseModel, Field fr...
--- +++ @@ -131,6 +131,13 @@ class AnalyticsBatcher: def __init__(self, batch_size: int = 50, flush_interval: float = 120): + """ + Initialize an AnalyticsBatcher instance. + + Args: + batch_size (int, optional): Maximum number of events to batch before flushing. Defaults to 50. +...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/_analytics.py
Generate missing documentation strings
import typing as t from copy import deepcopy from pydantic import BaseModel from .base import BaseBackend class InMemoryBackend(BaseBackend): def __init__(self): self._datasets: t.Dict[str, t.List[t.Dict[str, t.Any]]] = {} self._experiments: t.Dict[str, t.List[t.Dict[str, t.Any]]] = {} de...
--- +++ @@ -1,3 +1,4 @@+"""In-memory backend for temporary dataset and experiment storage.""" import typing as t from copy import deepcopy @@ -8,12 +9,44 @@ class InMemoryBackend(BaseBackend): + """Backend that stores datasets and experiments in memory. + + This backend is designed for temporary storage o...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/backends/inmemory.py
Generate docstrings with examples
from __future__ import annotations import random class MemorableNames: def __init__(self): # List of adjectives (similar to what Docker uses) self.adjectives = [ "admiring", "adoring", "affectionate", "agitated", "amazing", ...
--- +++ @@ -1,3 +1,4 @@+"""Shared utilities for project module.""" from __future__ import annotations @@ -5,6 +6,7 @@ class MemorableNames: + """Generator for memorable, unique names for experiments and datasets.""" def __init__(self): # List of adjectives (similar to what Docker uses) @@ -1...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/backends/utils.py
Help me document legacy Python code
import asyncio import threading import typing as t from concurrent.futures import ThreadPoolExecutor def run_async_in_current_loop(coro: t.Awaitable[t.Any]) -> t.Any: try: # Try to get the current event loop loop = asyncio.get_event_loop() if loop.is_running(): # If the loop ...
--- +++ @@ -1,3 +1,4 @@+"""Shared utilities for embedding implementations.""" import asyncio import threading @@ -6,6 +7,20 @@ def run_async_in_current_loop(coro: t.Awaitable[t.Any]) -> t.Any: + """Run an async coroutine in the current event loop if possible. + + This handles Jupyter environments correctl...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/embeddings/utils.py
Create docstrings for each class method
import typing as t from ragas.cache import CacheInterface from .base import BaseRagasEmbedding from .utils import batch_texts, run_sync_in_async, validate_texts class HuggingFaceEmbeddings(BaseRagasEmbedding): PROVIDER_NAME = "huggingface" REQUIRES_MODEL = True def __init__( self, mod...
--- +++ @@ -1,3 +1,4 @@+"""HuggingFace embeddings implementation supporting both local and API-based models.""" import typing as t @@ -8,6 +9,11 @@ class HuggingFaceEmbeddings(BaseRagasEmbedding): + """HuggingFace embeddings supporting both local and API-based models. + + Supports sentence-transformers f...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/embeddings/huggingface_provider.py
Document this module using docstrings
from __future__ import annotations import typing as t import warnings from uuid import UUID from datasets import Dataset from langchain_core.callbacks import BaseCallbackHandler, BaseCallbackManager from langchain_core.embeddings import Embeddings as LangchainEmbeddings from langchain_core.language_models import Base...
--- +++ @@ -75,6 +75,33 @@ _pbar: t.Optional[tqdm] = None, return_executor: bool = False, ) -> t.Union[EvaluationResult, Executor]: + """ + Async version of evaluate that performs evaluation without applying nest_asyncio. + + This function is the async-first implementation that doesn't patch the even...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/evaluation.py
Help me comply with documentation standards
from __future__ import annotations import logging import threading import typing as t from dataclasses import dataclass, field import numpy as np from tqdm.auto import tqdm from ragas.async_utils import apply_nest_asyncio, as_completed, process_futures, run from ragas.run_config import RunConfig from ragas.utils imp...
--- +++ @@ -17,6 +17,30 @@ @dataclass class Executor: + """ + Executor class for running asynchronous jobs with progress tracking and error handling. + + Attributes + ---------- + desc : str + Description for the progress bar + show_progress : bool + Whether to show the progress bar +...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/executor.py
Write docstrings for backend logic
from __future__ import annotations import asyncio import inspect import typing as t import warnings from abc import ABC, abstractmethod from dataclasses import field import numpy as np from langchain_core.embeddings import Embeddings from langchain_openai.embeddings import OpenAIEmbeddings from pydantic.dataclasses i...
--- +++ @@ -27,8 +27,20 @@ class BaseRagasEmbedding(ABC): + """Modern abstract base class for Ragas embedding implementations. + + This class provides a consistent interface for embedding text using various + providers. Implementations should provide both sync and async methods for + embedding single te...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/embeddings/base.py
Generate docstrings with parameter types
import functools import hashlib import inspect import json import logging import sys from abc import ABC, abstractmethod from typing import Any, Optional from pydantic import BaseModel, GetCoreSchemaHandler from pydantic_core import CoreSchema, core_schema logger = logging.getLogger(__name__) class CacheInterface(A...
--- +++ @@ -14,23 +14,53 @@ class CacheInterface(ABC): + """Abstract base class defining the interface for cache implementations. + + This class provides a standard interface that all cache implementations must follow. + It supports basic cache operations like get, set and key checking. + """ @ab...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/cache.py
Add docstrings to improve readability
from __future__ import annotations import typing as t from langchain.smith import RunEvalConfig from ragas.integrations.langchain import EvaluatorChain if t.TYPE_CHECKING: from langsmith.schemas import Dataset as LangsmithDataset from ragas.testset import Testset try: from langsmith import Client ...
--- +++ @@ -23,6 +23,37 @@ def upload_dataset( dataset: Testset, dataset_name: str, dataset_desc: str = "" ) -> LangsmithDataset: + """ + Uploads a new dataset to LangSmith, converting it from a TestDataset object to a + pandas DataFrame before upload. If a dataset with the specified name already + ex...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/integrations/langsmith.py
Add docstrings explaining edge cases
import json import typing as t from ragas.messages import AIMessage, HumanMessage def get_last_orchestration_value(traces: t.List[t.Dict[str, t.Any]], key: str): last_index = -1 last_value = None for i, trace in enumerate(traces): orchestration = trace.get("trace", {}).get("orchestrationTrace", {...
--- +++ @@ -5,6 +5,13 @@ def get_last_orchestration_value(traces: t.List[t.Dict[str, t.Any]], key: str): + """ + Iterates through the traces to find the last occurrence of a specified key + within the orchestrationTrace. + + Returns: + (index, value): Tuple where index is the last index at which ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/integrations/amazon_bedrock.py
Generate NumPy-style docstrings
__all__ = ["Experiment", "experiment", "version_experiment"] import asyncio import typing as t from pathlib import Path from pydantic import BaseModel from tqdm import tqdm from ragas.backends.base import BaseBackend from ragas.dataset import Dataset, DataTable from ragas.utils import find_git_root, memorable_names...
--- +++ @@ -1,3 +1,4 @@+"""Experiments hold the results of an experiment against a dataset.""" __all__ = ["Experiment", "experiment", "version_experiment"] @@ -24,6 +25,23 @@ create_branch: bool = True, stage_all: bool = False, ) -> str: + """Version control the current state of the codebase for an ex...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/experiment.py
Generate docstrings for each module
from __future__ import annotations import json import logging import typing as t import uuid from typing import Any, Dict, List, Optional, Union from ragas.dataset_schema import ( MultiTurnSample, SingleTurnSample, ) from ragas.messages import AIMessage, HumanMessage, ToolCall, ToolMessage logger = logging....
--- +++ @@ -1,3 +1,92 @@+""" +AG-UI Protocol Integration for Ragas. + +This module provides conversion utilities and row enrichment for AG-UI protocol +agents. It supports converting AG-UI streaming events to Ragas message format +and running rows against AG-UI FastAPI endpoints for use with the @experiment +decorator ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/integrations/ag_ui.py
Add docstrings including usage examples
import json from typing import Any, Dict, List, Union from ragas.messages import AIMessage, HumanMessage, ToolCall, ToolMessage def convert_to_ragas_messages( messages: List[Dict[str, Any]], ) -> List[Union[HumanMessage, AIMessage, ToolMessage]]: def convert_tool_calls(tool_calls_data: List[Dict[str, Any]])...
--- +++ @@ -7,8 +7,32 @@ def convert_to_ragas_messages( messages: List[Dict[str, Any]], ) -> List[Union[HumanMessage, AIMessage, ToolMessage]]: + """ + Convert Swarm messages to Ragas message format. + + Parameters + ---------- + messages : List[Union[Response, Dict]] + List of messages to c...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/integrations/swarm.py
Generate docstrings with examples
from __future__ import annotations import logging import typing as t import warnings from ragas.dataset_schema import EvaluationDataset if t.TYPE_CHECKING: pass logger = logging.getLogger(__name__) def _process_search_results(search_results: t.Dict[str, t.List]) -> t.List[str]: retrieved_contexts = [] ...
--- +++ @@ -14,6 +14,19 @@ def _process_search_results(search_results: t.Dict[str, t.List]) -> t.List[str]: + """ + Extracts relevant text from search results while issuing warnings for unsupported result types. + + Parameters + ---------- + search_results : Dict[str, List] + A r2r result obje...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/integrations/r2r.py
Generate documentation strings for clarity
from __future__ import annotations import json import random import typing as t from abc import ABC, abstractmethod from collections import defaultdict from dataclasses import dataclass, field from uuid import UUID import numpy as np from pydantic import BaseModel, field_validator from ragas.callbacks import parse_r...
--- +++ @@ -27,19 +27,61 @@ class BaseSample(BaseModel): + """ + Base class for evaluation samples. + """ def to_dict(self) -> t.Dict: + """ + Get the dictionary representation of the sample without attributes that are None. + """ return self.model_dump(exclude_none=Tru...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/dataset_schema.py
Generate docstrings for each module
__all__ = ["observe", "logger", "LangfuseTrace", "sync_trace", "add_query_param"] import asyncio import logging import typing as t from datetime import datetime from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse if t.TYPE_CHECKING: from langfuse import Langfuse, observe from langfuse.api imp...
--- +++ @@ -1,3 +1,4 @@+"""Utils to help to interact with langfuse traces""" __all__ = ["observe", "logger", "LangfuseTrace", "sync_trace", "add_query_param"] @@ -96,6 +97,16 @@ async def sync_trace( trace_id: t.Optional[str] = None, max_retries: int = 10, delay: float = 2 ) -> LangfuseTrace: + """Wait fo...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/integrations/tracing/langfuse.py
Fully document this Python code with docstrings
from __future__ import annotations import asyncio import inspect import logging import threading import typing as t from abc import ABC, abstractmethod from dataclasses import dataclass, field import instructor from langchain_community.chat_models.vertexai import ChatVertexAI from langchain_community.llms import Vert...
--- +++ @@ -46,6 +46,7 @@ def is_multiple_completion_supported(llm: BaseLanguageModel) -> bool: + """Return whether the given LLM supports n-completion.""" for llm_type in MULTIPLE_COMPLETION_SUPPORTED: if isinstance(llm, llm_type): return True @@ -68,6 +69,7 @@ self.run_config...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/llms/base.py
Add docstrings that explain logic
import typing as t from ragas.llms.adapters.base import StructuredOutputAdapter if t.TYPE_CHECKING: from ragas.llms.litellm_llm import LiteLLMStructuredLLM class LiteLLMAdapter(StructuredOutputAdapter): def create_llm( self, client: t.Any, model: str, provider: str, ...
--- +++ @@ -7,6 +7,11 @@ class LiteLLMAdapter(StructuredOutputAdapter): + """ + Adapter using LiteLLM for structured outputs. + + Supports: All 100+ LiteLLM providers (Gemini, Ollama, vLLM, Groq, etc.) + """ def create_llm( self, @@ -15,6 +20,18 @@ provider: str, **kwarg...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/llms/adapters/litellm.py
Create structured documentation for my script
import typing as t from abc import ABC, abstractmethod class StructuredOutputAdapter(ABC): @abstractmethod def create_llm( self, client: t.Any, model: str, provider: str, **kwargs, ) -> t.Any: pass
--- +++ @@ -3,6 +3,12 @@ class StructuredOutputAdapter(ABC): + """ + Base class for structured output adapters. + + Provides a simple interface for adapters that support structured output + from different backends (Instructor, LiteLLM, etc). + """ @abstractmethod def create_llm( @@ -12,4 ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/llms/adapters/base.py
Add minimal docstrings for each function
import typing as t from ragas.llms.adapters.base import StructuredOutputAdapter from ragas.llms.base import InstructorLLM, InstructorModelArgs, _get_instructor_client class InstructorAdapter(StructuredOutputAdapter): def create_llm( self, client: t.Any, model: str, provider: str,...
--- +++ @@ -5,6 +5,11 @@ class InstructorAdapter(StructuredOutputAdapter): + """ + Adapter using Instructor library for structured outputs. + + Supports: OpenAI, Anthropic, Azure, Groq, Mistral, Cohere, Google, etc. + """ def create_llm( self, @@ -13,6 +18,21 @@ provider: str, ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/llms/adapters/instructor.py
Create simple docstrings for beginners
import asyncio import inspect import logging import threading import typing as t from ragas._analytics import LLMUsageEvent, track from ragas.cache import CacheInterface, cacher from ragas.llms.base import InstructorBaseRagasLLM, InstructorTypeVar logger = logging.getLogger(__name__) class LiteLLMStructuredLLM(Inst...
--- +++ @@ -12,6 +12,14 @@ class LiteLLMStructuredLLM(InstructorBaseRagasLLM): + """ + LLM wrapper using LiteLLM for structured outputs. + + Works with all 100+ LiteLLM-supported providers including Gemini, + Ollama, vLLM, Groq, and many others. + + The LiteLLM client should be initialized with struc...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/llms/litellm_llm.py
Add missing documentation to my Python functions
import typing as t from abc import ABC, abstractmethod from pydantic import GetCoreSchemaHandler from pydantic_core import CoreSchema, core_schema class Loss(ABC): @abstractmethod def __call__(self, predicted: t.List, actual: t.List) -> float: raise NotImplementedError @classmethod def __ge...
--- +++ @@ -6,6 +6,9 @@ class Loss(ABC): + """ + Abstract base class for all loss functions. + """ @abstractmethod def __call__(self, predicted: t.List, actual: t.List) -> float: @@ -15,6 +18,9 @@ def __get_pydantic_core_schema__( cls, source_type: t.Any, handler: GetCoreSchemaHand...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/losses.py
Add docstrings explaining edge cases
import typing as t from ragas.llms.adapters.instructor import InstructorAdapter from ragas.llms.adapters.litellm import LiteLLMAdapter ADAPTERS = { "instructor": InstructorAdapter(), "litellm": LiteLLMAdapter(), } def get_adapter(name: str) -> t.Any: if name not in ADAPTERS: raise ValueError(f"U...
--- +++ @@ -10,12 +10,33 @@ def get_adapter(name: str) -> t.Any: + """ + Get adapter by name. + + Args: + name: Adapter name ("instructor" or "litellm") + + Returns: + StructuredOutputAdapter instance + + Raises: + ValueError: If adapter name is unknown + """ if name not ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/llms/adapters/__init__.py
Document functions with clear intent
import asyncio import logging import typing as t from typing import Dict, List from langchain_core.outputs import Generation, LLMResult from langchain_core.prompt_values import PromptValue from ragas._analytics import LLMUsageEvent, track from ragas.llms.base import BaseRagasLLM from ragas.run_config import RunConfi...
--- +++ @@ -1,3 +1,4 @@+"""OCI Gen AI LLM wrapper implementation for Ragas.""" import asyncio import logging @@ -32,6 +33,12 @@ class OCIGenAIWrapper(BaseRagasLLM): + """ + OCI Gen AI LLM wrapper for Ragas. + + This wrapper provides direct integration with Oracle Cloud Infrastructure + Generative AI...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/llms/oci_genai_wrapper.py
Create Google-style docstrings for my code
import typing as t from pydantic import BaseModel class Message(BaseModel): content: str metadata: t.Optional[t.Dict[str, t.Any]] = None class ToolCall(BaseModel): name: str args: t.Dict[str, t.Any] class HumanMessage(Message): type: t.Literal["human"] = "human" def pretty_repr(self):...
--- +++ @@ -4,40 +4,111 @@ class Message(BaseModel): + """ + Represents a generic message. + + Attributes + ---------- + content : str + The content of the message. + metadata : Optional[Dict[str, Any]], optional + Additional metadata associated with the message. + """ cont...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/messages.py
Create docstrings for all classes and functions
import typing as t import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult if t.TYPE_CHECKING: from ragas.embeddings.base import BaseRagasEmbedding class SemanticSimilarity(BaseMetric): embeddings: "BaseRagasEmbedding" def __init__( ...
--- +++ @@ -1,3 +1,4 @@+"""Semantic Similarity metric.""" import typing as t @@ -11,6 +12,44 @@ class SemanticSimilarity(BaseMetric): + """ + Evaluate semantic similarity between reference and response using embeddings. + + Scores the semantic similarity of ground truth with generated answer using + ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/_semantic_similarity.py
Add docstrings for better understanding
from enum import Enum from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult class DistanceMeasure(Enum): LEVENSHTEIN = "levenshtein" HAMMING = "hamming" JARO = "jaro" JARO_WINKLER = "jaro_winkler" class ExactMatch(BaseMetric): def __init__( ...
--- +++ @@ -1,3 +1,4 @@+"""String-based metrics v2 - Class-based implementations with automatic validation.""" from enum import Enum @@ -13,12 +14,39 @@ class ExactMatch(BaseMetric): + """ + Check if reference and response are exactly identical. + + This implementation provides automatic validation an...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/_string.py
Add docstrings to existing functions
import typing as t from typing import List, Union from ragas.messages import AIMessage, HumanMessage, ToolMessage from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( CompareOutcomeInput, CompareOutcomeOutput, CompareOutcomePrompt, In...
--- +++ @@ -1,3 +1,4 @@+"""AgentGoalAccuracy metrics - Modern collections implementation.""" import typing as t from typing import List, Union @@ -20,6 +21,42 @@ class AgentGoalAccuracyWithReference(BaseMetric): + """ + Measures if an agent achieved the user's goal compared to a reference outcome. + + ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/agent_goal_accuracy/metric.py
Create docstrings for all classes and functions
import typing as t import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( AnswerAccuracyInput, AnswerAccuracyJudge1Prompt, AnswerAccuracyJudge2Prompt, AnswerAccuracyOutput, ) if t.TYPE_CHECKING: from ragas.llms....
--- +++ @@ -1,3 +1,4 @@+"""Answer Accuracy metric v2 - Modern implementation with dual-judge evaluation.""" import typing as t @@ -18,6 +19,47 @@ class AnswerAccuracy(BaseMetric): + """ + Answer Accuracy metric using dual-judge evaluation. + + Measures answer accuracy compared to ground truth using a ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/answer_accuracy/metric.py
Write docstrings for this repository
import typing as t from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class WorkflowInput(BaseModel): workflow: str = Field( ..., description="The agentic workflow comprised of Human, AI and Tools" ) class WorkflowOutput(BaseModel): user_goal: str = ...
--- +++ @@ -1,3 +1,4 @@+"""AgentGoalAccuracy prompt classes and models.""" import typing as t @@ -22,6 +23,7 @@ class InferGoalOutcomePrompt(BasePrompt[WorkflowInput, WorkflowOutput]): + """Prompt for inferring user goal and end state from a workflow.""" input_model = WorkflowInput output_model ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/agent_goal_accuracy/util.py
Include argument descriptions in docstrings
from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class AnswerAccuracyInput(BaseModel): query: str = Field(..., description="The original question") user_answer: str = Field(..., description="The user's answer to evaluate") reference_answer: str = Field(..., ...
--- +++ @@ -1,3 +1,4 @@+"""Answer Accuracy prompt classes and models.""" from pydantic import BaseModel, Field @@ -5,6 +6,7 @@ class AnswerAccuracyInput(BaseModel): + """Input model for answer accuracy evaluation.""" query: str = Field(..., description="The original question") user_answer: str =...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/answer_accuracy/util.py
Add docstrings that explain inputs and outputs
import typing as t from typing import List import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( ClassificationWithReason, CorrectnessClassifierInput, CorrectnessClassifierPrompt, StatementGeneratorInput, Statem...
--- +++ @@ -1,3 +1,4 @@+"""Answer Correctness metric v2 - Modern implementation with multi-step pipeline.""" import typing as t from typing import List @@ -22,6 +23,53 @@ class AnswerCorrectness(BaseMetric): + """ + Answer Correctness metric using multi-step pipeline evaluation. + + Measures answer cor...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/answer_correctness/metric.py
Add minimal docstrings for each function
import typing as t from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class StatementGeneratorInput(BaseModel): question: str = Field(..., description="The question being answered") answer: str = Field( ..., description="The answer text to break down into...
--- +++ @@ -1,3 +1,4 @@+"""Answer Correctness prompt classes and models.""" import typing as t @@ -7,6 +8,7 @@ class StatementGeneratorInput(BaseModel): + """Input model for statement generation.""" question: str = Field(..., description="The question being answered") answer: str = Field( @@ -15...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/answer_correctness/util.py
Create Google-style docstrings for my code
from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class AnswerRelevanceInput(BaseModel): response: str = Field( ..., description="The response/answer to generate questions from" ) class AnswerRelevanceOutput(BaseModel): question: str = Field( ...
--- +++ @@ -1,3 +1,4 @@+"""Answer Relevancy prompt classes and models.""" from pydantic import BaseModel, Field @@ -5,6 +6,7 @@ class AnswerRelevanceInput(BaseModel): + """Input model for answer relevance evaluation.""" response: str = Field( ..., description="The response/answer to generate...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/answer_relevancy/util.py
Provide docstrings following PEP 257
import typing as t import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( AnswerRelevanceInput, AnswerRelevanceOutput, AnswerRelevancePrompt, ) if t.TYPE_CHECKING: from ragas.embeddings.base import BaseRagasEmbeddin...
--- +++ @@ -1,3 +1,4 @@+"""Answer Relevancy metrics v2 - Modern implementation with structured prompts.""" import typing as t @@ -18,6 +19,45 @@ class AnswerRelevancy(BaseMetric): + """ + Modern v2 implementation of answer relevancy evaluation. + + Evaluates answer relevancy by generating multiple que...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/answer_relevancy/metric.py
Add docstrings to meet PEP guidelines
import asyncio import typing as t from ragas.embeddings.base import BaseRagasEmbedding from ragas.llms.base import InstructorBaseRagasLLM from ragas.metrics.base import SimpleBaseMetric from ragas.metrics.result import MetricResult from ragas.metrics.validators import NumericValidator class BaseMetric(SimpleBaseMet...
--- +++ @@ -1,3 +1,4 @@+"""Base class for collections metrics with modern component validation.""" import asyncio import typing as t @@ -10,6 +11,23 @@ class BaseMetric(SimpleBaseMetric, NumericValidator): + """ + Base class for metrics collections with modern component validation. + + This class inher...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/base.py
Document my Python code with docstrings
from typing import List from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class ExtractEntitiesInput(BaseModel): text: str = Field(..., description="The text to extract entities from") class EntitiesList(BaseModel): entities: List[str] = Field( ..., d...
--- +++ @@ -1,3 +1,4 @@+"""Context Entity Recall prompt classes and models.""" from typing import List @@ -7,11 +8,13 @@ class ExtractEntitiesInput(BaseModel): + """Input model for entity extraction.""" text: str = Field(..., description="The text to extract entities from") class EntitiesList(Ba...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/context_entity_recall/util.py
Create structured documentation for my script
from typing import List from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class ContextRecallInput(BaseModel): question: str = Field(..., description="The original question asked by the user") context: str = Field(..., description="The retrieved context passage ...
--- +++ @@ -1,3 +1,4 @@+"""Context Recall prompt classes and models.""" from typing import List @@ -7,6 +8,7 @@ class ContextRecallInput(BaseModel): + """Input model for context recall evaluation.""" question: str = Field(..., description="The original question asked by the user") context: str =...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/context_recall/util.py
Add docstrings including usage examples
import typing as t from typing import List import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( ContextPrecisionInput, ContextPrecisionOutput, ContextPrecisionPrompt, ) if t.TYPE_CHECKING: from ragas.llms.base imp...
--- +++ @@ -1,3 +1,4 @@+"""Context Precision metrics v2 - Modern implementation with function-based prompts.""" import typing as t from typing import List @@ -18,6 +19,41 @@ class ContextPrecisionWithReference(BaseMetric): + """ + Modern v2 implementation of context precision with reference. + + Evalua...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/context_precision/metric.py
Help me add docstrings to my project
import typing as t from typing import List, Sequence from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( EntitiesList, ExtractEntitiesInput, ExtractEntitiesPrompt, ) if t.TYPE_CHECKING: from ragas.llms.base import InstructorBaseRaga...
--- +++ @@ -1,3 +1,4 @@+"""Context Entity Recall metrics v2 - Modern implementation with structured prompts.""" import typing as t from typing import List, Sequence @@ -16,6 +17,41 @@ class ContextEntityRecall(BaseMetric): + """ + Modern v2 implementation of context entity recall evaluation. + + Calcul...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/context_entity_recall/metric.py
Write docstrings for data processing functions
from __future__ import annotations import logging import typing as t from dataclasses import dataclass, field import numpy as np from pydantic import BaseModel from ragas.dataset_schema import SingleTurnSample from ragas.metrics._string import DistanceMeasure, NonLLMStringSimilarity from ragas.metrics.base import ( ...
--- +++ @@ -86,6 +86,14 @@ @dataclass class LLMContextRecall(MetricWithLLM, SingleTurnMetric): + """ + Estimates context recall by estimating TP and FN using annotated answer and + retrieved context. + + Attributes + ---------- + name : str + """ name: str = "context_recall" _require...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/_context_recall.py
Generate documentation strings for clarity
from __future__ import annotations import logging import typing as t from dataclasses import dataclass, field import numpy as np from pydantic import BaseModel, Field from ragas.dataset_schema import SingleTurnSample from ragas.metrics._string import NonLLMStringSimilarity from ragas.metrics.base import ( Metric...
--- +++ @@ -80,6 +80,16 @@ @dataclass class LLMContextPrecisionWithReference(MetricWithLLM, SingleTurnMetric): + """ + Average Precision is a metric that evaluates whether all of the + relevant items selected by the model are ranked higher or not. + + Attributes + ---------- + name : str + evalu...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/_context_precision.py
Add docstrings to improve readability
from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class ContextPrecisionInput(BaseModel): question: str = Field(..., description="The question being asked") context: str = Field(..., description="The context to evaluate for usefulness") answer: str = Field( ...
--- +++ @@ -1,3 +1,4 @@+"""Context Precision prompt classes and models.""" from pydantic import BaseModel, Field @@ -5,6 +6,7 @@ class ContextPrecisionInput(BaseModel): + """Input model for context precision evaluation.""" question: str = Field(..., description="The question being asked") contex...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/context_precision/util.py
Document my Python code with docstrings
import typing as t from typing import List import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( ContextRecallInput, ContextRecallOutput, ContextRecallPrompt, ) if t.TYPE_CHECKING: from ragas.llms.base import Instr...
--- +++ @@ -1,3 +1,4 @@+"""Context Recall metrics v2 - Modern implementation with structured prompts.""" import typing as t from typing import List @@ -18,6 +19,41 @@ class ContextRecall(BaseMetric): + """ + Modern v2 implementation of context recall evaluation. + + Evaluates context recall by classify...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/context_recall/metric.py
Annotate my code with docstrings
import typing as t from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult class CHRFScore(BaseMetric): def __init__( self, name: str = "chrf_score", kwargs: t.Optional[t.Dict[str, t.Any]] = None, **base_kwargs, ): super()....
--- +++ @@ -1,3 +1,4 @@+"""CHRFScore metric - Modern collections implementation.""" import typing as t @@ -6,6 +7,39 @@ class CHRFScore(BaseMetric): + """ + Calculate CHRF (Character F-score) between reference and response texts. + + CHRF is a character n-gram F-score metric that correlates well with ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/chrf_score/metric.py
Provide clean and structured docstrings
import logging import typing as t from io import StringIO import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult logger = logging.getLogger(__name__) class DataCompyScore(BaseMetric): def __init__( self, mode: t.Literal["rows", "...
--- +++ @@ -1,3 +1,4 @@+"""DataCompyScore metric - Modern collections implementation.""" import logging import typing as t @@ -12,6 +13,34 @@ class DataCompyScore(BaseMetric): + """ + Compare CSV data using datacompy library to compute precision, recall, or F1 scores. + + This metric compares two CSV s...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/datacompy_score/metric.py
Document helper functions with docstrings
import typing as t from typing import List import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( ContextRelevanceInput, ContextRelevanceJudge1Prompt, ContextRelevanceJudge2Prompt, ContextRelevanceOutput, ) if t.TYP...
--- +++ @@ -1,3 +1,4 @@+"""Context Relevance metric v2 - Modern implementation with dual-judge evaluation.""" import typing as t from typing import List @@ -19,6 +20,47 @@ class ContextRelevance(BaseMetric): + """ + Context Relevance metric using dual-judge evaluation. + + Evaluates whether the retriev...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/context_relevance/metric.py
Add verbose docstrings with examples
from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class ContextRelevanceInput(BaseModel): user_input: str = Field(..., description="The user's question") context: str = Field(..., description="The context to evaluate for relevance") class ContextRelevanceOutput...
--- +++ @@ -1,3 +1,4 @@+"""Context Relevance prompt classes and models.""" from pydantic import BaseModel, Field @@ -5,12 +6,14 @@ class ContextRelevanceInput(BaseModel): + """Input model for context relevance evaluation.""" user_input: str = Field(..., description="The user's question") context...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/context_relevance/util.py
Add detailed docstrings explaining each function
import copy import typing as t from typing import Dict, List, Tuple from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt if t.TYPE_CHECKING: from ragas.llms.base import InstructorBaseRagasLLM class ClaimDecompositionInput(BaseModel): response: str = Field(..., des...
--- +++ @@ -1,3 +1,4 @@+"""Factual Correctness prompt classes and models.""" import copy import typing as t @@ -12,6 +13,7 @@ class ClaimDecompositionInput(BaseModel): + """Input for claim decomposition.""" response: str = Field(..., description="The response text to decompose into claims") atomi...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/factual_correctness/util.py
Add minimal docstrings for each function
import typing as t from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt DEFAULT_REFERENCE_FREE_RUBRICS = { "score1_description": "The response is entirely incorrect and fails to address any aspect of the user input.", "score2_description": "The response contains part...
--- +++ @@ -1,3 +1,4 @@+"""DomainSpecificRubrics prompt classes and models.""" import typing as t @@ -23,6 +24,7 @@ class RubricScoreInput(BaseModel): + """Input model for rubric-based scoring.""" user_input: t.Optional[str] = Field( default=None, description="The input/question provided to ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/domain_specific_rubrics/util.py
Add docstrings explaining edge cases
import typing as t from typing import List import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from ragas.metrics.utils import fbeta_score from .util import ( ClaimDecompositionInput, ClaimDecompositionOutput, ClaimDecompositionPrompt, ...
--- +++ @@ -1,3 +1,4 @@+"""Factual Correctness metrics v2 - Modern implementation with multi-modal scoring.""" import typing as t from typing import List @@ -22,6 +23,51 @@ class FactualCorrectness(BaseMetric): + """ + Modern v2 implementation of factual correctness evaluation. + + Evaluates the factua...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/factual_correctness/metric.py
Document my Python code with docstrings
import typing as t from typing import List from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( NLIStatementInput, NLIStatementOutput, NLIStatementPrompt, StatementGeneratorInput, StatementGeneratorOutput, StatementGeneratorPr...
--- +++ @@ -1,3 +1,4 @@+"""Faithfulness metric v2 - Modern implementation with multi-step pipeline.""" import typing as t from typing import List @@ -19,6 +20,46 @@ class Faithfulness(BaseMetric): + """ + Faithfulness metric using multi-step pipeline evaluation. + + Measures how factually consistent a ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/faithfulness/metric.py
Write docstrings for utility functions
import typing as t from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class StatementGeneratorInput(BaseModel): question: str = Field(..., description="The question being answered") answer: str = Field( ..., description="The answer text to break down into...
--- +++ @@ -1,3 +1,4 @@+"""Faithfulness prompt classes and models.""" import typing as t @@ -7,6 +8,7 @@ class StatementGeneratorInput(BaseModel): + """Input model for statement generation.""" question: str = Field(..., description="The question being answered") answer: str = Field( @@ -15,6 +17...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/faithfulness/util.py
Document this script properly
import typing as t from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class InstanceRubricScoreInput(BaseModel): user_input: t.Optional[str] = Field( default=None, description="The input/question provided to the system" ) response: t.Optional[str] = F...
--- +++ @@ -1,3 +1,4 @@+"""InstanceSpecificRubrics prompt classes and models.""" import typing as t @@ -7,6 +8,7 @@ class InstanceRubricScoreInput(BaseModel): + """Input model for instance-specific rubric scoring.""" user_input: t.Optional[str] = Field( default=None, description="The input/q...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/instance_specific_rubrics/util.py
Write docstrings that follow conventions
from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class ResponseGroundednessInput(BaseModel): response: str = Field(..., description="The response/assertion to evaluate") context: str = Field(..., description="The context to evaluate against") class ResponseGro...
--- +++ @@ -1,3 +1,4 @@+"""Response Groundedness prompt classes and models.""" from pydantic import BaseModel, Field @@ -5,12 +6,14 @@ class ResponseGroundednessInput(BaseModel): + """Input model for response groundedness evaluation.""" response: str = Field(..., description="The response/assertion t...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/response_groundedness/util.py
Write docstrings for algorithm functions
from __future__ import annotations import asyncio import logging import typing as t from abc import ABC, abstractmethod from collections import Counter from dataclasses import dataclass, field from enum import Enum from pydantic import ValidationError from tqdm import tqdm from ragas._analytics import EvaluationEven...
--- +++ @@ -49,6 +49,16 @@ class MetricType(Enum): + """ + Enumeration of metric types in Ragas. + + Attributes + ---------- + SINGLE_TURN : str + Represents a single-turn metric type. + MULTI_TURN : str + Represents a multi-turn metric type. + """ SINGLE_TURN = "single_tur...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/base.py
Document functions with detailed explanations
import typing as t from pydantic import BaseModel, Field from ragas.metrics.collections.multi_modal_faithfulness.util import ( is_image_path_or_url, process_image_to_base64, ) class MultiModalRelevanceInput(BaseModel): user_input: str = Field(..., description="The user's question or input") respon...
--- +++ @@ -1,3 +1,4 @@+"""Utility functions and prompt classes for MultiModalRelevance metric.""" import typing as t @@ -10,6 +11,7 @@ class MultiModalRelevanceInput(BaseModel): + """Input model for multimodal relevance evaluation.""" user_input: str = Field(..., description="The user's question or ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/multi_modal_relevance/util.py
Add documentation for all methods
import typing as t from typing import List import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( ResponseGroundednessInput, ResponseGroundednessJudge1Prompt, ResponseGroundednessJudge2Prompt, ResponseGroundednessOut...
--- +++ @@ -1,3 +1,4 @@+"""Response Groundedness metric v2 - Modern implementation with dual-judge evaluation.""" import typing as t from typing import List @@ -19,6 +20,47 @@ class ResponseGroundedness(BaseMetric): + """ + Response Groundedness metric using dual-judge evaluation. + + Evaluates how wel...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/response_groundedness/metric.py
Help me document legacy Python code
from typing import List from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt from ragas.prompt.metrics.common import nli_statement_prompt, statement_generator_prompt class StatementGeneratorInput(BaseModel): question: str = Field(..., description="The question asked") ...
--- +++ @@ -1,3 +1,4 @@+"""Noise Sensitivity prompt classes and models.""" from typing import List @@ -8,12 +9,14 @@ class StatementGeneratorInput(BaseModel): + """Input for statement generation.""" question: str = Field(..., description="The question asked") text: str = Field(..., description="...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/noise_sensitivity/util.py
Create docstrings for all classes and functions
import typing as t from typing import List from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( MULTIMODAL_FAITHFULNESS_INSTRUCTION, MultiModalFaithfulnessOutput, build_multimodal_message_content, ) if t.TYPE_CHECKING: from ragas.llm...
--- +++ @@ -1,3 +1,4 @@+"""MultiModalFaithfulness metric - Collections implementation for multimodal faithfulness evaluation.""" import typing as t from typing import List @@ -16,6 +17,50 @@ class MultiModalFaithfulness(BaseMetric): + """ + MultiModalFaithfulness metric for evaluating response faithfulnes...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/multi_modal_faithfulness/metric.py
Replace inline comments with docstrings
import typing as t from typing import List from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( MULTIMODAL_RELEVANCE_INSTRUCTION, MultiModalRelevanceOutput, build_multimodal_relevance_message_content, ) if t.TYPE_CHECKING: from ragas...
--- +++ @@ -1,3 +1,4 @@+"""MultiModalRelevance metric - Collections implementation for multimodal relevance evaluation.""" import typing as t from typing import List @@ -16,6 +17,51 @@ class MultiModalRelevance(BaseMetric): + """ + MultiModalRelevance metric for evaluating response relevance against + ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/multi_modal_relevance/metric.py
Write docstrings for algorithm functions
import typing as t from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class SQLEquivalenceInput(BaseModel): reference: str = Field(..., description="Reference SQL query") response: str = Field(..., description="Generated SQL query to evaluate") database_schema...
--- +++ @@ -1,3 +1,4 @@+"""SQLSemanticEquivalence prompt classes and models.""" import typing as t @@ -25,6 +26,7 @@ class SQLEquivalencePrompt(BasePrompt[SQLEquivalenceInput, SQLEquivalenceOutput]): + """Prompt for evaluating semantic equivalence between SQL queries.""" input_model = SQLEquivalenceI...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/sql_semantic_equivalence/util.py
Generate missing documentation strings
import typing as t from typing import List, Optional from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import SQLEquivalenceInput, SQLEquivalenceOutput, SQLEquivalencePrompt if t.TYPE_CHECKING: from ragas.llms.base import InstructorBaseRagasLLM clas...
--- +++ @@ -1,3 +1,4 @@+"""SQLSemanticEquivalence metric - Modern collections implementation.""" import typing as t from typing import List, Optional @@ -12,6 +13,40 @@ class SQLSemanticEquivalence(BaseMetric): + """ + Evaluates semantic equivalence between a generated SQL query and a reference query. + +...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/sql_semantic_equivalence/metric.py
Add verbose docstrings with examples
import typing as t from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult class RougeScore(BaseMetric): def __init__( self, name: str = "rouge_score", rouge_type: t.Literal["rouge1", "rougeL"] = "rougeL", mode: t.Literal["fmeasure", "...
--- +++ @@ -1,3 +1,4 @@+"""Rouge Score metric v2 - Class-based implementation with automatic validation.""" import typing as t @@ -6,6 +7,39 @@ class RougeScore(BaseMetric): + """ + Calculate ROUGE score between reference and response texts. + + This implementation provides automatic validation and pu...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/_rouge_score.py
Add docstrings that explain inputs and outputs
import typing as t from typing import Dict, List, Literal import numpy as np from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( StatementFaithfulnessInput, StatementFaithfulnessOutput, StatementFaithfulnessPrompt, StatementGenerato...
--- +++ @@ -1,3 +1,4 @@+"""Noise Sensitivity metrics v2 - Modern implementation with function-based prompts.""" import typing as t from typing import Dict, List, Literal @@ -21,6 +22,51 @@ class NoiseSensitivity(BaseMetric): + """ + Modern v2 implementation of noise sensitivity evaluation. + + Measures...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/noise_sensitivity/metric.py
Write docstrings for algorithm functions
__all__ = ["MetricResult"] import typing as t from pydantic import GetCoreSchemaHandler, ValidationInfo from pydantic_core import core_schema class MetricResult: def __init__( self, value: t.Any, reason: t.Optional[str] = None, traces: t.Optional[t.Dict[str, t.Any]] = None, ...
--- +++ @@ -1,3 +1,4 @@+"""MetricResult object to store the result of a metric""" __all__ = ["MetricResult"] @@ -8,6 +9,16 @@ class MetricResult: + """Class to hold the result of a metric evaluation. + + This class behaves like its underlying result value but still provides access + to additional meta...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/result.py
Add docstrings including usage examples
import typing as t from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( DEFAULT_REFERENCE_FREE_RUBRICS, DEFAULT_WITH_REFERENCE_RUBRICS, RubricScoreInput, RubricScoreOutput, RubricScorePrompt, format_rubrics, ) if t.TYPE_CHECK...
--- +++ @@ -1,3 +1,4 @@+"""DomainSpecificRubrics metric - Modern collections implementation.""" import typing as t @@ -18,6 +19,65 @@ class DomainSpecificRubrics(BaseMetric): + """ + Evaluates responses using domain-specific rubrics with customizable scoring criteria. + + This metric allows you to def...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/domain_specific_rubrics/metric.py
Fully document this Python code with docstrings
__all__ = [ "DiscreteValidator", "NumericValidator", "RankingValidator", "AllowedValuesType", "get_validator_for_allowed_values", "get_metric_type_name", ] import typing as t from abc import ABC # Type alias for all possible allowed_values types across different metric types AllowedValuesType...
--- +++ @@ -1,3 +1,4 @@+"""Validation mixins for different metric types.""" __all__ = [ "DiscreteValidator", @@ -16,19 +17,31 @@ class BaseValidator(ABC): + """Base validator mixin with common validation interface.""" name: str # Note: allowed_values is now inherited from SimpleBaseMetric bas...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/validators.py
Create documentation strings for testing functions
import typing as t from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult class BleuScore(BaseMetric): def __init__( self, name: str = "bleu_score", kwargs: t.Optional[t.Dict[str, t.Any]] = None, **base_kwargs, ): super()....
--- +++ @@ -1,3 +1,4 @@+"""BLEU Score metric v2 - Class-based implementation with automatic validation.""" import typing as t @@ -6,6 +7,33 @@ class BleuScore(BaseMetric): + """ + Calculate BLEU score between reference and response texts. + + This implementation provides automatic validation and pure ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/_bleu_score.py
Write docstrings describing each step
import base64 import binascii import logging import os import re import typing as t from io import BytesIO from urllib.parse import urlparse import requests from PIL import Image from pydantic import BaseModel, Field logger = logging.getLogger(__name__) # Constants for security/processing ALLOWED_URL_SCHEMES = {"ht...
--- +++ @@ -1,3 +1,4 @@+"""Utility functions and prompt classes for MultiModalFaithfulness metric.""" import base64 import binascii @@ -25,6 +26,7 @@ class MultiModalFaithfulnessInput(BaseModel): + """Input model for multimodal faithfulness evaluation.""" response: str = Field(..., description="The re...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/multi_modal_faithfulness/util.py
Create docstrings for each class method
from __future__ import annotations import typing as t import warnings from dataclasses import dataclass, field from ragas.dataset_schema import MultiTurnSample, SingleTurnSample from ragas.messages import AIMessage, ToolCall from ragas.metrics._string import ExactMatch from ragas.metrics.base import MetricType, Multi...
--- +++ @@ -15,6 +15,34 @@ @dataclass class ToolCallAccuracy(MultiTurnMetric): + """ + Tool Call Accuracy metric measures how accurately an LLM agent makes tool calls + compared to reference tool calls. + + The metric supports two evaluation modes: + 1. Strict order (default): Tool calls must match ex...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/_tool_call_accuracy.py
Write reusable docstrings
from __future__ import annotations import re import typing as t QUOTE_RE = re.compile( r'["\u201c\u201d\u201e\u201f\'\u2018\u2019`\u00b4](.*?)["\u201c\u201d\u201e\u201f\'\u2018\u2019`\u00b4]' ) def normalize_text(text: str) -> str: return re.sub(r"\s+", " ", text).strip().lower() def extract_quoted_spans...
--- +++ @@ -1,3 +1,4 @@+"""Quoted Spans utility functions.""" from __future__ import annotations @@ -10,10 +11,22 @@ def normalize_text(text: str) -> str: + """Normalize text by collapsing whitespace and lower-casing.""" return re.sub(r"\s+", " ", text).strip().lower() def extract_quoted_spans(ans...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/quoted_spans/util.py
Add minimal docstrings for each function
import typing as t from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( InstanceRubricScoreInput, InstanceRubricScoreOutput, InstanceRubricScorePrompt, ) if t.TYPE_CHECKING: from ragas.llms.base import InstructorBaseRagasLLM class ...
--- +++ @@ -1,3 +1,4 @@+"""InstanceSpecificRubrics metric - Modern collections implementation.""" import typing as t @@ -15,6 +16,50 @@ class InstanceSpecificRubrics(BaseMetric): + """ + Evaluates responses using instance-specific rubrics where each sample has its own criteria. + + Unlike DomainSpecif...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/instance_specific_rubrics/metric.py
Document all endpoints with docstrings
from __future__ import annotations import logging import typing as t from dataclasses import dataclass, field import numpy as np from langchain_core.callbacks import Callbacks from langchain_core.prompt_values import StringPromptValue from ragas.dataset_schema import SingleTurnSample from ragas.llms.base import Base...
--- +++ @@ -17,6 +17,31 @@ @dataclass class AnswerAccuracy(MetricWithLLM, SingleTurnMetric): + """ + Measures answer accuracy compared to ground truth given a user_input. + This metric averages two distinct judge prompts to evaluate. + + Top10, Zero-shoot LLM-as-a-Judge Leaderboard: + 1)- nvidia/Llama...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/_nv_metrics.py
Improve my code by adding docstrings
import typing as t from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import count_matched_spans, extract_quoted_spans class QuotedSpansAlignment(BaseMetric): def __init__( self, name: str = "quoted_spans_alignment", casefold:...
--- +++ @@ -1,3 +1,4 @@+"""QuotedSpansAlignment metric - Modern collections implementation.""" import typing as t @@ -8,6 +9,41 @@ class QuotedSpansAlignment(BaseMetric): + """ + Measure citation alignment for quoted spans in model-generated answers. + + This metric computes the fraction of quoted spa...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/quoted_spans/metric.py
Create structured documentation for my script
from __future__ import annotations import logging import typing as t from dataclasses import dataclass, field import numpy as np from pydantic import BaseModel, Field from ragas.dataset_schema import SingleTurnSample from ragas.metrics.base import ( MetricOutputType, MetricType, MetricWithLLM, Single...
--- +++ @@ -200,6 +200,9 @@ return await self._ascore(row, callbacks) async def _ascore(self, row: t.Dict, callbacks: Callbacks) -> float: + """ + returns the NLI score for each (q, c, a) pair + """ assert self.llm is not None, "LLM is not set" statements = await ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/_faithfulness.py
Generate docstrings for each module
import typing as t from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class ExtractedKeyphrasesInput(BaseModel): text: str = Field(..., description="The text to extract keyphrases from") class ExtractedKeyphrases(BaseModel): keyphrases: t.List[str] = Field(......
--- +++ @@ -1,3 +1,4 @@+"""Summary Score prompt classes and models.""" import typing as t @@ -7,11 +8,13 @@ class ExtractedKeyphrasesInput(BaseModel): + """Input model for keyphrase extraction.""" text: str = Field(..., description="The text to extract keyphrases from") class ExtractedKeyphrases...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/summary_score/util.py
Help me write clear docstrings
import typing as t from ragas.messages import ToolCall def sorted_key_for_tool_call(tc: ToolCall) -> t.Tuple[str, ...]: key_list = [tc.name] args = tc.args args_names = sorted(args) for name in args_names: key_list.append(name) key_list.append(str(args[name])) return tuple(key_li...
--- +++ @@ -1,3 +1,4 @@+"""Tool Call Accuracy utility functions and models.""" import typing as t @@ -5,6 +6,12 @@ def sorted_key_for_tool_call(tc: ToolCall) -> t.Tuple[str, ...]: + """ + Generate a consistent sorting key for tool calls. + + Ensures tool calls with the same content are compared correc...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/tool_call_accuracy/util.py
Add well-formatted docstrings
import hashlib import json import logging import typing as t from dataclasses import dataclass, field from langchain_core.callbacks import Callbacks from ragas.cache import CacheInterface from ragas.dataset_schema import SingleMetricAnnotation from ragas.losses import Loss from ragas.optimizers.base import Optimizer ...
--- +++ @@ -17,6 +17,46 @@ @dataclass class DSPyOptimizer(Optimizer): + """ + Advanced prompt optimizer using DSPy's MIPROv2. + + MIPROv2 performs sophisticated prompt optimization by combining: + - Instruction optimization (prompt engineering) + - Demonstration optimization (few-shot examples) + -...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/optimizers/dspy_optimizer.py
Add inline docstrings for readability
import json def extract_entities_prompt(text: str) -> str: safe_text = json.dumps(text) return f"""Given a text, extract unique entities without repetition. Ensure you consider different forms or mentions of the same entity as a single entity. Please return the output in a JSON format that complies with th...
--- +++ @@ -1,8 +1,16 @@+"""Context Entity Recall prompts - V1-identical using exact PydanticPrompt.to_string() output.""" import json def extract_entities_prompt(text: str) -> str: + """ + V1-identical entity extraction prompt using exact PydanticPrompt.to_string() output. + Args: + text: The t...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/context_entity_recall.py
Add minimal docstrings for each function
import json def claim_decomposition_prompt( response: str, atomicity: str = "low", coverage: str = "low" ) -> str: safe_response = json.dumps(response) # Select examples based on atomicity and coverage configuration if atomicity == "low" and coverage == "low": examples = [ { ...
--- +++ @@ -1,3 +1,4 @@+"""Factual correctness prompts - V1-identical converted to functions.""" import json @@ -5,6 +6,17 @@ def claim_decomposition_prompt( response: str, atomicity: str = "low", coverage: str = "low" ) -> str: + """ + V1-identical claim decomposition prompt with configurable atomicit...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/factual_correctness.py
Create structured documentation for my script
import json def context_recall_prompt(question: str, context: str, answer: str) -> str: # Use json.dumps() to safely escape the strings safe_question = json.dumps(question) safe_context = json.dumps(context) safe_answer = json.dumps(answer) return f"""Given a context, and an answer, analyze each...
--- +++ @@ -1,8 +1,20 @@+"""Context Recall prompt for classifying statement attributions.""" import json def context_recall_prompt(question: str, context: str, answer: str) -> str: + """ + Generate the prompt for context recall evaluation. + + Args: + question: The original question + con...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/context_recall.py
Write docstrings for this repository
import json def context_relevance_judge1_prompt(query: str, context: str) -> str: safe_query = json.dumps(query) safe_context = json.dumps(context) return f"""### Instructions You are a world class expert designed to evaluate the relevance score of a Context in order to answer the Question. Your task i...
--- +++ @@ -1,8 +1,19 @@+"""Context Relevance prompts - Convert NVIDIA dual-judge templates to function format.""" import json def context_relevance_judge1_prompt(query: str, context: str) -> str: + """ + First judge template for context relevance evaluation. + + Args: + query: The user's questi...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/context_relevance.py
Add docstrings for utility scripts
from __future__ import annotations import json import logging import os import typing as t from abc import ABC, abstractmethod from langchain_core.prompt_values import StringPromptValue from pydantic import BaseModel from ragas._version import __version__ from ragas.utils import camel_to_snake if t.TYPE_CHECKING: ...
--- +++ @@ -45,6 +45,9 @@ stop: t.Optional[t.List[str]] = None, callbacks: Callbacks = [], ) -> t.Any: + """ + Generate a single completion from the prompt. + """ pass @abstractmethod @@ -57,9 +60,15 @@ stop: t.Optional[t.List[str]] = None, cal...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/base.py
Fill in missing docstrings in my code
import typing as t import warnings from typing import List from ragas.messages import AIMessage, ToolCall from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import exact_match_args, sorted_key_for_tool_call if t.TYPE_CHECKING: from ragas.messages impor...
--- +++ @@ -1,3 +1,4 @@+"""Tool Call Accuracy metric - Modern collections implementation.""" import typing as t import warnings @@ -14,6 +15,49 @@ class ToolCallAccuracy(BaseMetric): + """ + Modern implementation of Tool Call Accuracy metric. + + Measures how accurately an LLM agent makes tool calls co...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/tool_call_accuracy/metric.py
Add docstrings to clarify complex logic
import logging import typing as t from typing import List from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( AnswersGenerated, ExtractedKeyphrases, ExtractedKeyphrasesInput, ExtractKeyphrasesPrompt, GenerateAnswersInput, Gen...
--- +++ @@ -1,3 +1,4 @@+"""Summary Score metric v2 - Modern implementation with multi-step pipeline.""" import logging import typing as t @@ -23,6 +24,52 @@ class SummaryScore(BaseMetric): + """ + Summary Score metric using multi-step pipeline evaluation. + + Measures how well a summary captures import...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/summary_score/metric.py
Add return value explanations in docstrings
from __future__ import annotations __all__ = ["SimpleExampleStore", "SimpleInMemoryExampleStore", "DynamicFewShotPrompt"] import gzip import json import typing as t import warnings from abc import ABC, abstractmethod from pathlib import Path import numpy as np from ragas.embeddings.base import BaseRagasEmbedding as...
--- +++ @@ -24,20 +24,29 @@ def get_examples( self, data: t.Dict, top_k: int = 5 ) -> t.List[t.Tuple[t.Dict, t.Dict]]: + """Get top_k most similar examples to data.""" pass @abstractmethod def add_example(self, input: t.Dict, output: t.Dict) -> None: + """Add an exam...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/dynamic_few_shot.py
Create documentation strings for testing functions
import json import typing as t def nli_statement_prompt(context: str, statements: t.List[str]) -> str: # Format inputs exactly like V1's model_dump_json(indent=4, exclude_none=True) safe_context = json.dumps(context) safe_statements = json.dumps(statements, indent=4).replace("\n", "\n ") return f...
--- +++ @@ -1,9 +1,20 @@+"""Noise Sensitivity prompts - V1-identical using exact PydanticPrompt.to_string() output.""" import json import typing as t def nli_statement_prompt(context: str, statements: t.List[str]) -> str: + """ + V1-identical NLI statement evaluation - matches PydanticPrompt.to_string() ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/noise_sensitivity.py
Add verbose docstrings with examples
import json import typing as t def extract_keyphrases_prompt(text: str) -> str: # Format input exactly like V1's model_dump_json(indent=4, exclude_none=True) safe_text = json.dumps(text) return f"""Extract keyphrases of type: Person, Organization, Location, Date/Time, Monetary Values, and Percentages. P...
--- +++ @@ -1,9 +1,19 @@+"""Summary Score prompts - V1-identical using exact PydanticPrompt.to_string() output.""" import json import typing as t def extract_keyphrases_prompt(text: str) -> str: + """ + V1-identical keyphrase extraction - matches PydanticPrompt.to_string() exactly. + + Args: + ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/summary_score.py
Add docstrings to clarify complex logic
from __future__ import annotations import inspect import logging import os import typing as t from .pydantic_prompt import PydanticPrompt if t.TYPE_CHECKING: from ragas.llms.base import BaseRagasLLM, InstructorBaseRagasLLM logger = logging.getLogger(__name__) class PromptMixin: name: str = "" def _...
--- +++ @@ -15,6 +15,10 @@ class PromptMixin: + """ + Mixin class for classes that have prompts. + eg: [BaseSynthesizer][ragas.testset.synthesizers.base.BaseSynthesizer], [MetricWithLLM][ragas.metrics.base.MetricWithLLM] + """ name: str = "" @@ -26,12 +30,23 @@ return prompts def...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/mixin.py