Update agent.py
Browse files
agent.py
CHANGED
|
@@ -11,14 +11,13 @@ import cmath
|
|
| 11 |
import pandas as pd
|
| 12 |
import uuid
|
| 13 |
import numpy as np
|
| 14 |
-
|
| 15 |
from PIL import Image
|
| 16 |
import pandasql as psql
|
| 17 |
|
| 18 |
-
# interpreter_instance = CodeInterpreter()
|
| 19 |
|
| 20 |
|
| 21 |
-
|
| 22 |
from langgraph.graph import START, StateGraph, MessagesState
|
| 23 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 24 |
from langchain_community.document_loaders import WikipediaLoader
|
|
@@ -31,18 +30,18 @@ from langchain_huggingface import (
|
|
| 31 |
HuggingFaceEndpoint,
|
| 32 |
HuggingFaceEmbeddings,
|
| 33 |
)
|
| 34 |
-
|
| 35 |
from langchain_core.messages import SystemMessage, HumanMessage
|
| 36 |
from langchain_core.tools import tool
|
| 37 |
from langchain.tools.retriever import create_retriever_tool
|
| 38 |
-
|
| 39 |
from langchain.vectorstores import Chroma
|
| 40 |
import os
|
| 41 |
os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
|
| 42 |
|
| 43 |
load_dotenv()
|
| 44 |
|
| 45 |
-
### ===============
|
| 46 |
|
| 47 |
def _format_documents_as_pseudo_xml(documents, result_tag="Document", truncate_chars=None) -> str:
|
| 48 |
"""
|
|
@@ -129,101 +128,6 @@ def arxiv_search(query: str) -> str:
|
|
| 129 |
except Exception as e:
|
| 130 |
return f"Error during Arxiv search: {str(e)}"
|
| 131 |
|
| 132 |
-
# from typing import Dict, Any
|
| 133 |
-
# import pandas as pd
|
| 134 |
-
# from langchain_core.tools import tool
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
# def _format_stdout(result: Dict[str, Any]) -> str:
|
| 138 |
-
# if stdout := result.get("stdout"):
|
| 139 |
-
# return "\n**Standard Output:**\n```\n" + stdout.strip() + "\n```"
|
| 140 |
-
# return ""
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
# def _format_stderr(result: Dict[str, Any]) -> str:
|
| 144 |
-
# if stderr := result.get("stderr"):
|
| 145 |
-
# return "\n**Standard Error (if any):**\n```\n" + stderr.strip() + "\n```"
|
| 146 |
-
# return ""
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
# def _format_execution_result(result: Dict[str, Any]) -> str:
|
| 150 |
-
# if "result" in result and result["result"] is not None:
|
| 151 |
-
# return "\n**Execution Result:**\n```\n" + str(result["result"]).strip() + "\n```"
|
| 152 |
-
# return ""
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
# def _format_dataframes(result: Dict[str, Any]) -> str:
|
| 156 |
-
# if "dataframes" in result and result["dataframes"]:
|
| 157 |
-
# output = []
|
| 158 |
-
# for df_info in result["dataframes"]:
|
| 159 |
-
# df_preview = pd.DataFrame(df_info["head"])
|
| 160 |
-
# output.append(
|
| 161 |
-
# f"\n**DataFrame `{df_info['name']}` (Shape: {df_info['shape']})**\n"
|
| 162 |
-
# "First 5 rows:\n```\n" + str(df_preview) + "\n```"
|
| 163 |
-
# )
|
| 164 |
-
# return "\n".join(output)
|
| 165 |
-
# return ""
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
# def _format_plots(result: Dict[str, Any]) -> str:
|
| 169 |
-
# if "plots" in result and result["plots"]:
|
| 170 |
-
# return f"\n**Generated {len(result['plots'])} plot(s)** (Image data returned separately)"
|
| 171 |
-
# return ""
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
# @tool
|
| 175 |
-
# def execute_code_multilang(code: str, language: str = "python") -> Dict[str, Any]:
|
| 176 |
-
# """
|
| 177 |
-
# Execute code in multiple languages and return a structured result.
|
| 178 |
-
|
| 179 |
-
# Args:
|
| 180 |
-
# code (str): The source code to execute.
|
| 181 |
-
# language (str): Language of the code. Supported: "python", "bash", "sql", "c", "java".
|
| 182 |
-
|
| 183 |
-
# Returns:
|
| 184 |
-
# Dict[str, Any]: Execution summary with status, language, raw result, and formatted output.
|
| 185 |
-
# """
|
| 186 |
-
# supported_languages = ["python", "bash", "sql", "c", "java"]
|
| 187 |
-
# language = language.lower()
|
| 188 |
-
|
| 189 |
-
# if language not in supported_languages:
|
| 190 |
-
# return {
|
| 191 |
-
# "status": "error",
|
| 192 |
-
# "summary": f"❌ Unsupported language: `{language}`. Supported: {', '.join(supported_languages)}",
|
| 193 |
-
# "language": language
|
| 194 |
-
# }
|
| 195 |
-
|
| 196 |
-
# try:
|
| 197 |
-
# result = interpreter_instance.execute_code(code, language=language)
|
| 198 |
-
# except Exception as e:
|
| 199 |
-
# return {
|
| 200 |
-
# "status": "error",
|
| 201 |
-
# "summary": f"❌ Execution crashed with error: {str(e)}",
|
| 202 |
-
# "language": language
|
| 203 |
-
# }
|
| 204 |
-
|
| 205 |
-
# status = result.get("status", "error")
|
| 206 |
-
# output_parts = []
|
| 207 |
-
|
| 208 |
-
# if status == "success":
|
| 209 |
-
# output_parts.append(f"✅ Code executed successfully in **{language.upper()}**")
|
| 210 |
-
# output_parts.append(_format_stdout(result))
|
| 211 |
-
# output_parts.append(_format_stderr(result))
|
| 212 |
-
# output_parts.append(_format_execution_result(result))
|
| 213 |
-
# output_parts.append(_format_dataframes(result))
|
| 214 |
-
# output_parts.append(_format_plots(result))
|
| 215 |
-
# else:
|
| 216 |
-
# output_parts.append(f"❌ Code execution failed in **{language.upper()}**")
|
| 217 |
-
# output_parts.append(_format_stderr(result))
|
| 218 |
-
|
| 219 |
-
# summary = "\n".join(filter(None, output_parts))
|
| 220 |
-
|
| 221 |
-
# return {
|
| 222 |
-
# "status": status,
|
| 223 |
-
# "language": language,
|
| 224 |
-
# "summary": summary,
|
| 225 |
-
# "raw_result": result,
|
| 226 |
-
# }
|
| 227 |
|
| 228 |
### =============== MATHEMATICAL TOOLS =============== ###
|
| 229 |
|
|
@@ -344,8 +248,6 @@ def validate_file_path(file_path: str) -> None:
|
|
| 344 |
raise ValueError("File is too large to analyze securely.")
|
| 345 |
|
| 346 |
|
| 347 |
-
# ========== Tools ========== #
|
| 348 |
-
|
| 349 |
@tool
|
| 350 |
def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
|
| 351 |
"""
|
|
@@ -525,12 +427,6 @@ tools = [
|
|
| 525 |
extract_text_from_image,
|
| 526 |
analyze_csv_file,
|
| 527 |
analyze_excel_file,
|
| 528 |
-
# execute_code_multilang,
|
| 529 |
-
# analyze_image,
|
| 530 |
-
# transform_image,
|
| 531 |
-
# draw_on_image,
|
| 532 |
-
# generate_simple_image,
|
| 533 |
-
# combine_images,
|
| 534 |
]
|
| 535 |
|
| 536 |
|
|
@@ -593,7 +489,7 @@ def build_graph(provider: str = "groq"):
|
|
| 593 |
|
| 594 |
# test
|
| 595 |
if __name__ == "__main__":
|
| 596 |
-
question = "
|
| 597 |
graph = build_graph(provider="groq")
|
| 598 |
messages = [HumanMessage(content=question)]
|
| 599 |
messages = graph.invoke({"messages": messages})
|
|
|
|
| 11 |
import pandas as pd
|
| 12 |
import uuid
|
| 13 |
import numpy as np
|
| 14 |
+
|
| 15 |
from PIL import Image
|
| 16 |
import pandasql as psql
|
| 17 |
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
+
### Langraph ###
|
| 21 |
from langgraph.graph import START, StateGraph, MessagesState
|
| 22 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 23 |
from langchain_community.document_loaders import WikipediaLoader
|
|
|
|
| 30 |
HuggingFaceEndpoint,
|
| 31 |
HuggingFaceEmbeddings,
|
| 32 |
)
|
| 33 |
+
|
| 34 |
from langchain_core.messages import SystemMessage, HumanMessage
|
| 35 |
from langchain_core.tools import tool
|
| 36 |
from langchain.tools.retriever import create_retriever_tool
|
| 37 |
+
|
| 38 |
from langchain.vectorstores import Chroma
|
| 39 |
import os
|
| 40 |
os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
|
| 41 |
|
| 42 |
load_dotenv()
|
| 43 |
|
| 44 |
+
### =============== SERACH TOOLS =============== ###
|
| 45 |
|
| 46 |
def _format_documents_as_pseudo_xml(documents, result_tag="Document", truncate_chars=None) -> str:
|
| 47 |
"""
|
|
|
|
| 128 |
except Exception as e:
|
| 129 |
return f"Error during Arxiv search: {str(e)}"
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
### =============== MATHEMATICAL TOOLS =============== ###
|
| 133 |
|
|
|
|
| 248 |
raise ValueError("File is too large to analyze securely.")
|
| 249 |
|
| 250 |
|
|
|
|
|
|
|
| 251 |
@tool
|
| 252 |
def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
|
| 253 |
"""
|
|
|
|
| 427 |
extract_text_from_image,
|
| 428 |
analyze_csv_file,
|
| 429 |
analyze_excel_file,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
]
|
| 431 |
|
| 432 |
|
|
|
|
| 489 |
|
| 490 |
# test
|
| 491 |
if __name__ == "__main__":
|
| 492 |
+
question = "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia."
|
| 493 |
graph = build_graph(provider="groq")
|
| 494 |
messages = [HumanMessage(content=question)]
|
| 495 |
messages = graph.invoke({"messages": messages})
|