|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +from typing import Any, List, Optional |
| 17 | + |
| 18 | +from langchain.callbacks.manager import ( |
| 19 | + AsyncCallbackManagerForLLMRun, |
| 20 | + CallbackManagerForLLMRun, |
| 21 | +) |
| 22 | +from langchain.schema.output import GenerationChunk |
| 23 | +from langchain_community.llms import HuggingFacePipeline |
| 24 | + |
| 25 | + |
| 26 | +class HuggingFacePipelineCompatible(HuggingFacePipeline): |
| 27 | + """ |
| 28 | + Hackish way to add backward-compatibility functions to the Langchain class. |
| 29 | + TODO: Planning to add this fix directly to Langchain repo. |
| 30 | + """ |
| 31 | + |
| 32 | + def _call( |
| 33 | + self, |
| 34 | + prompt: str, |
| 35 | + stop: Optional[List[str]] = None, |
| 36 | + run_manager: Optional[CallbackManagerForLLMRun] = None, |
| 37 | + **kwargs: Any, |
| 38 | + ) -> str: |
| 39 | + """ |
| 40 | + Hackish way to perform a single llm call since Langchain dropped support |
| 41 | + """ |
| 42 | + if not isinstance(prompt, str): |
| 43 | + raise ValueError( |
| 44 | + "Argument `prompt` is expected to be a string. Instead found " |
| 45 | + f"{type(prompt)}. If you want to run the LLM on multiple prompts, use " |
| 46 | + "`generate` instead." |
| 47 | + ) |
| 48 | + |
| 49 | + # Streaming for NeMo Guardrails is not supported in sync calls. |
| 50 | + if self.model_kwargs and self.model_kwargs.get("streaming"): |
| 51 | + raise Exception( |
| 52 | + "Streaming mode not supported for HuggingFacePipeline in NeMo Guardrails!" |
| 53 | + ) |
| 54 | + |
| 55 | + llm_result = self._generate( |
| 56 | + [prompt], |
| 57 | + stop=stop, |
| 58 | + run_manager=run_manager, |
| 59 | + **kwargs, |
| 60 | + ) |
| 61 | + return llm_result.generations[0][0].text |
| 62 | + |
| 63 | + async def _acall( |
| 64 | + self, |
| 65 | + prompt: str, |
| 66 | + stop: Optional[List[str]] = None, |
| 67 | + run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, |
| 68 | + **kwargs: Any, |
| 69 | + ) -> str: |
| 70 | + """ |
| 71 | + Hackish way to add async support |
| 72 | + """ |
| 73 | + if not isinstance(prompt, str): |
| 74 | + raise ValueError( |
| 75 | + "Argument `prompt` is expected to be a string. Instead found " |
| 76 | + f"{type(prompt)}. If you want to run the LLM on multiple prompts, use " |
| 77 | + "`generate` instead." |
| 78 | + ) |
| 79 | + |
| 80 | + # Handle streaming, if the flag is set |
| 81 | + if self.model_kwargs and self.model_kwargs.get("streaming"): |
| 82 | + # Retrieve the streamer object, needs to be set in model_kwargs |
| 83 | + streamer = self.model_kwargs.get("streamer") |
| 84 | + if not streamer: |
| 85 | + raise Exception( |
| 86 | + "Cannot stream, please add HuggingFace streamer object to model_kwargs!" |
| 87 | + ) |
| 88 | + |
| 89 | + loop = asyncio.get_running_loop() |
| 90 | + |
| 91 | + # Pass the asyncio loop to the stream so that it can send back |
| 92 | + # the chunks in the queue. |
| 93 | + streamer.loop = loop |
| 94 | + |
| 95 | + # Launch the generation in a separate task. |
| 96 | + generation_kwargs = dict( |
| 97 | + prompts=[prompt], |
| 98 | + stop=stop, |
| 99 | + run_manager=run_manager, |
| 100 | + **kwargs, |
| 101 | + ) |
| 102 | + loop.create_task(self._agenerate(**generation_kwargs)) |
| 103 | + |
| 104 | + # And start waiting for the chunks to come in. |
| 105 | + completion = "" |
| 106 | + async for item in streamer: |
| 107 | + completion += item |
| 108 | + chunk = GenerationChunk(text=item) |
| 109 | + if run_manager: |
| 110 | + await run_manager.on_llm_new_token(item, chunk=chunk) |
| 111 | + |
| 112 | + return completion |
| 113 | + |
| 114 | + llm_result = await self._agenerate( |
| 115 | + [prompt], |
| 116 | + stop=stop, |
| 117 | + run_manager=run_manager, |
| 118 | + **kwargs, |
| 119 | + ) |
| 120 | + return llm_result.generations[0][0].text |
0 commit comments