Spaces:
Sleeping
Sleeping
| # adapted from https://github.com/huggingface/smolagents/blob/main/examples/open_deep_research/scripts/text_inspector_tool.py | |
| from smolagents import Tool | |
| from smolagents.models import Model, ChatMessage | |
| class TextFileInspectorTool(Tool): | |
| name = "inspect_file_as_text" | |
| description = """You cannot load files yourself: instead call this tool to read a file as markdown text and ask questions about it. | |
| This tool handles the following file extensions: [".html", ".htm", ".xlsx", ".txt", ".pptx", ".pdf", ".docx"], and all other types of text files. IT DOES NOT HANDLE IMAGES OR AUDIO.""" | |
| inputs = { | |
| "file_path": { | |
| "description": "The path to the file you want to read as text. Must be a '.something' file, like '.pdf'. If it is an image, use the image_inspector tool instead! DO NOT use this tool for an HTML webpage: use the web_search tool instead!", | |
| "type": "string", | |
| }, | |
| "question": { | |
| "description": "[Optional]: Your question, as a natural language sentence. Provide as much context as possible. Do not pass this parameter if you just want to directly return the content of the file.", | |
| "type": "string", | |
| "nullable": True, | |
| }, | |
| } | |
| output_type = "string" | |
| def __init__(self, model: Model, text_limit: int = 100000): | |
| super().__init__() | |
| self.model = model | |
| self.text_limit = text_limit | |
| from .mdconvert import MarkdownConverter | |
| self.md_converter = MarkdownConverter() | |
| def forward(self, file_path, question: str | None = None) -> str: | |
| from smolagents.models import MessageRole | |
| result = self.md_converter.convert(file_path) | |
| if file_path[-4:] in [".png", ".jpg"]: | |
| raise Exception("Cannot use inspect_file_as_text tool with images: use image_inspector tool instead!") | |
| if ".zip" in file_path: | |
| return result.text_content | |
| if not question: | |
| return result.text_content | |
| messages = [ | |
| ChatMessage( | |
| role=MessageRole.SYSTEM, | |
| content=[ | |
| { | |
| "type": "text", | |
| "text": "You will have to write a short caption for this file, then answer this question:" | |
| + question, | |
| } | |
| ], | |
| ), | |
| ChatMessage( | |
| role=MessageRole.USER, | |
| content=[ | |
| { | |
| "type": "text", | |
| "text": "Here is the complete file:\n### " | |
| + str(result.title) | |
| + "\n\n" | |
| + result.text_content[: self.text_limit], | |
| } | |
| ], | |
| ), | |
| ChatMessage( | |
| role=MessageRole.USER, | |
| content=[ | |
| { | |
| "type": "text", | |
| "text": "Now answer the question below. Use these three headings: '1. Short answer', '2. Extremely detailed answer', '3. Additional Context on the document and question asked'." | |
| + question, | |
| } | |
| ], | |
| ), | |
| ] | |
| return self.model(messages).content | |