Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
response_chain.py58 linesDownload Raw Back to openapi
1"""Response parser."""2 3import json4import re5from typing import Any6 7from langchain_classic.chains.api.openapi.prompts import RESPONSE_TEMPLATE8from langchain_classic.chains.llm import LLMChain9from langchain_core.language_models import BaseLanguageModel10from langchain_core.output_parsers import BaseOutputParser11from langchain_core.prompts.prompt import PromptTemplate12 13 14class APIResponderOutputParser(BaseOutputParser):15    """Parse the response and error tags."""16 17    def _load_json_block(self, serialized_block: str) -> str:18        try:19            response_content = json.loads(serialized_block, strict=False)20            return response_content.get("response", "ERROR parsing response.")21        except json.JSONDecodeError:22            return "ERROR parsing response."23        except:24            raise25 26    def parse(self, llm_output: str) -> str:27        """Parse the response and error tags."""28        json_match = re.search(r"```json(.*?)```", llm_output, re.DOTALL)29        if json_match:30            return self._load_json_block(json_match.group(1).strip())31        else:32            raise ValueError(f"No response found in output: {llm_output}.")33 34    @property35    def _type(self) -> str:36        return "api_responder"37 38 39class APIResponderChain(LLMChain):40    """Get the response parser."""41 42    @classmethod43    def is_lc_serializable(cls) -> bool:44        return False45 46    @classmethod47    def from_llm(48        cls, llm: BaseLanguageModel, verbose: bool = True, **kwargs: Any49    ) -> LLMChain:50        """Get the response parser."""51        output_parser = APIResponderOutputParser()52        prompt = PromptTemplate(53            template=RESPONSE_TEMPLATE,54            output_parser=output_parser,55            input_variables=["response", "instructions"],56        )57        return cls(prompt=prompt, llm=llm, verbose=verbose, **kwargs)58 
codekingpro/portable-devtools · Team Ai