|
| 1 | +import typing as t |
| 2 | + |
| 3 | +from langchain_core.callbacks import Callbacks |
| 4 | +from langchain_core.outputs import Generation, LLMResult |
| 5 | +from langchain_core.prompt_values import PromptValue |
| 6 | + |
| 7 | +from ragas.cache import CacheInterface |
| 8 | +from ragas.llms import BaseRagasLLM |
| 9 | +from ragas.run_config import RunConfig |
| 10 | + |
| 11 | + |
| 12 | +class HaystackLLMWrapper(BaseRagasLLM): |
| 13 | + """ |
| 14 | + A wrapper class for using Haystack LLM generators within the Ragas framework. |
| 15 | +
|
| 16 | + This class integrates Haystack's LLM components (e.g., `OpenAIGenerator`, |
| 17 | + `HuggingFaceAPIGenerator`, etc.) into Ragas, enabling both synchronous and |
| 18 | + asynchronous text generation. |
| 19 | +
|
| 20 | + Parameters |
| 21 | + ---------- |
| 22 | + haystack_generator : AzureOpenAIGenerator | HuggingFaceAPIGenerator | HuggingFaceLocalGenerator | OpenAIGenerator |
| 23 | + An instance of a Haystack generator. |
| 24 | + run_config : RunConfig, optional |
| 25 | + Configuration object to manage LLM execution settings, by default None. |
| 26 | + cache : CacheInterface, optional |
| 27 | + A cache instance for storing results, by default None. |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__( |
| 31 | + self, |
| 32 | + haystack_generator: t.Any, |
| 33 | + run_config: t.Optional[RunConfig] = None, |
| 34 | + cache: t.Optional[CacheInterface] = None, |
| 35 | + ): |
| 36 | + super().__init__(cache=cache) |
| 37 | + |
| 38 | + # Lazy Import of required Haystack components |
| 39 | + try: |
| 40 | + from haystack import AsyncPipeline |
| 41 | + from haystack.components.generators import ( |
| 42 | + AzureOpenAIGenerator, |
| 43 | + HuggingFaceAPIGenerator, |
| 44 | + HuggingFaceLocalGenerator, |
| 45 | + OpenAIGenerator, |
| 46 | + ) |
| 47 | + except ImportError as exc: |
| 48 | + raise ImportError( |
| 49 | + "Haystack is not installed. Please install it using `pip install haystack-ai`." |
| 50 | + ) from exc |
| 51 | + |
| 52 | + # Validate haystack_generator type |
| 53 | + if not isinstance( |
| 54 | + haystack_generator, |
| 55 | + ( |
| 56 | + AzureOpenAIGenerator, |
| 57 | + HuggingFaceAPIGenerator, |
| 58 | + HuggingFaceLocalGenerator, |
| 59 | + OpenAIGenerator, |
| 60 | + ), |
| 61 | + ): |
| 62 | + raise TypeError( |
| 63 | + "Expected 'haystack_generator' to be one of: " |
| 64 | + "AzureOpenAIGenerator, HuggingFaceAPIGenerator, " |
| 65 | + "HuggingFaceLocalGenerator, or OpenAIGenerator, but received " |
| 66 | + f"{type(haystack_generator).__name__}." |
| 67 | + ) |
| 68 | + |
| 69 | + # Set up Haystack pipeline and generator |
| 70 | + self.generator = haystack_generator |
| 71 | + self.async_pipeline = AsyncPipeline() |
| 72 | + self.async_pipeline.add_component("llm", self.generator) |
| 73 | + |
| 74 | + if run_config is None: |
| 75 | + run_config = RunConfig() |
| 76 | + self.set_run_config(run_config) |
| 77 | + |
| 78 | + def is_finished(self, response: LLMResult) -> bool: |
| 79 | + return True |
| 80 | + |
| 81 | + def generate_text( |
| 82 | + self, |
| 83 | + prompt: PromptValue, |
| 84 | + n: int = 1, |
| 85 | + temperature: float = 1e-8, |
| 86 | + stop: t.Optional[t.List[str]] = None, |
| 87 | + callbacks: t.Optional[Callbacks] = None, |
| 88 | + ) -> LLMResult: |
| 89 | + |
| 90 | + component_output: t.Dict[str, t.Any] = self.generator.run(prompt.to_string()) |
| 91 | + replies = component_output.get("llm", {}).get("replies", []) |
| 92 | + output_text = replies[0] if replies else "" |
| 93 | + |
| 94 | + return LLMResult(generations=[[Generation(text=output_text)]]) |
| 95 | + |
| 96 | + async def agenerate_text( |
| 97 | + self, |
| 98 | + prompt: PromptValue, |
| 99 | + n: int = 1, |
| 100 | + temperature: t.Optional[float] = None, |
| 101 | + stop: t.Optional[t.List[str]] = None, |
| 102 | + callbacks: t.Optional[Callbacks] = None, |
| 103 | + ) -> LLMResult: |
| 104 | + # Prepare input parameters for the LLM component |
| 105 | + llm_input = { |
| 106 | + "prompt": prompt.to_string(), |
| 107 | + "generation_kwargs": {"temperature": temperature}, |
| 108 | + } |
| 109 | + |
| 110 | + # Run the async pipeline with the LLM input |
| 111 | + pipeline_output = await self.async_pipeline.run_async(data={"llm": llm_input}) |
| 112 | + replies = pipeline_output.get("llm", {}).get("replies", []) |
| 113 | + output_text = replies[0] if replies else "" |
| 114 | + |
| 115 | + return LLMResult(generations=[[Generation(text=output_text)]]) |
| 116 | + |
| 117 | + def __repr__(self) -> str: |
| 118 | + try: |
| 119 | + from haystack.components.generators import ( |
| 120 | + AzureOpenAIGenerator, |
| 121 | + HuggingFaceAPIGenerator, |
| 122 | + HuggingFaceLocalGenerator, |
| 123 | + OpenAIGenerator, |
| 124 | + ) |
| 125 | + except ImportError: |
| 126 | + return f"{self.__class__.__name__}(llm=Unknown(...))" |
| 127 | + |
| 128 | + generator = self.generator |
| 129 | + |
| 130 | + if isinstance(generator, OpenAIGenerator): |
| 131 | + model_info = generator.model |
| 132 | + elif isinstance(generator, HuggingFaceLocalGenerator): |
| 133 | + model_info = generator.huggingface_pipeline_kwargs.get("model") |
| 134 | + elif isinstance(generator, HuggingFaceAPIGenerator): |
| 135 | + model_info = generator.api_params.get("model") |
| 136 | + elif isinstance(generator, AzureOpenAIGenerator): |
| 137 | + model_info = generator.azure_deployment |
| 138 | + else: |
| 139 | + model_info = "Unknown" |
| 140 | + |
| 141 | + return f"{self.__class__.__name__}(llm={model_info}(...))" |
0 commit comments