File size: 19,368 Bytes
b3f9415
2834b30
 
 
 
 
 
b3f9415
 
 
 
 
 
 
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3f9415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2834b30
b3f9415
2834b30
b3f9415
 
 
 
 
 
 
 
6d5c14c
b3f9415
 
 
 
 
 
 
 
 
 
 
 
92357df
b3f9415
 
 
 
 
 
 
 
 
 
 
 
 
92357df
b3f9415
 
 
 
 
 
 
 
 
 
2834b30
b3f9415
 
b16840f
b3f9415
 
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
3b7ebef
2834b30
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
3b7ebef
2834b30
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7ebef
2834b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
import os
import json
import base64
from pathlib import Path

from dotenv import load_dotenv
load_dotenv()

from langchain_community.tools import DuckDuckGoSearchRun
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_community.document_loaders import WikipediaLoader
from langchain_community.document_loaders import ArxivLoader
from langchain_core.tools import tool

from huggingface_hub import InferenceClient

from utils import load_config, load_prompt

_config = load_config()
_vlm_model_name = _config["models"]["vlm"]["model_name"]
_vlm_system_prompt = load_prompt("prompts/vlm_prompt.yaml").content
_asr_model_name = _config["models"]["asr"]["model_name"]
_hf_client = InferenceClient(token=os.getenv("HF_INFERENCE_KEY"))

_ddg_search = None
_tavily_search = None

def _get_ddg():
    global _ddg_search
    if _ddg_search is None:
        _ddg_search = DuckDuckGoSearchRun()
    return _ddg_search

def _get_tavily():
    global _tavily_search
    if _tavily_search is None:
        _tavily_search = TavilySearchResults(max_results=3)
    return _tavily_search

# ============================================
# Basic Tools
# ============================================

@tool
def calculator(a: float, b: float, type: str) -> float:
    """Performs mathematical calculations, addition, subtraction, multiplication, division, modulus.
    Args: 
        a (float): first float number
        b (float): second float number
        type (str): the type of calculation to perform, can be addition, subtraction, multiplication, division, modulus
    """

    if type == "addition":
        return a + b
    elif type == "subtraction":
        return a - b
    elif type == "multiplication":
        return a * b
    elif type == "division":
        if b == 0:
            raise ValueError("Cannot divide by zero.")
        return a / b
    elif type == "modulus":
        return a % b
    else:
        raise TypeError(f"{type} is not an option for type, choose one of addition, subtraction, multiplication, division, modulus")

@tool
def duck_web_search(query: str) -> str:
    """Use DuckDuckGo to search the web.

    Args:
        query: The search query.
    """
    search = _get_ddg().invoke(input=query)
    
    return {"duckduckgo_web_search": search}

@tool
def wiki_search(query: str) -> str:
    """Search Wikipedia for a query and return maximum 3 results.
    
    Args:
        query: The search query."""
    documents = WikipediaLoader(query=query, load_max_docs=3).load()
    processed_documents = "\n\n---\n\n".join(
        [
            f'Document title: {document.metadata.get("title", "")}. Summary: {document.metadata.get("summary", "")}. Documents details: {document.page_content}'
            for document in documents
        ])
    return {"wiki_results": processed_documents}

@tool
def arxiv_search(query: str) -> str:
    """Search Arxiv for a query and return maximum 3 result.
    
    Args:
        query: The search query."""
    documents = ArxivLoader(query=query, load_max_docs=3).load()
    processed_documents = "\n\n---\n\n".join(
        [
            f'Document title: {document.metadata.get("title", "")}. Summary: {document.metadata.get("summary", "")}. Documents details: {document.page_content}'
            for document in documents
        ])
    return {"arxiv_results": processed_documents}

@tool
def tavily_web_search(query: str) -> str:
    """Search the web using Tavily for a query and return maximum 3 results.
    
    Args:
        query: The search query."""
    search_documents = _get_tavily().invoke(input=query)
    web_results = "\n\n---\n\n".join(
        [
            f'Document title: {document["title"]}. Contents: {document["content"]}. Relevance Score: {document["score"]}'
            for document in search_documents
        ])
    return {"web_results": web_results}


@tool
def fetch_webpage(url: str) -> str:
    """
    Fetch and extract the main text content from a webpage.
    Use this when a search result points to a specific URL you need to read in full.

    Args:
        url: The full URL of the page to fetch.

    Returns:
        The extracted text content of the page.
    """
    import trafilatura
    try:
        downloaded = trafilatura.fetch_url(url)
        if downloaded is None:
            return f"[fetch_webpage] could not fetch {url}"
        text = trafilatura.extract(downloaded, include_tables=True, include_links=False)
        if text is None:
            return f"[fetch_webpage] could not extract content from {url}"
        return f"Page content from {url}:\n\n{text}"
    except Exception as e:
        return f"[fetch_webpage] failed: {e}"


