BiGuan/Agent
0
1"""2tools/read_file.py —— 工具④:读取本地文件(万能读取器)3 4有些题目会附带一个文件(Excel 表格、PDF、Word 文档、Python 代码、纯文本等)。5这个工具负责把这些文件的内容读成文字交给大模型。它会先看文件后缀名,再决定用什么方式读:6不同格式的文件读法不一样,所以下面用一连串 if 分别处理。7 8注意:图片要用 visual_qa(看图)、音频要用 transcribe_audio(转写),它们不归这个工具管。9"""10 11import os12 13from langchain_core.tools import tool14 15 16@tool17def read_file(file_path: str) -> str:18 """Read a local file and return its content as text. Handles spreadsheets19 (.xlsx/.xls/.csv/.tsv), PDFs (.pdf), Word documents (.docx) and any plain-text or code20 file (.txt/.py/.json/.md/...). For images use `visual_qa`; for audio use21 `transcribe_audio`. Returns the full text so you can reason over it or parse it with22 `python_repl`."""23 # 先确认文件真的存在,不存在就直接返回提示(避免后面读取时报错崩溃)。24 if not os.path.exists(file_path):25 return f"File not found: {file_path}"26 ext = os.path.splitext(file_path)[1].lower() # 取出后缀名(如 ".xlsx"),转小写27 try:28 # —— Excel 表格 ——29 if ext in (".xlsx", ".xls"):30 import pandas as pd # pandas 是处理表格数据的常用库31 32 # sheet_name=None 表示"读取工作簿里的所有工作表",结果是 {表名: 表格数据} 的字典。33 sheets = pd.read_excel(file_path, sheet_name=None)34 # 把每张表都转成 CSV 文字(逗号分隔),拼起来一起返回。35 return "\n\n".join(36 f"## Sheet: {name}\n{df.to_csv(index=False)}" for name, df in sheets.items()37 )38 39 # —— CSV / TSV 文本表格 ——40 if ext in (".csv", ".tsv"):41 import pandas as pd42 43 # CSV 用逗号分隔,TSV 用制表符(Tab)分隔,这里据后缀选对分隔符。44 sep = "\t" if ext == ".tsv" else ","45 return pd.read_csv(file_path, sep=sep).to_csv(index=False)46 47 # —— PDF 文档 ——48 if ext == ".pdf":49 from pypdf import PdfReader50 51 reader = PdfReader(file_path)52 # 逐页抽取文字再用换行拼起来(有的页面抽不出文字就当空字符串处理)。53 return "\n".join((page.extract_text() or "") for page in reader.pages)54 55 # —— Word 文档 ——56 if ext == ".docx":57 import docx58 59 document = docx.Document(file_path)60 # 逐段落取文字再拼起来。61 return "\n".join(p.text for p in document.paragraphs)62 63 # —— 其它情况:当作普通纯文本/代码文件,直接按文本读 ——64 # errors="replace" 表示遇到无法识别的字符时用占位符替代,而不是报错。65 with open(file_path, "r", encoding="utf-8", errors="replace") as f:66 return f.read()67 except Exception as e:68 # 任何读取错误都转成一句说明返回,保证程序不崩。69 return f"Error reading file '{file_path}': {e}"70 