Spaces:
Sleeping
Sleeping
Download agent.py from olaf-bu/Final_Assignment: direct link, hf CLI and curl.
- Browser
- Download file 2.11 kB
-
https://huggingface.co/spaces/olaf-bu/Final_Assignment/resolve/main/agent.py
- Command line
-
hf download hf://spaces/olaf-bu/Final_Assignment/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/olaf-bu/Final_Assignment/resolve/main/agent.py
2.11 kB
| from logging import getLogger | |
| from typing import Any, List, Optional | |
| from smolagents import CodeAgent | |
| logger = getLogger(__name__) | |
| class Agent: | |
| """ | |
| Agent class that wraps a CodeAgent and provides a callable interface for answering questions. | |
| Args: | |
| model (Any): The language model to use. | |
| tools (Optional[List[Any]]): List of tools to provide to the agent. | |
| prompt (Optional[str]): Custom prompt template for the agent. | |
| """ | |
| def __init__(self, model: Any, | |
| tools: Optional[List[Any]] = None, | |
| prompt: Optional[str] = None, | |
| ): | |
| logger.info('Initializing Agent') | |
| self.model = model | |
| self.tools = tools | |
| self.imports = ['pandas', 'numpy', 'os', 'requests', 'markdownify ', | |
| 'tempfile', 'datetime', 'json', 'time', 're', | |
| 'openpyxl', 'pathlib', 'sys', 'duckduckgo_search' | |
| ] | |
| self.agent = CodeAgent( | |
| model=self.model, | |
| tools=self.tools, | |
| add_base_tools=True, | |
| additional_authorized_imports=self.imports, | |
| ) | |
| if prompt is None: | |
| logger.info('reading default system prompt') | |
| with open('system_prompt2.txt') as prompt_file: | |
| prompt = prompt_file.read() | |
| self.prompt = prompt | |
| logger.info('Agent initialized') | |
| def __call__(self, question: str, file_path: Optional[str] = None) -> str: | |
| """ | |
| Run the agent to answer a question, optionally using a file as context. | |
| Args: | |
| question (str): The question to answer. | |
| file_path (Optional[str]): Path to a file to use as context (if any). | |
| Returns: | |
| str: The agent's answer as a string. | |
| """ | |
| logger.info('question is [%s], file_path %s', question, file_path) | |
| answer = self.agent.run(self.prompt.format(question=question, context=file_path)) | |
| logger.info('got answer [%s]', answer) | |
| answer = str(answer).strip("'").strip('"').strip() | |
| return answer | |