@tool
def python_eval(code: str) -> str:
    """
    Execute a Python code snippet and return its stdout output.
    Use this when a question asks what a script outputs, or when computation requires running code.

    Args:
        code: Python source code to execute.

    Returns:
        The stdout output of the code, or an error/timeout message.
    """
    import subprocess
    import tempfile
    try:
        with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
            f.write(code)
            tmp_path = f.name
        result = subprocess.run(
            ['python3', tmp_path],
            capture_output=True, text=True, timeout=30
        )
        os.unlink(tmp_path)
        if result.returncode == 0:
            return f"Output:\n{result.stdout}"
        return f"[python_eval] exit {result.returncode}:\n{result.stderr}"
    except subprocess.TimeoutExpired:
        return "[python_eval] execution timed out (30s limit)"
    except Exception as e:
        return f"[python_eval] failed: {e}"


# ============================================
# VLM Tool
# ============================================

@tool
def analyze_image(image_path: str, question: str) -> str:
    """
    Analyze an image using a Vision Language Model (VLM) to answer a specific question.
    
    Args:
        image_path: Path to the image file (JPG, PNG).
        question: The specific question to answer about the image.
    
    Returns:
        A detailed description or answer based on the visual content.
    """
    try:
        if not os.path.exists(image_path):
            return f"[analyze_image] image file not found at {image_path}"

        with open(image_path, "rb") as img_file:
            image_data = base64.b64encode(img_file.read()).decode("utf-8")
        ext = Path(image_path).suffix.lower().lstrip(".")
        mime_type = "image/jpeg" if ext in ("jpg", "jpeg") else f"image/{ext}"
        image_url = f"data:{mime_type};base64,{image_data}"

        messages = [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": image_url}},
                    {"type": "text", "text": f"{_vlm_system_prompt}\n\nQuestion: {question}"}
                ]
            }
        ]

        output = _hf_client.chat_completion(
            messages=messages,
            model=_vlm_model_name,
            max_tokens=1000
        )

        return output.choices[0].message.content

    except Exception as e:
        return f"[analyze_image] VLM call failed: {e}"


# ============================================
# Document Processing Tools
# ============================================

@tool
def read_pdf(file_path: str) -> str:
    """
    Extract text content from a PDF file.
    
    Args:
        file_path: Path to the PDF file to read.
        
    Returns:
        The text content of the PDF, with page separators.
    """
    from pypdf import PdfReader
    
    try:
        reader = PdfReader(file_path)
        text = []
        for i, page in enumerate(reader.pages):
            page_text = page.extract_text()
            if page_text:
                text.append(f"--- Page {i+1} ---\n{page_text}")
        
        return "\n\n".join(text) if text else "[Empty PDF]"
    except Exception as e:
        return f"[read_pdf] failed to read PDF: {e}"


@tool
def read_docx(file_path: str) -> str:
    """
    Extract text content from a Word document (.docx).
    
    Args:
        file_path: Path to the Word document to read.
        
    Returns:
        The text content of the document.
    """
    from docx import Document
    
    try:
        doc = Document(file_path)
        text_parts = []

        paragraphs = [para.text for para in doc.paragraphs if para.text.strip()]
        if paragraphs:
            text_parts.append("\n".join(paragraphs))

        for i, table in enumerate(doc.tables):
            rows = [" | ".join(cell.text.strip() for cell in row.cells) for row in table.rows]
            rows = [r for r in rows if r.strip()]
            if rows:
                text_parts.append(f"--- Table {i+1} ---\n" + "\n".join(rows))

        return "\n\n".join(text_parts) if text_parts else "[Empty document]"
    except Exception as e:
        return f"[read_docx] failed to read DOCX: {e}"


@tool
def read_pptx(file_path: str) -> str:
    """
    Extract text content from a PowerPoint presentation (.pptx).
    
    Args:
        file_path: Path to the PowerPoint file to read.
        
    Returns:
        The text content from all slides.
    """
    from pptx import Presentation
    
    try:
        prs = Presentation(file_path)
        text = []
        
        for slide_num, slide in enumerate(prs.slides, 1):
            slide_text = [f"--- Slide {slide_num} ---"]
            for shape in slide.shapes:
                if hasattr(shape, "text") and shape.text.strip():
                    slide_text.append(shape.text)
            if len(slide_text) > 1:
                text.append("\n".join(slide_text))
        
        return "\n\n".join(text) if text else "[Empty presentation]"
    except Exception as e:
        return f"[read_pptx] failed to read PPTX: {e}"


