|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +import typing as t |
| 5 | +from abc import ABC, abstractmethod |
| 6 | + |
| 7 | +from langchain.chat_models import AzureChatOpenAI, ChatOpenAI |
| 8 | +from langchain.chat_models.base import BaseChatModel |
| 9 | +from langchain.llms import AzureOpenAI, OpenAI |
| 10 | +from langchain.llms.base import BaseLLM |
| 11 | +from langchain.schema import LLMResult |
| 12 | + |
| 13 | +from ragas.async_utils import run_async_tasks |
| 14 | + |
| 15 | +if t.TYPE_CHECKING: |
| 16 | + from langchain.callbacks.base import Callbacks |
| 17 | + from langchain.prompts import ChatPromptTemplate |
| 18 | + |
| 19 | + |
| 20 | +def isOpenAI(llm: BaseLLM | BaseChatModel) -> bool: |
| 21 | + return isinstance(llm, OpenAI) or isinstance(llm, ChatOpenAI) |
| 22 | + |
| 23 | + |
| 24 | +# have to specify it twice for runtime and static checks |
| 25 | +MULTIPLE_COMPLETION_SUPPORTED = [OpenAI, ChatOpenAI, AzureOpenAI, AzureChatOpenAI] |
| 26 | +MultipleCompletionSupportedLLM = t.Union[ |
| 27 | + OpenAI, ChatOpenAI, AzureOpenAI, AzureChatOpenAI |
| 28 | +] |
| 29 | + |
| 30 | + |
| 31 | +class BaseRagasLLM(ABC): |
| 32 | + """ |
| 33 | + BaseLLM is the base class for all LLMs. It provides a consistent interface for other |
| 34 | + classes that interact with LLMs like Langchains, LlamaIndex, LiteLLM etc. Handles |
| 35 | + multiple_completions even if not supported by the LLM. |
| 36 | +
|
| 37 | + It currently takes in ChatPromptTemplates and returns LLMResults which are Langchain |
| 38 | + primitives. |
| 39 | + """ |
| 40 | + |
| 41 | + # supports multiple compeletions for the given prompt |
| 42 | + n_completions_supported: bool = False |
| 43 | + |
| 44 | + @property |
| 45 | + @abstractmethod |
| 46 | + def llm(self): |
| 47 | + ... |
| 48 | + |
| 49 | + @abstractmethod |
| 50 | + def generate( |
| 51 | + self, |
| 52 | + prompts: list[str], |
| 53 | + n: int = 1, |
| 54 | + temperature: float = 0, |
| 55 | + callbacks: t.Optional[Callbacks] = None, |
| 56 | + ) -> list[list[str]]: |
| 57 | + ... |
| 58 | + |
| 59 | + |
| 60 | +class LangchainLLM(BaseRagasLLM): |
| 61 | + n_completions_supported: bool = True |
| 62 | + |
| 63 | + def __init__(self, llm: BaseLLM | BaseChatModel): |
| 64 | + self.langchain_llm = llm |
| 65 | + |
| 66 | + @property |
| 67 | + def llm(self): |
| 68 | + return self.langchain_llm |
| 69 | + |
| 70 | + @staticmethod |
| 71 | + def llm_supports_completions(llm): |
| 72 | + for llm_type in MULTIPLE_COMPLETION_SUPPORTED: |
| 73 | + if isinstance(llm, llm_type): |
| 74 | + return True |
| 75 | + |
| 76 | + def generate_multiple_completions( |
| 77 | + self, |
| 78 | + prompts: list[ChatPromptTemplate], |
| 79 | + n: int = 1, |
| 80 | + callbacks: t.Optional[Callbacks] = None, |
| 81 | + ) -> LLMResult: |
| 82 | + self.langchain_llm = t.cast(MultipleCompletionSupportedLLM, self.langchain_llm) |
| 83 | + old_n = self.langchain_llm.n |
| 84 | + self.langchain_llm.n = n |
| 85 | + |
| 86 | + if isinstance(self.llm, BaseLLM): |
| 87 | + ps = [p.format() for p in prompts] |
| 88 | + result = self.llm.generate(ps, callbacks=callbacks) |
| 89 | + else: # if BaseChatModel |
| 90 | + ps = [p.format_messages() for p in prompts] |
| 91 | + result = self.llm.generate(ps, callbacks=callbacks) |
| 92 | + self.llm.n = old_n |
| 93 | + |
| 94 | + return result |
| 95 | + |
| 96 | + async def generate_completions( |
| 97 | + self, |
| 98 | + prompts: list[ChatPromptTemplate], |
| 99 | + callbacks: t.Optional[Callbacks] = None, |
| 100 | + ) -> LLMResult: |
| 101 | + if isinstance(self.llm, BaseLLM): |
| 102 | + ps = [p.format() for p in prompts] |
| 103 | + result = await self.llm.agenerate(ps, callbacks=callbacks) |
| 104 | + else: # if BaseChatModel |
| 105 | + ps = [p.format_messages() for p in prompts] |
| 106 | + result = await self.llm.agenerate(ps, callbacks=callbacks) |
| 107 | + |
| 108 | + return result |
| 109 | + |
| 110 | + def generate( |
| 111 | + self, |
| 112 | + prompts: list[ChatPromptTemplate], |
| 113 | + n: int = 1, |
| 114 | + temperature: float = 0, |
| 115 | + callbacks: t.Optional[Callbacks] = None, |
| 116 | + ) -> LLMResult: |
| 117 | + # set temperature to 0.2 for multiple completions |
| 118 | + temperature = 0.2 if n > 1 else 0 |
| 119 | + self.llm.temperature = temperature |
| 120 | + |
| 121 | + if self.llm_supports_completions(self.llm): |
| 122 | + return self.generate_multiple_completions(prompts, n, callbacks) |
| 123 | + else: # call generate_completions n times to mimic multiple completions |
| 124 | + list_llmresults = run_async_tasks( |
| 125 | + [self.generate_completions(prompts, callbacks) for _ in range(n)] |
| 126 | + ) |
| 127 | + |
| 128 | + # fill results as if the LLM supported multiple completions |
| 129 | + generations = [] |
| 130 | + for i in range(len(prompts)): |
| 131 | + completions = [] |
| 132 | + for result in list_llmresults: |
| 133 | + completions.append(result.generations[i][0]) |
| 134 | + generations.append(completions) |
| 135 | + |
| 136 | + # compute total token usage by adding individual token usage |
| 137 | + llm_output = list_llmresults[0].llm_output |
| 138 | + if "token_usage" in llm_output: |
| 139 | + sum_prompt_tokens = 0 |
| 140 | + sum_completion_tokens = 0 |
| 141 | + sum_total_tokens = 0 |
| 142 | + for result in list_llmresults: |
| 143 | + token_usage = result.llm_output["token_usage"] |
| 144 | + sum_prompt_tokens += token_usage["prompt_tokens"] |
| 145 | + sum_completion_tokens += token_usage["completion_tokens"] |
| 146 | + sum_total_tokens += token_usage["total_tokens"] |
| 147 | + |
| 148 | + llm_output["token_usage"] = { |
| 149 | + "prompt_tokens": sum_prompt_tokens, |
| 150 | + "completion_tokens": sum_completion_tokens, |
| 151 | + "sum_total_tokens": sum_total_tokens, |
| 152 | + } |
| 153 | + |
| 154 | + return LLMResult(generations=generations, llm_output=llm_output) |
| 155 | + |
| 156 | + |
| 157 | +def llm_factory() -> LangchainLLM: |
| 158 | + oai_key = os.getenv("OPENAI_API_KEY", "no-key") |
| 159 | + openai_llm = ChatOpenAI(openai_api_key=oai_key) |
| 160 | + return LangchainLLM(llm=openai_llm) |
0 commit comments