|
| 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." |
| 41 | + }, |
| 42 | + "query": { |
| 43 | + "type": "string", |
| 44 | + "description": "User's question to guide the analysis" |
| 45 | + } |
| 46 | + } |
| 47 | + output_type = "array" |
| 48 | + category = ToolCategory.MULTIMODAL.value |
| 49 | + tool_sign = ToolSign.MULTIMODAL_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 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: List[bytes], |
| 87 | + query: str, |
| 88 | + ) -> 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: List 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 | + List[str]: One analysis string per file that aligns with the order |
| 102 | + """ |
| 103 | + # Send tool run message |
| 104 | + if self.observer: |
| 105 | + running_prompt = self.running_prompt_zh if self.observer.lang == "zh" else self.running_prompt_en |
| 106 | + self.observer.add_message("", ProcessType.TOOL, running_prompt) |
| 107 | + card_content = [{"icon": "file", "text": f"Analyzing file..."}] |
| 108 | + self.observer.add_message("", ProcessType.CARD, json.dumps(card_content, ensure_ascii=False)) |
| 109 | + |
| 110 | + if file_url_list is None: |
| 111 | + raise ValueError("file_url_list cannot be None") |
| 112 | + |
| 113 | + if not isinstance(file_url_list, list): |
| 114 | + raise ValueError("file_url_list must be a list of bytes") |
| 115 | + |
| 116 | + try: |
| 117 | + analysis_results: List[str] = [] |
| 118 | + |
| 119 | + for index, single_file in enumerate(file_url_list, start=1): |
| 120 | + logger.info(f"Extracting text content from file #{index}, query: {query}") |
| 121 | + filename = f"file_{index}.txt" |
| 122 | + |
| 123 | + # Step 1: Get file content |
| 124 | + raw_text = self.process_text_file(filename, single_file) |
| 125 | + |
| 126 | + if not raw_text: |
| 127 | + error_msg = f"No text content extracted from file #{index}" |
| 128 | + logger.error(error_msg) |
| 129 | + raise Exception(error_msg) |
| 130 | + |
| 131 | + logger.info(f"Analyzing text content with LLM for file #{index}, query: {query}") |
| 132 | + |
| 133 | + # Step 2: Analyze file content |
| 134 | + try: |
| 135 | + text, _ = self.analyze_file(query, raw_text) |
| 136 | + analysis_results.append(text) |
| 137 | + except Exception as analysis_error: |
| 138 | + logger.error(f"Failed to analyze file #{index}: {analysis_error}") |
| 139 | + analysis_results.append(str(analysis_error)) |
| 140 | + |
| 141 | + return analysis_results |
| 142 | + |
| 143 | + except Exception as e: |
| 144 | + logger.error(f"Error analyzing text file: {str(e)}", exc_info=True) |
| 145 | + error_msg = f"Error analyzing text file: {str(e)}" |
| 146 | + raise Exception(error_msg) |
| 147 | + |
| 148 | + |
| 149 | + def process_text_file(self, filename: str, file_content: bytes,) -> str: |
| 150 | + """ |
| 151 | + Process text file, convert to text using external API |
| 152 | + """ |
| 153 | + # file_content is byte data, need to send to API through file upload |
| 154 | + api_url = f"{self.data_process_service_url}/tasks/process_text_file" |
| 155 | + logger.info(f"Processing text file {filename} with API: {api_url}") |
| 156 | + |
| 157 | + raw_text = "" |
| 158 | + try: |
| 159 | + # Upload byte data as a file |
| 160 | + files = { |
| 161 | + 'file': (filename, file_content, 'application/octet-stream') |
| 162 | + } |
| 163 | + data = { |
| 164 | + 'chunking_strategy': 'basic', |
| 165 | + 'timeout': 60 |
| 166 | + } |
| 167 | + with httpx.Client(timeout=60) as client: |
| 168 | + response = client.post(api_url, files=files, data=data) |
| 169 | + |
| 170 | + if response.status_code == 200: |
| 171 | + result = response.json() |
| 172 | + raw_text = result.get("text", "") |
| 173 | + logger.info( |
| 174 | + f"File processed successfully: {raw_text[:200]}...{raw_text[-200:]}..., length: {len(raw_text)}") |
| 175 | + else: |
| 176 | + error_detail = response.json().get('detail', 'unknown error') if response.headers.get( |
| 177 | + 'content-type', '').startswith('application/json') else response.text |
| 178 | + logger.error( |
| 179 | + f"File processing failed (status code: {response.status_code}): {error_detail}") |
| 180 | + raise Exception(error_detail) |
| 181 | + |
| 182 | + except Exception as e: |
| 183 | + logger.error(f"Failed to process text file {filename}: {str(e)}", exc_info=True) |
| 184 | + raise |
| 185 | + |
| 186 | + return raw_text |
| 187 | + |
| 188 | + def analyze_file(self, query: str, raw_text: str,): |
| 189 | + """ |
| 190 | + Process text file, convert to text using external API |
| 191 | + """ |
| 192 | + language = getattr(self.observer, "lang", "en") if self.observer else "en" |
| 193 | + prompts = get_prompt_template(template_type='analyze_file', language=language) |
| 194 | + system_prompt_template = Template(prompts['system_prompt'], undefined=StrictUndefined) |
| 195 | + user_prompt_template = Template(prompts['user_prompt'], undefined=StrictUndefined) |
| 196 | + |
| 197 | + system_prompt = system_prompt_template.render({'query': query}) |
| 198 | + user_prompt = user_prompt_template.render({}) |
| 199 | + |
| 200 | + result, truncation_percentage = self.llm_model.analyze_long_text( |
| 201 | + text_content=raw_text, |
| 202 | + system_prompt=system_prompt, |
| 203 | + user_prompt=user_prompt |
| 204 | + ) |
| 205 | + return result.content, truncation_percentage |
0 commit comments