@tool
def read_text_file(file_path: str) -> str:
    """
    Read content from a plain text file (.txt).
    
    Args:
        file_path: Path to the text file to read.
        
    Returns:
        The content of the text file.
    """
    try:
        with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
            return f.read()
    except Exception as e:
        return f"[read_text_file] failed: {e}"


# ============================================
# Data Processing Tools (using polars)
# ============================================

@tool
def read_csv(file_path: str) -> str:
    """
    Read and analyze a CSV file using polars.
    
    Args:
        file_path: Path to the CSV file to read.
        
    Returns:
        Summary of the CSV including schema, row count, and data preview.
    """
    import polars as pl
    
    try:
        df = pl.read_csv(file_path)
        
        output = f"CSV File — {len(df)} rows, {len(df.columns)} columns\n"
        output += f"Columns: {df.columns}\n\n"
        output += f"Column Statistics:\n{df.describe()}\n\n"
        output += f"Data (first 20 rows):\n{df.head(20)}"
        if len(df) <= 50:
            output += f"\n\nComplete data:\n{df}"
        return output
    except Exception as e:
        return f"[read_csv] failed to read CSV: {e}"


@tool
def read_excel(file_path: str, sheet_id: int = 0) -> str:
    """
    Read and analyze an Excel file (.xlsx) using polars.
    
    Args:
        file_path: Path to the Excel file to read.
        sheet_id: The sheet index to read (0-based). Default is 0 (first sheet).
        
    Returns:
        Summary of the Excel sheet including schema, row count, and data preview.
    """
    import polars as pl
    import openpyxl

    try:
        wb = openpyxl.load_workbook(file_path, read_only=True)
        sheet_names = wb.sheetnames
        wb.close()
    except Exception:
        sheet_names = []

    try:
        df = pl.read_excel(file_path, sheet_id=sheet_id)
        sheet_label = sheet_names[sheet_id] if sheet_id < len(sheet_names) else str(sheet_id)

        output = f"Excel File — Available sheets: {sheet_names}\n\n"
        output += f"Sheet {sheet_id} ('{sheet_label}') — {len(df)} rows, {len(df.columns)} columns\n"
        output += f"Columns: {df.columns}\n\n"
        output += f"Column Statistics:\n{df.describe()}\n\n"
        output += f"Data (first 20 rows):\n{df.head(20)}"
        if len(df) <= 50:
            output += f"\n\nComplete data:\n{df}"
        return output
    except Exception as e:
        return f"[read_excel] failed to read Excel: {e}"


@tool
def read_jsonld(file_path: str) -> str:
    """
    Read and parse a JSON-LD file.
    
    Args:
        file_path: Path to the JSON-LD file to read.
        
    Returns:
        The formatted JSON content.
    """
    try:
        with open(file_path, 'r') as f:
            data = json.load(f)
        return f"JSON-LD Content:\n{json.dumps(data, indent=2)}"
    except Exception as e:
        return f"[read_jsonld] failed to read JSON-LD: {e}"


@tool
def read_pdb(file_path: str) -> str:
    """
    Read and analyze a PDB (Protein Data Bank) file for protein structure analysis.
    
    Args:
        file_path: Path to the PDB file to read.
        
    Returns:
        Analysis of the protein structure including atoms, chains, and coordinates.
    """
    from Bio.PDB import PDBParser
    import numpy as np
    
    try:
        parser = PDBParser(QUIET=True)
        structure = parser.get_structure("protein", file_path)
        
        info = ["=== PDB Structure Analysis ==="]
        
        atoms = list(structure.get_atoms())
        info.append(f"Total atoms: {len(atoms)}")
        
        for model in structure:
            info.append(f"\nModel {model.id}:")
            for chain in model:
                residues = list(chain.get_residues())
                info.append(f"  Chain {chain.id}: {len(residues)} residues")
        
        if len(atoms) >= 2:
            info.append("\nFirst atoms (for distance calculations):")
            for i, atom in enumerate(atoms[:5]):
                coord = atom.get_coord()
                info.append(
                    f"  Atom {i+1}: {atom.get_name()} at "
                    f"[{coord[0]:.4f}, {coord[1]:.4f}, {coord[2]:.4f}]"
                )
            
            dist = np.linalg.norm(atoms[0].get_coord() - atoms[1].get_coord())
            info.append(f"\nDistance between first two atoms: {dist:.4f} Angstroms")
        
        return "\n".join(info)
    except Exception as e:
        return f"[read_pdb] failed to read PDB: {e}"


