Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -492,19 +492,29 @@
|
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
|
| 509 |
|
| 510 |
|
|
@@ -629,10 +639,158 @@ Your answer should only start with "FINAL ANSWER: ", then follows with the answe
|
|
| 629 |
|
| 630 |
|
| 631 |
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 636 |
|
| 637 |
|
| 638 |
|
|
|
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
+
import os
|
| 496 |
+
import json
|
| 497 |
+
import torch
|
| 498 |
+
import base64
|
| 499 |
+
import requests
|
| 500 |
+
import mimetypes
|
| 501 |
+
from PIL import Image
|
| 502 |
+
from tavily import TavilyClient
|
| 503 |
+
from langchain_core.tools import tool
|
| 504 |
+
from langchain_openai import ChatOpenAI
|
| 505 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 506 |
+
from langchain_core.rate_limiters import InMemoryRateLimiter
|
| 507 |
+
from dataclasses import dataclass, field
|
| 508 |
+
from langchain_experimental.utilities import PythonREPL
|
| 509 |
+
from langgraph.prebuilt import ToolNode, tools_condition
|
| 510 |
+
from langgraph.graph.message import add_messages
|
| 511 |
+
from langchain_community.document_loaders import ArxivLoader
|
| 512 |
+
from langchain_core.messages import SystemMessage, HumanMessage, AnyMessage, AIMessage, ToolMessage
|
| 513 |
+
from langchain_community.document_loaders import WikipediaLoader
|
| 514 |
+
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 515 |
+
from langgraph.graph import StateGraph, START, END, MessagesState
|
| 516 |
+
from typing import TypedDict, List, Dict, Any, Optional, Annotated
|
| 517 |
+
from transformers import Blip2Processor, Blip2ForConditionalGeneration
|
| 518 |
|
| 519 |
|
| 520 |
|
|
|
|
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
+
# === TOOL STUBS ===
|
| 643 |
+
@tool
|
| 644 |
+
def python_repl_tool(query: str) -> str:
|
| 645 |
+
"""
|
| 646 |
+
Execute Python query like calculations; return printed output.
|
| 647 |
+
|
| 648 |
+
Args:
|
| 649 |
+
query: The calculation formula.
|
| 650 |
+
|
| 651 |
+
Returns:
|
| 652 |
+
The result of the query exacuation
|
| 653 |
+
"""
|
| 654 |
+
python_repl = PythonREPL()
|
| 655 |
+
return python_repl.run(query)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
@tool
|
| 659 |
+
def web_search(query: str) -> str:
|
| 660 |
+
"""Search Tavily for a query and return maximum 3 results.
|
| 661 |
+
Args:
|
| 662 |
+
query: The search query.
|
| 663 |
+
Returns:
|
| 664 |
+
A concise details about the query from internet."""
|
| 665 |
+
response = TavilySearchResults().invoke({"query": query, "max_results": 3})
|
| 666 |
+
content = []
|
| 667 |
+
for doc in response:
|
| 668 |
+
content.append(f'<Document source="{doc["url"]}" confidence score="{doc["score"]}"/>\n{doc["content"]}\n</Document>')
|
| 669 |
+
return {"web_results": content}
|
| 670 |
+
|
| 671 |
+
@tool
|
| 672 |
+
def vision_caption(image_path: str) -> str:
|
| 673 |
+
"""
|
| 674 |
+
Extract text from an image using OCR library pytesseract (if available).
|
| 675 |
+
Args:
|
| 676 |
+
image_path (str): the path to the image file.
|
| 677 |
+
Returns:
|
| 678 |
+
A concise, human‑readable caption describing the image content.
|
| 679 |
+
"""
|
| 680 |
+
try:
|
| 681 |
+
# Open the image
|
| 682 |
+
image = Image.open(image_path)
|
| 683 |
+
|
| 684 |
+
# Extract text from the image
|
| 685 |
+
text = pytesseract.image_to_string(image)
|
| 686 |
+
|
| 687 |
+
return f"Extracted text from image:\n\n{text}"
|
| 688 |
+
except Exception as e:
|
| 689 |
+
return f"Error extracting text from image: {str(e)}"
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
@tool
|
| 693 |
+
def wiki_search(query: str) -> str:
|
| 694 |
+
"""Search Wikipedia for a query and return maximum 2 results.
|
| 695 |
+
|
| 696 |
+
Args:
|
| 697 |
+
query: The search query.
|
| 698 |
+
Returns:
|
| 699 |
+
Search results about the query from the Wikipedia website
|
| 700 |
+
"""
|
| 701 |
+
docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
| 702 |
+
return "\n\n---\n\n".join(f'{doc.page_content}' for doc in docs)
|
| 703 |
+
|
| 704 |
+
@tool
|
| 705 |
+
def arvix_search(query: str) -> str:
|
| 706 |
+
"""Search Arxiv for a query and return maximum 3 result.
|
| 707 |
+
|
| 708 |
+
Args:
|
| 709 |
+
query: The search query.
|
| 710 |
+
Returns:
|
| 711 |
+
Search results about the query from the Arxiv website
|
| 712 |
+
"""
|
| 713 |
+
docs = ArxivLoader(query=query, load_max_docs=2).load()
|
| 714 |
+
return "\n\n---\n\n".join(f'{doc.page_content}' for doc in docs)
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
@tool
|
| 718 |
+
def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
|
| 719 |
+
"""
|
| 720 |
+
Download a file from a URL and save it to a temporary location.
|
| 721 |
+
Args:
|
| 722 |
+
url (str): the URL of the file to download.
|
| 723 |
+
filename (str, optional): the name of the file. If not provided, a random name file will be created.
|
| 724 |
+
Returns:
|
| 725 |
+
Nothing
|
| 726 |
+
"""
|
| 727 |
+
try:
|
| 728 |
+
# Parse URL to get filename if not provided
|
| 729 |
+
if not filename:
|
| 730 |
+
path = urlparse(url).path
|
| 731 |
+
filename = os.path.basename(path)
|
| 732 |
+
if not filename:
|
| 733 |
+
filename = f"downloaded_{uuid.uuid4().hex[:8]}"
|
| 734 |
+
|
| 735 |
+
# Create temporary file
|
| 736 |
+
temp_dir = tempfile.gettempdir()
|
| 737 |
+
filepath = os.path.join(temp_dir, filename)
|
| 738 |
+
|
| 739 |
+
# Download the file
|
| 740 |
+
response = requests.get(url, stream=True)
|
| 741 |
+
response.raise_for_status()
|
| 742 |
+
|
| 743 |
+
# Save the file
|
| 744 |
+
with open(filepath, "wb") as f:
|
| 745 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 746 |
+
f.write(chunk)
|
| 747 |
+
|
| 748 |
+
return f"File downloaded to {filepath}. You can read this file to process its contents."
|
| 749 |
+
except Exception as e:
|
| 750 |
+
return f"Error downloading file: {str(e)}"
|
| 751 |
+
|
| 752 |
+
@tool
|
| 753 |
+
def file_reader(file_path: str) -> str:
|
| 754 |
+
"""
|
| 755 |
+
Analyze a text file using pandas and answer a question about it.
|
| 756 |
+
The file can be any of excel, csv, tsv, xls, json, txt or log.
|
| 757 |
+
Args:
|
| 758 |
+
file_path (str): the path to the CSV file.
|
| 759 |
+
Returns:
|
| 760 |
+
The conetent inside the PDF/Text file
|
| 761 |
+
"""
|
| 762 |
+
try:
|
| 763 |
+
_, ext = os.path.splitext(file_path.lower())
|
| 764 |
+
if ext in {".csv", ".tsv"}:
|
| 765 |
+
sep = "\t" if ext == ".tsv" else ","
|
| 766 |
+
data = pd.read_csv(file_path, sep=sep)
|
| 767 |
+
if ext in {".xls", ".xlsx"}:
|
| 768 |
+
data = pd.read_excel(file_path)
|
| 769 |
+
if ext == ".json":
|
| 770 |
+
data = pd.read_json(file_path)
|
| 771 |
+
if ext in {".txt", ".log"}:
|
| 772 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 773 |
+
data = f.read()
|
| 774 |
+
|
| 775 |
+
# Run various analyses based on the query
|
| 776 |
+
result = f"text file loaded with {len(data)} rows and {len(data.columns)} columns.\n"
|
| 777 |
+
result += f"Columns: {', '.join(data.columns)}\n\n"+\
|
| 778 |
+
"Summary statistics:\n" + str(data.describe())
|
| 779 |
+
# Add summary statistics
|
| 780 |
+
return result
|
| 781 |
+
|
| 782 |
+
except Exception as e:
|
| 783 |
+
return f"Error analyzing text file: {str(e)}"
|
| 784 |
+
|
| 785 |
+
tools = [
|
| 786 |
+
python_repl_tool,
|
| 787 |
+
web_search,
|
| 788 |
+
vision_caption,
|
| 789 |
+
arvix_search,
|
| 790 |
+
wiki_search,
|
| 791 |
+
download_file_from_url,
|
| 792 |
+
file_reader,
|
| 793 |
+
]
|
| 794 |
|
| 795 |
|
| 796 |
|