|
| 1 | +""" |
| 2 | +Analyze Text File Tool |
| 3 | +
|
| 4 | +Extracts content from text files (excluding images) and analyzes it using a large language model. |
| 5 | +Supports files from S3, HTTP, and HTTPS URLs. |
| 6 | +""" |
| 7 | +import json |
| 8 | +import logging |
| 9 | +from typing import List, Optional, Union |
| 10 | + |
| 11 | +import httpx |
| 12 | +from jinja2 import Template, StrictUndefined |
| 13 | +from pydantic import Field |
| 14 | +from smolagents.tools import Tool |
| 15 | + |
| 16 | +from nexent.core import MessageObserver |
| 17 | +from nexent.core.utils.observer import ProcessType |
| 18 | +from nexent.core.utils.prompt_template_utils import get_prompt_template |
| 19 | +from nexent.core.utils.tools_common_message import ToolCategory, ToolSign |
| 20 | +from nexent.storage import MinIOStorageClient |
| 21 | +from nexent.multi_modal.load_save_object import LoadSaveObjectManager |
| 22 | + |
| 23 | + |
| 24 | +logger = logging.getLogger("analyze_text_file_tool") |
| 25 | + |
| 26 | + |
| 27 | +class AnalyzeTextFileTool(Tool): |
| 28 | + """Tool for analyzing text file content using a large language model""" |
| 29 | + |
| 30 | + name = "analyze_text_file" |
| 31 | + description = ( |
| 32 | + "Extract content from text files and analyze them using a large language model based on your query. " |
| 33 | + "Supports multiple files from S3 URLs (s3://bucket/key or /bucket/key), HTTP, and HTTPS URLs. " |
| 34 | + "The tool will extract the text content from each file and return an analysis based on your question." |
| 35 | + ) |
| 36 | + |
| 37 | + inputs = { |
| 38 | + "file_url_list": { |
| 39 | + "type": "array", |
| 40 | + "description": "List of file URLs (S3, HTTP, or HTTPS). Supports s3://bucket/key, /bucket/key, http://, and https:// URLs. Can also accept a single file URL which will be treated as a list with one element." |
| 41 | + }, |
| 42 | + "query": { |
| 43 | + "type": "string", |
| 44 | + "description": "User's question to guide the analysis" |
| 45 | + } |
| 46 | + } |
| 47 | + output_type = "string" |
| 48 | + category = ToolCategory.FILE.value |
| 49 | + tool_sign = ToolSign.FILE_OPERATION.value |
| 50 | + |
| 51 | + def __init__( |
| 52 | + self, |
| 53 | + storage_client: Optional[MinIOStorageClient] = Field( |
| 54 | + description="Storage client for downloading files from S3 URLs、HTTP URLs、HTTPS URLs.", |
| 55 | + default=None, |
| 56 | + exclude=True |
| 57 | + ), |
| 58 | + observer: MessageObserver = Field( |
| 59 | + description="Message observer", |
| 60 | + default=None, |
| 61 | + exclude=True |
| 62 | + ), |
| 63 | + data_process_service_url: str = Field( |
| 64 | + description="URL of data process service", |
| 65 | + default=None, |
| 66 | + exclude=True), |
| 67 | + llm_model: str = Field( |
| 68 | + description="The LLM model to use", |
| 69 | + default=None, |
| 70 | + exclude=True) |
| 71 | + ): |
| 72 | + super().__init__() |
| 73 | + self.storage_client = storage_client |
| 74 | + self.observer = observer |
| 75 | + self.llm_model = llm_model |
| 76 | + self.data_process_service_url = data_process_service_url |
| 77 | + self.mm = LoadSaveObjectManager(storage_client=self.storage_client) |
| 78 | + |
| 79 | + self.running_prompt_zh = "正在分析文本文件..." |
| 80 | + self.running_prompt_en = "Analyzing text file..." |
| 81 | + # Dynamically apply the load_object decorator to forward method |
| 82 | + self.forward = self.mm.load_object(input_names=["file_url_list"])(self._forward_impl) |
| 83 | + |
| 84 | + def _forward_impl( |
| 85 | + self, |
| 86 | + file_url_list: Union[bytes, List[bytes]], |
| 87 | + query: str, |
| 88 | + ) -> Union[str, List[str]]: |
| 89 | + """ |
| 90 | + Analyze text file content using a large language model. |
| 91 | +
|
| 92 | + Note: This method is wrapped by load_object decorator which downloads |
| 93 | + the image from S3 URL, HTTP URL, or HTTPS URL and passes bytes to this method. |
| 94 | +
|
| 95 | + Args: |
| 96 | + file_url_list: File bytes or a sequence of file bytes (converted from URLs by the decorator). |
| 97 | + The load_object decorator converts URLs to bytes before calling this method. |
| 98 | + query: User's question to guide the analysis |
| 99 | +
|
| 100 | + Returns: |
| 101 | + Union[str, List[str]]: Single analysis string for one file or a list |
| 102 | + of analysis strings that align with the order of the provided files. |
| 103 | + """ |
| 104 | + # Send tool run message |
| 105 | + if self.observer: |
| 106 | + running_prompt = self.running_prompt_zh if self.observer.lang == "zh" else self.running_prompt_en |
| 107 | + self.observer.add_message("", ProcessType.TOOL, running_prompt) |
| 108 | + card_content = [{"icon": "file", "text": f"Analyzing file..."}] |
| 109 | + self.observer.add_message("", ProcessType.CARD, json.dumps(card_content, ensure_ascii=False)) |
| 110 | + |
| 111 | + if file_url_list is None: |
| 112 | + raise ValueError("file_url_list must contain at least one file") |
| 113 | + |
| 114 | + if isinstance(file_url_list, (list, tuple)): |
| 115 | + file_inputs: List[bytes] = list(file_url_list) |
| 116 | + elif isinstance(file_url_list, bytes): |
| 117 | + file_inputs = [file_url_list] |
| 118 | + else: |
| 119 | + raise ValueError("file_url_list must be bytes or a list/tuple of bytes") |
| 120 | + |
| 121 | + try: |
| 122 | + analysis_results: List[str] = [] |
| 123 | + |
| 124 | + for index, single_file in enumerate(file_inputs, start=1): |
| 125 | + logger.info(f"Extracting text content from file #{index}, query: {query}") |
| 126 | + filename = f"file_{index}.txt" |
| 127 | + |
| 128 | + # Step 1: Get file content |
| 129 | + raw_text = self.process_text_file(filename, single_file) |
| 130 | + |
| 131 | + if not raw_text: |
| 132 | + error_msg = f"No text content extracted from file #{index}" |
| 133 | + logger.error(error_msg) |
| 134 | + raise Exception(error_msg) |
| 135 | + |
| 136 | + logger.info(f"Analyzing text content with LLM for file #{index}, query: {query}") |
| 137 | + |
| 138 | + # Step 2: Analyze file content |
| 139 | + try: |
| 140 | + text, _ = self.analyze_file(query, raw_text) |
| 141 | + analysis_results.append(text) |
| 142 | + except Exception as analysis_error: |
| 143 | + logger.error(f"Failed to analyze file #{index}: {analysis_error}") |
| 144 | + analysis_results.append(str(analysis_error)) |
| 145 | + |
| 146 | + if len(analysis_results) == 1: |
| 147 | + return analysis_results[0] |
| 148 | + return analysis_results |
| 149 | + |
| 150 | + except Exception as e: |
| 151 | + logger.error(f"Error analyzing text file: {str(e)}", exc_info=True) |
| 152 | + error_msg = f"Error analyzing text file: {str(e)}" |
| 153 | + raise Exception(error_msg) |
| 154 | + |
| 155 | + |
| 156 | + def process_text_file(self, filename: str, file_content: bytes,) -> str: |
| 157 | + """ |
| 158 | + Process text file, convert to text using external API |
| 159 | + """ |
| 160 | + # file_content is byte data, need to send to API through file upload |
| 161 | + api_url = f"{self.data_process_service_url}/tasks/process_text_file" |
| 162 | + logger.info(f"Processing text file {filename} with API: {api_url}") |
| 163 | + |
| 164 | + raw_text = "" |
| 165 | + try: |
| 166 | + # Upload byte data as a file |
| 167 | + files = { |
| 168 | + 'file': (filename, file_content, 'application/octet-stream') |
| 169 | + } |
| 170 | + data = { |
| 171 | + 'chunking_strategy': 'basic', |
| 172 | + 'timeout': 60 |
| 173 | + } |
| 174 | + with httpx.Client(timeout=60) as client: |
| 175 | + response = client.post(api_url, files=files, data=data) |
| 176 | + |
| 177 | + if response.status_code == 200: |
| 178 | + result = response.json() |
| 179 | + raw_text = result.get("text", "") |
| 180 | + logger.info( |
| 181 | + f"File processed successfully: {raw_text[:200]}...{raw_text[-200:]}..., length: {len(raw_text)}") |
| 182 | + else: |
| 183 | + error_detail = response.json().get('detail', 'unknown error') if response.headers.get( |
| 184 | + 'content-type', '').startswith('application/json') else response.text |
| 185 | + logger.error( |
| 186 | + f"File processing failed (status code: {response.status_code}): {error_detail}") |
| 187 | + raise Exception(error_detail) |
| 188 | + |
| 189 | + except Exception as e: |
| 190 | + logger.error(f"Failed to process text file {filename}: {str(e)}", exc_info=True) |
| 191 | + raise |
| 192 | + |
| 193 | + return raw_text |
| 194 | + |
| 195 | + def analyze_file(self, query: str, raw_text: str,): |
| 196 | + """ |
| 197 | + Process text file, convert to text using external API |
| 198 | + """ |
| 199 | + language = getattr(self.observer, "lang", "en") if self.observer else "en" |
| 200 | + prompts = get_prompt_template(template_type='analyze_file', language=language) |
| 201 | + system_prompt_template = Template(prompts['system_prompt'], undefined=StrictUndefined) |
| 202 | + user_prompt_template = Template(prompts['user_prompt'], undefined=StrictUndefined) |
| 203 | + |
| 204 | + system_prompt = system_prompt_template.render({'query': query}) |
| 205 | + user_prompt = user_prompt_template.render({}) |
| 206 | + |
| 207 | + result, truncation_percentage = self.llm_model.analyze_long_text( |
| 208 | + text_content=raw_text, |
| 209 | + system_prompt=system_prompt, |
| 210 | + user_prompt=user_prompt |
| 211 | + ) |
| 212 | + return result.content, truncation_percentage |
0 commit comments