# ============================================
# Audio Processing Tools
# ============================================

@tool
def transcribe_audio(file_path: str) -> str:
    """
    Transcribe an audio file (MP3, WAV, etc.) to text using Whisper.
    
    Args:
        file_path: Path to the audio file to transcribe.
        
    Returns:
        The transcribed text from the audio.
    """
    try:
        result = _hf_client.automatic_speech_recognition(audio=file_path, model=_asr_model_name)
        return f"Audio Transcription:\n{result.text}"
    except Exception as e:
        return f"[transcribe_audio] failed: {e}"


# ============================================
# Code Processing Tools
# ============================================

@tool
def read_python_file(file_path: str) -> str:
    """
    Read a Python source code file.
    
    Args:
        file_path: Path to the Python file to read.
        
    Returns:
        The Python code content.
    """
    try:
        with open(file_path, 'r') as f:
            code = f.read()
        return f"Python Code:\n```python\n{code}\n```"
    except Exception as e:
        return f"[read_python_file] failed: {e}"


# ============================================
# Archive Processing Tools
# ============================================

@tool
def extract_zip(file_path: str) -> str:
    """
    Extract a ZIP archive and list its contents.
    
    Args:
        file_path: Path to the ZIP file to extract.
        
    Returns:
        List of files extracted from the archive with their paths.
    """
    import zipfile
    
    try:
        extract_dir = Path(file_path).parent / Path(file_path).stem
        extract_dir.mkdir(exist_ok=True)
        
        with zipfile.ZipFile(file_path, 'r') as zip_ref:
            zip_ref.extractall(extract_dir)
        
        results = [f"ZIP Archive extracted to: {extract_dir}\n\nContents:"]
        
        for root, dirs, files in os.walk(extract_dir):
            for file in files:
                full_path = os.path.join(root, file)
                rel_path = os.path.relpath(full_path, extract_dir)
                file_size = os.path.getsize(full_path)
                results.append(f"  - {rel_path} ({file_size} bytes)")
        
        results.append(f"\nUse the appropriate read tool on the extracted files at: {extract_dir}/")
        
        return "\n".join(results)
    except Exception as e:
        return f"[extract_zip] failed: {e}"


# ============================================
# Generic File Processing
# ============================================

@tool
def read_file(file_path: str) -> str:
    """
    Automatically read a file based on its extension.
    
    Supported formats: PDF, DOCX, PPTX, TXT, CSV, XLSX, JSON-LD, PDB, Python, ZIP, JPG, JPEG, PNG, MP3, WAV, FLAC, OGG, M4A
    
    Args:
        file_path: Path to the file to read.
        
    Returns:
        The processed content of the file.
    """
    ext = Path(file_path).suffix.lower()
    
    processors = {
        '.pdf': lambda p: read_pdf.invoke(p),
        '.docx': lambda p: read_docx.invoke(p),
        '.pptx': lambda p: read_pptx.invoke(p),
        '.txt': lambda p: read_text_file.invoke(p),
        '.csv': lambda p: read_csv.invoke(p),
        '.xlsx': lambda p: read_excel.invoke(p),
        '.jsonld': lambda p: read_jsonld.invoke(p),
        '.pdb': lambda p: read_pdb.invoke(p),
        '.py': lambda p: read_python_file.invoke(p),
        '.mp3': lambda p: transcribe_audio.invoke(p),
        '.wav': lambda p: transcribe_audio.invoke(p),
        '.flac': lambda p: transcribe_audio.invoke(p),
        '.ogg': lambda p: transcribe_audio.invoke(p),
        '.m4a': lambda p: transcribe_audio.invoke(p),
        '.zip': lambda p: extract_zip.invoke(p),
        '.jpg': lambda p: analyze_image.invoke({"image_path": p, "question": "Describe this image in detail."}),
        '.jpeg': lambda p: analyze_image.invoke({"image_path": p, "question": "Describe this image in detail."}),
        '.png': lambda p: analyze_image.invoke({"image_path": p, "question": "Describe this image in detail."}),
    }
    
    processor = processors.get(ext)
    
    if processor:
        return processor(file_path)
    
    return f"[Unsupported file type: {ext}]"

# ============================================
# List of all tools
# ============================================

tools_list = [
    calculator,
    duck_web_search,
    wiki_search,
    arxiv_search,
    tavily_web_search,
    fetch_webpage,
    python_eval,
    read_pdf,
    read_docx,
    read_pptx,
    read_text_file,
    read_csv,
    read_excel,
    read_jsonld,
    read_pdb,
    transcribe_audio,
    read_python_file,
    extract_zip,
    analyze_image,
    read_file,
]