|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "code", |
| 5 | + "execution_count": null, |
| 6 | + "metadata": {}, |
| 7 | + "outputs": [], |
| 8 | + "source": [ |
| 9 | + "#| default_exp metric.decorator" |
| 10 | + ] |
| 11 | + }, |
| 12 | + { |
| 13 | + "cell_type": "markdown", |
| 14 | + "metadata": {}, |
| 15 | + "source": [ |
| 16 | + "# decorator factory for metrics\n", |
| 17 | + "> decorator factory for creating custom metrics" |
| 18 | + ] |
| 19 | + }, |
| 20 | + { |
| 21 | + "cell_type": "code", |
| 22 | + "execution_count": null, |
| 23 | + "metadata": {}, |
| 24 | + "outputs": [], |
| 25 | + "source": [ |
| 26 | + "#| export\n", |
| 27 | + "\n", |
| 28 | + "import typing as t\n", |
| 29 | + "import inspect\n", |
| 30 | + "import asyncio\n", |
| 31 | + "from dataclasses import dataclass\n", |
| 32 | + "from ragas_annotator.metric import MetricResult\n", |
| 33 | + "\n", |
| 34 | + "\n", |
| 35 | + "\n", |
| 36 | + "\n", |
| 37 | + "def create_metric_decorator(metric_class):\n", |
| 38 | + " \"\"\"\n", |
| 39 | + " Factory function that creates decorator factories for different metric types.\n", |
| 40 | + " \n", |
| 41 | + " Args:\n", |
| 42 | + " metric_class: The metric class to use (DiscreteMetrics, NumericMetrics, etc.)\n", |
| 43 | + " \n", |
| 44 | + " Returns:\n", |
| 45 | + " A decorator factory function for the specified metric type\n", |
| 46 | + " \"\"\"\n", |
| 47 | + " def decorator_factory(llm, prompt, name: t.Optional[str] = None, **metric_params):\n", |
| 48 | + " \"\"\"\n", |
| 49 | + " Creates a decorator that wraps a function into a metric instance.\n", |
| 50 | + " \n", |
| 51 | + " Args:\n", |
| 52 | + " llm: The language model instance to use\n", |
| 53 | + " prompt: The prompt template\n", |
| 54 | + " name: Optional name for the metric (defaults to function name)\n", |
| 55 | + " **metric_params: Additional parameters specific to the metric type\n", |
| 56 | + " (values for DiscreteMetrics, range for NumericMetrics, etc.)\n", |
| 57 | + " \n", |
| 58 | + " Returns:\n", |
| 59 | + " A decorator function\n", |
| 60 | + " \"\"\"\n", |
| 61 | + " def decorator(func):\n", |
| 62 | + " # Get metric name and check if function is async\n", |
| 63 | + " metric_name = name or func.__name__\n", |
| 64 | + " is_async = inspect.iscoroutinefunction(func)\n", |
| 65 | + " \n", |
| 66 | + " @dataclass\n", |
| 67 | + " class CustomMetric(metric_class):\n", |
| 68 | + " def _extract_result(self, result, reasoning: bool):\n", |
| 69 | + " \"\"\"Extract score and reason from the result.\"\"\"\n", |
| 70 | + " if isinstance(result, tuple) and len(result) == 2:\n", |
| 71 | + " score, reason = result\n", |
| 72 | + " else:\n", |
| 73 | + " score, reason = result, None\n", |
| 74 | + " \n", |
| 75 | + " # Use \"result\" instead of \"score\" for the new MetricResult implementation\n", |
| 76 | + " return MetricResult(result=score, reason=reason if reasoning else None)\n", |
| 77 | + " \n", |
| 78 | + " def _run_sync_in_async(self, func, *args, **kwargs):\n", |
| 79 | + " \"\"\"Run a synchronous function in an async context.\"\"\"\n", |
| 80 | + " # For sync functions, just run them normally\n", |
| 81 | + " return func(*args, **kwargs)\n", |
| 82 | + " \n", |
| 83 | + " def _execute_metric(self, is_async_execution, reasoning, **kwargs):\n", |
| 84 | + " \"\"\"Execute the metric function with proper async handling.\"\"\"\n", |
| 85 | + " try:\n", |
| 86 | + " if is_async:\n", |
| 87 | + " # Async function implementation\n", |
| 88 | + " if is_async_execution:\n", |
| 89 | + " # In async context, await the function directly\n", |
| 90 | + " result = func(self.llm, self.prompt, **kwargs)\n", |
| 91 | + " else:\n", |
| 92 | + " # In sync context, run the async function in an event loop\n", |
| 93 | + " try:\n", |
| 94 | + " loop = asyncio.get_event_loop()\n", |
| 95 | + " except RuntimeError:\n", |
| 96 | + " loop = asyncio.new_event_loop()\n", |
| 97 | + " asyncio.set_event_loop(loop)\n", |
| 98 | + " result = loop.run_until_complete(func(self.llm, self.prompt, **kwargs))\n", |
| 99 | + " else:\n", |
| 100 | + " # Sync function implementation\n", |
| 101 | + " result = func(self.llm, self.prompt, **kwargs)\n", |
| 102 | + " \n", |
| 103 | + " return self._extract_result(result, reasoning)\n", |
| 104 | + " except Exception as e:\n", |
| 105 | + " # Handle errors gracefully\n", |
| 106 | + " error_msg = f\"Error executing metric {self.name}: {str(e)}\"\n", |
| 107 | + " return MetricResult(result=None, reason=error_msg)\n", |
| 108 | + " \n", |
| 109 | + " def score(self, reasoning: bool = True, n: int = 1, **kwargs):\n", |
| 110 | + " \"\"\"Synchronous scoring method.\"\"\"\n", |
| 111 | + " return self._execute_metric(is_async_execution=False, reasoning=reasoning, **kwargs)\n", |
| 112 | + " \n", |
| 113 | + " async def ascore(self, reasoning: bool = True, n: int = 1, **kwargs):\n", |
| 114 | + " \"\"\"Asynchronous scoring method.\"\"\"\n", |
| 115 | + " if is_async:\n", |
| 116 | + " # For async functions, await the result\n", |
| 117 | + " result = await func(self.llm, self.prompt, **kwargs)\n", |
| 118 | + " return self._extract_result(result, reasoning)\n", |
| 119 | + " else:\n", |
| 120 | + " # For sync functions, run normally\n", |
| 121 | + " result = self._run_sync_in_async(func, self.llm, self.prompt, **kwargs)\n", |
| 122 | + " return self._extract_result(result, reasoning)\n", |
| 123 | + " \n", |
| 124 | + " # Create the metric instance with all parameters\n", |
| 125 | + " metric_instance = CustomMetric(\n", |
| 126 | + " name=metric_name,\n", |
| 127 | + " prompt=prompt,\n", |
| 128 | + " llm=llm,\n", |
| 129 | + " **metric_params\n", |
| 130 | + " )\n", |
| 131 | + " \n", |
| 132 | + " # Preserve metadata\n", |
| 133 | + " metric_instance.__name__ = metric_name\n", |
| 134 | + " metric_instance.__doc__ = func.__doc__\n", |
| 135 | + " \n", |
| 136 | + " return metric_instance\n", |
| 137 | + " \n", |
| 138 | + " return decorator\n", |
| 139 | + " \n", |
| 140 | + " return decorator_factory\n", |
| 141 | + "\n", |
| 142 | + "\n" |
| 143 | + ] |
| 144 | + }, |
| 145 | + { |
| 146 | + "cell_type": "markdown", |
| 147 | + "metadata": {}, |
| 148 | + "source": [ |
| 149 | + "### Example usage\n" |
| 150 | + ] |
| 151 | + }, |
| 152 | + { |
| 153 | + "cell_type": "code", |
| 154 | + "execution_count": null, |
| 155 | + "metadata": {}, |
| 156 | + "outputs": [ |
| 157 | + { |
| 158 | + "name": "stdout", |
| 159 | + "output_type": "stream", |
| 160 | + "text": [ |
| 161 | + "high\n", |
| 162 | + "reason\n" |
| 163 | + ] |
| 164 | + } |
| 165 | + ], |
| 166 | + "source": [ |
| 167 | + "#| eval: false\n", |
| 168 | + "\n", |
| 169 | + "\n", |
| 170 | + "from ragas_annotator.metric import DiscreteMetric\n", |
| 171 | + "from ragas_annotator.metric.llm import LLM\n", |
| 172 | + "from pydantic import BaseModel\n", |
| 173 | + "\n", |
| 174 | + "discrete_metric = create_metric_decorator(DiscreteMetric)\n", |
| 175 | + "\n", |
| 176 | + "@discrete_metric(llm=LLM(),\n", |
| 177 | + " prompt=\"Evaluate if given answer is helpful\\n\\n{response}\",\n", |
| 178 | + " name='new_metric',values=[\"low\",\"med\",\"high\"])\n", |
| 179 | + "def my_metric(llm,prompt,**kwargs):\n", |
| 180 | + "\n", |
| 181 | + " class response_model(BaseModel):\n", |
| 182 | + " output: t.List[bool]\n", |
| 183 | + " reason: str\n", |
| 184 | + " \n", |
| 185 | + " response = llm.generate(prompt.format(**kwargs),response_model=response_model)\n", |
| 186 | + " total = sum(response.output)\n", |
| 187 | + " if total < 1:\n", |
| 188 | + " score = 'low'\n", |
| 189 | + " else:\n", |
| 190 | + " score = 'high'\n", |
| 191 | + " return score,\"reason\"\n", |
| 192 | + "\n", |
| 193 | + "result = my_metric.score(response='my response') # result\n", |
| 194 | + "print(result)\n", |
| 195 | + "print(result.reason)" |
| 196 | + ] |
| 197 | + }, |
| 198 | + { |
| 199 | + "cell_type": "code", |
| 200 | + "execution_count": null, |
| 201 | + "metadata": {}, |
| 202 | + "outputs": [], |
| 203 | + "source": [] |
| 204 | + } |
| 205 | + ], |
| 206 | + "metadata": { |
| 207 | + "kernelspec": { |
| 208 | + "display_name": "python3", |
| 209 | + "language": "python", |
| 210 | + "name": "python3" |
| 211 | + } |
| 212 | + }, |
| 213 | + "nbformat": 4, |
| 214 | + "nbformat_minor": 2 |
| 215 | +} |
0 commit comments