Team Ai
Apppublic

aphilippov/python-server-api

sourceHugging Faceapache-2.0updated 3y agoView on Hugging Face
0likes
text_analyzer_agent.py71 linesDownload Raw Back to contrib
1from autogen import oai2from autogen.agentchat.agent import Agent3from autogen.agentchat.assistant_agent import ConversableAgent4from typing import Callable, Dict, Optional, Union, List, Tuple, Any5 6system_message = """You are an expert in text analysis.7The user will give you TEXT to analyze.8The user will give you analysis INSTRUCTIONS copied twice, at both the beginning and the end.9You will follow these INSTRUCTIONS in analyzing the TEXT, then give the results of your expert analysis in the format requested."""10 11 12class TextAnalyzerAgent(ConversableAgent):13    """(Experimental) Text Analysis agent, a subclass of ConversableAgent designed to analyze text as instructed."""14 15    def __init__(16        self,17        name="analyzer",18        system_message: Optional[str] = system_message,19        human_input_mode: Optional[str] = "NEVER",20        llm_config: Optional[Union[Dict, bool]] = None,21        **kwargs,22    ):23        """24        Args:25            name (str): name of the agent.26            system_message (str): system message for the ChatCompletion inference.27            human_input_mode (str): This agent should NEVER prompt the human for input.28            llm_config (dict or False): llm inference configuration.29                Please refer to [OpenAIWrapper.create](/docs/reference/oai/client#create)30                for available options.31                To disable llm-based auto reply, set to False.32            **kwargs (dict): other kwargs in [ConversableAgent](../conversable_agent#__init__).33        """34        super().__init__(35            name=name,36            system_message=system_message,37            human_input_mode=human_input_mode,38            llm_config=llm_config,39            **kwargs,40        )41        self.register_reply(Agent, TextAnalyzerAgent._analyze_in_reply, position=2)42 43    def _analyze_in_reply(44        self,45        messages: Optional[List[Dict]] = None,46        sender: Optional[Agent] = None,47        config: Optional[Any] = None,48    ) -> Tuple[bool, Union[str, Dict, None]]:49        """Analyzes the given text as instructed, and returns the analysis as a message.50        Assumes exactly two messages containing the text to analyze and the analysis instructions.51        See Teachability.analyze for an example of how to use this method."""52        if self.llm_config is False:53            raise ValueError("TextAnalyzerAgent requires self.llm_config to be set in its base class.")54        if messages is None:55            messages = self._oai_messages[sender]  # In case of a direct call.56        assert len(messages) == 257 58        # Delegate to the analysis method.59        return True, self.analyze_text(messages[0]["content"], messages[1]["content"])60 61    def analyze_text(self, text_to_analyze, analysis_instructions):62        """Analyzes the given text as instructed, and returns the analysis."""63        # Assemble the message.64        text_to_analyze = "# TEXT\n" + text_to_analyze + "\n"65        analysis_instructions = "# INSTRUCTIONS\n" + analysis_instructions + "\n"66        msg_text = "\n".join(67            [analysis_instructions, text_to_analyze, analysis_instructions]68        )  # Repeat the instructions.69        # Generate and return the analysis string.70        return self.generate_oai_reply([{"role": "user", "content": msg_text}], None, None)[1]71