Jugal Sheth commited on
Commit Β·
6c513b1
1
Parent(s): 49931ed
- README.md +9 -6
- agentTest.py +16 -0
- agents/__init__.py +0 -0
- agents/__pycache__/__init__.cpython-310.pyc +0 -0
- agents/__pycache__/__init__.cpython-312.pyc +0 -0
- agents/__pycache__/agent.cpython-310.pyc +0 -0
- agents/__pycache__/agent.cpython-312.pyc +0 -0
- agents/agent.py +91 -0
- app.py +89 -5
- app1.py +207 -0
- data/metadata.jsonl +0 -0
- requirements.txt +20 -0
- system_prompt.txt +62 -0
- test.ipynb +0 -0
- tools/__init__.py +0 -0
- tools/__pycache__/__init__.cpython-310.pyc +0 -0
- tools/__pycache__/__init__.cpython-312.pyc +0 -0
- tools/__pycache__/codetools.cpython-310.pyc +0 -0
- tools/__pycache__/codetools.cpython-312.pyc +0 -0
- tools/__pycache__/documenttools.cpython-310.pyc +0 -0
- tools/__pycache__/documenttools.cpython-312.pyc +0 -0
- tools/__pycache__/imagetools.cpython-310.pyc +0 -0
- tools/__pycache__/imagetools.cpython-312.pyc +0 -0
- tools/__pycache__/mathtools.cpython-310.pyc +0 -0
- tools/__pycache__/mathtools.cpython-312.pyc +0 -0
- tools/__pycache__/searchtools.cpython-310.pyc +0 -0
- tools/__pycache__/searchtools.cpython-312.pyc +0 -0
- tools/codetools.py +348 -0
- tools/documenttools.py +137 -0
- tools/imagetools.py +311 -0
- tools/mathtools.py +81 -0
- tools/searchtools.py +88 -0
- x.py +7 -0
README.md
CHANGED
|
@@ -1,12 +1,15 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 5.
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
|
|
|
|
|
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Template Final Assignment
|
| 3 |
+
emoji: π΅π»ββοΈ
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: indigo
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.25.2
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
hf_oauth: true
|
| 11 |
+
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
|
| 12 |
+
hf_oauth_expiration_minutes: 480
|
| 13 |
---
|
| 14 |
|
| 15 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
agentTest.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from langchain_core.messages import HumanMessage
|
| 3 |
+
from agents.agent import build_graph
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# test
|
| 7 |
+
if __name__ == "__main__":
|
| 8 |
+
|
| 9 |
+
question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
|
| 10 |
+
# Build the graph
|
| 11 |
+
graph = build_graph()
|
| 12 |
+
# Run the graph
|
| 13 |
+
messages = [HumanMessage(content=question)]
|
| 14 |
+
messages = graph.invoke({"messages": messages})
|
| 15 |
+
for m in messages["messages"]:
|
| 16 |
+
m.pretty_print()
|
agents/__init__.py
ADDED
|
File without changes
|
agents/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (156 Bytes). View file
|
|
|
agents/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (170 Bytes). View file
|
|
|
agents/__pycache__/agent.cpython-310.pyc
ADDED
|
Binary file (2.6 kB). View file
|
|
|
agents/__pycache__/agent.cpython-312.pyc
ADDED
|
Binary file (3.63 kB). View file
|
|
|
agents/agent.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dotenv import load_dotenv
|
| 2 |
+
|
| 3 |
+
load_dotenv()
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from langgraph.graph import START, StateGraph, MessagesState
|
| 7 |
+
from langgraph.prebuilt import tools_condition
|
| 8 |
+
from langgraph.prebuilt import ToolNode
|
| 9 |
+
from langchain_core.messages import SystemMessage, HumanMessage
|
| 10 |
+
from tools.searchtools import wiki_search, web_search, arxiv_search, vector_store
|
| 11 |
+
from tools.mathtools import multiply, add, subtract, divide, modulus,power,square_root
|
| 12 |
+
from tools.codetools import execute_code_multilang
|
| 13 |
+
from tools.documenttools import save_and_read_file,download_file_from_url, extract_text_from_image, analyze_csv_file, analyze_excel_file
|
| 14 |
+
from tools.imagetools import analyze_image, transform_image, draw_on_image, generate_simple_image, combine_images
|
| 15 |
+
from langchain_groq import ChatGroq
|
| 16 |
+
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
|
| 17 |
+
|
| 18 |
+
# load the system prompt from the file
|
| 19 |
+
with open("system_prompt.txt", "r", encoding="utf-8") as f:
|
| 20 |
+
system_prompt = f.read()
|
| 21 |
+
|
| 22 |
+
# System message
|
| 23 |
+
sys_msg = SystemMessage(content=system_prompt)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
tools = [
|
| 27 |
+
web_search,
|
| 28 |
+
wiki_search,
|
| 29 |
+
arxiv_search,
|
| 30 |
+
multiply,
|
| 31 |
+
add,
|
| 32 |
+
subtract,
|
| 33 |
+
divide,
|
| 34 |
+
modulus,
|
| 35 |
+
power,
|
| 36 |
+
square_root,
|
| 37 |
+
save_and_read_file,
|
| 38 |
+
download_file_from_url,
|
| 39 |
+
extract_text_from_image,
|
| 40 |
+
analyze_csv_file,
|
| 41 |
+
analyze_excel_file,
|
| 42 |
+
execute_code_multilang,
|
| 43 |
+
analyze_image,
|
| 44 |
+
transform_image,
|
| 45 |
+
draw_on_image,
|
| 46 |
+
generate_simple_image,
|
| 47 |
+
combine_images,
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# Build graph function
|
| 52 |
+
def build_graph():
|
| 53 |
+
"""Build the graph"""
|
| 54 |
+
# Load environment variables from .env file
|
| 55 |
+
llm = ChatGroq(model="qwen-qwq-32b", temperature=0)
|
| 56 |
+
|
| 57 |
+
# Bind tools to LLM
|
| 58 |
+
llm_with_tools = llm.bind_tools(tools)
|
| 59 |
+
|
| 60 |
+
# Node
|
| 61 |
+
def assistant(state: MessagesState):
|
| 62 |
+
"""Assistant node"""
|
| 63 |
+
return {"messages": [llm_with_tools.invoke(state["messages"])]}
|
| 64 |
+
|
| 65 |
+
def retriever(state: MessagesState):
|
| 66 |
+
"""Retriever node"""
|
| 67 |
+
similar_question = vector_store.similarity_search(state["messages"][0].content)
|
| 68 |
+
|
| 69 |
+
if similar_question: # Check if the list is not empty
|
| 70 |
+
example_msg = HumanMessage(
|
| 71 |
+
content=f"Here I provide a similar question and answer for reference: \n\n{similar_question[0].page_content}",
|
| 72 |
+
)
|
| 73 |
+
return {"messages": [sys_msg] + state["messages"] + [example_msg]}
|
| 74 |
+
else:
|
| 75 |
+
# Handle the case when no similar questions are found
|
| 76 |
+
return {"messages": [sys_msg] + state["messages"]}
|
| 77 |
+
|
| 78 |
+
builder = StateGraph(MessagesState)
|
| 79 |
+
builder.add_node("retriever", retriever)
|
| 80 |
+
builder.add_node("assistant", assistant)
|
| 81 |
+
builder.add_node("tools", ToolNode(tools))
|
| 82 |
+
builder.add_edge(START, "retriever")
|
| 83 |
+
builder.add_edge("retriever", "assistant")
|
| 84 |
+
builder.add_conditional_edges(
|
| 85 |
+
"assistant",
|
| 86 |
+
tools_condition,
|
| 87 |
+
)
|
| 88 |
+
builder.add_edge("tools", "assistant")
|
| 89 |
+
|
| 90 |
+
# Compile graph
|
| 91 |
+
return builder.compile()
|
app.py
CHANGED
|
@@ -1,7 +1,91 @@
|
|
| 1 |
-
import
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
from smolagents import ToolCallingAgent, TransformersModel, Tool, DuckDuckGoSearchTool
|
| 3 |
|
| 4 |
+
# ----------------------------
|
| 5 |
+
# MODEL CONFIGURATION
|
| 6 |
+
# ----------------------------
|
| 7 |
+
model = TransformersModel(
|
| 8 |
+
model_id="meta-llama/Llama-3.2-3B-Instruct"
|
| 9 |
+
)
|
| 10 |
|
| 11 |
+
# ----------------------------
|
| 12 |
+
# CUSTOM WEB SEARCH TOOL
|
| 13 |
+
# ----------------------------
|
| 14 |
+
class WebSearchTool(Tool):
|
| 15 |
+
def __init__(self):
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.name = "web_search"
|
| 18 |
+
self.description = "Search the web using DuckDuckGo"
|
| 19 |
+
self._ddg = DuckDuckGoSearchTool(max_results=5, rate_limit=2.0)
|
| 20 |
+
|
| 21 |
+
def __call__(self, query: str):
|
| 22 |
+
return self._ddg(query=query)
|
| 23 |
+
|
| 24 |
+
# ----------------------------
|
| 25 |
+
# AGENT
|
| 26 |
+
# ----------------------------
|
| 27 |
+
agent = ToolCallingAgent(
|
| 28 |
+
model=model,
|
| 29 |
+
tools=[WebSearchTool()],
|
| 30 |
+
max_steps=8
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# ----------------------------
|
| 34 |
+
# GAIA API ENDPOINTS
|
| 35 |
+
# ----------------------------
|
| 36 |
+
BASE_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 37 |
+
|
| 38 |
+
def get_questions():
|
| 39 |
+
r = requests.get(f"{BASE_URL}/questions")
|
| 40 |
+
r.raise_for_status()
|
| 41 |
+
return r.json()
|
| 42 |
+
|
| 43 |
+
def get_random_question():
|
| 44 |
+
r = requests.get(f"{BASE_URL}/random-question")
|
| 45 |
+
r.raise_for_status()
|
| 46 |
+
return r.json()
|
| 47 |
+
|
| 48 |
+
def submit_answers(username, agent_code, answers):
|
| 49 |
+
payload = {"username": username, "agent_code": agent_code, "answers": answers}
|
| 50 |
+
r = requests.post(f"{BASE_URL}/submit", json=payload)
|
| 51 |
+
r.raise_for_status()
|
| 52 |
+
return r.json()
|
| 53 |
+
|
| 54 |
+
# ----------------------------
|
| 55 |
+
# ANSWER GENERATION
|
| 56 |
+
# ----------------------------
|
| 57 |
+
def generate_answer(question):
|
| 58 |
+
prompt = f"""
|
| 59 |
+
Answer this question accurately and concisely.
|
| 60 |
+
Do not include reasoning or explanations.
|
| 61 |
+
Question: {question}
|
| 62 |
+
"""
|
| 63 |
+
try:
|
| 64 |
+
return agent.run(prompt).strip()
|
| 65 |
+
except Exception as e:
|
| 66 |
+
return f"Error: {e}"
|
| 67 |
+
|
| 68 |
+
# ----------------------------
|
| 69 |
+
# MAIN SCRIPT
|
| 70 |
+
# ----------------------------
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
# Replace with your Hugging Face username and Space URL
|
| 73 |
+
username = "<YOUR_HF_USERNAME>"
|
| 74 |
+
agent_code = "https://huggingface.co/spaces/<YOUR_HF_USERNAME>/smolagents-final/tree/main"
|
| 75 |
+
|
| 76 |
+
# Retrieve all GAIA questions
|
| 77 |
+
questions = get_questions()
|
| 78 |
+
print(f"Retrieved {len(questions)} GAIA questions.\n")
|
| 79 |
+
|
| 80 |
+
# Generate answers
|
| 81 |
+
answers = []
|
| 82 |
+
for q in questions:
|
| 83 |
+
print(f"[{q['task_id']}] {q['question']}")
|
| 84 |
+
ans = generate_answer(q["question"])
|
| 85 |
+
print(f" β {ans}")
|
| 86 |
+
answers.append({"task_id": q["task_id"], "submitted_answer": ans})
|
| 87 |
+
|
| 88 |
+
# Submit answers
|
| 89 |
+
print("\nSubmitting answers...")
|
| 90 |
+
result = submit_answers(username, agent_code, answers)
|
| 91 |
+
print(result)
|
app1.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Basic Agent Evaluation Runner"""
|
| 2 |
+
import os
|
| 3 |
+
import inspect
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import requests
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from langchain_core.messages import HumanMessage
|
| 8 |
+
from agents.agent import build_graph
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# (Keep Constants as is)
|
| 13 |
+
# --- Constants ---
|
| 14 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 15 |
+
|
| 16 |
+
# --- Basic Agent Definition ---
|
| 17 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class BasicAgent:
|
| 21 |
+
"""A langgraph agent."""
|
| 22 |
+
def __init__(self):
|
| 23 |
+
print("BasicAgent initialized.")
|
| 24 |
+
self.graph = build_graph()
|
| 25 |
+
|
| 26 |
+
def __call__(self, question: str) -> str:
|
| 27 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 28 |
+
# Wrap the question in a HumanMessage from langchain_core
|
| 29 |
+
messages = [HumanMessage(content=question)]
|
| 30 |
+
messages = self.graph.invoke({"messages": messages})
|
| 31 |
+
answer = messages['messages'][-1].content
|
| 32 |
+
return answer[14:]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 36 |
+
"""
|
| 37 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 38 |
+
and displays the results.
|
| 39 |
+
"""
|
| 40 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 41 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 42 |
+
|
| 43 |
+
if profile:
|
| 44 |
+
username= f"{profile.username}"
|
| 45 |
+
print(f"User logged in: {username}")
|
| 46 |
+
else:
|
| 47 |
+
print("User not logged in.")
|
| 48 |
+
return "Please Login to Hugging Face with the button.", None
|
| 49 |
+
|
| 50 |
+
api_url = DEFAULT_API_URL
|
| 51 |
+
questions_url = f"{api_url}/questions"
|
| 52 |
+
submit_url = f"{api_url}/submit"
|
| 53 |
+
|
| 54 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 55 |
+
try:
|
| 56 |
+
agent = BasicAgent()
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"Error instantiating agent: {e}")
|
| 59 |
+
return f"Error initializing agent: {e}", None
|
| 60 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
| 61 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 62 |
+
print(agent_code)
|
| 63 |
+
|
| 64 |
+
# 2. Fetch Questions
|
| 65 |
+
print(f"Fetching questions from: {questions_url}")
|
| 66 |
+
try:
|
| 67 |
+
response = requests.get(questions_url, timeout=15)
|
| 68 |
+
response.raise_for_status()
|
| 69 |
+
questions_data = response.json()
|
| 70 |
+
if not questions_data:
|
| 71 |
+
print("Fetched questions list is empty.")
|
| 72 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 73 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 74 |
+
except requests.exceptions.RequestException as e:
|
| 75 |
+
print(f"Error fetching questions: {e}")
|
| 76 |
+
return f"Error fetching questions: {e}", None
|
| 77 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 78 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 79 |
+
print(f"Response text: {response.text[:500]}")
|
| 80 |
+
return f"Error decoding server response for questions: {e}", None
|
| 81 |
+
except Exception as e:
|
| 82 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 83 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 84 |
+
|
| 85 |
+
# 3. Run your Agent
|
| 86 |
+
results_log = []
|
| 87 |
+
answers_payload = []
|
| 88 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 89 |
+
for item in questions_data:
|
| 90 |
+
task_id = item.get("task_id")
|
| 91 |
+
question_text = item.get("question")
|
| 92 |
+
if not task_id or question_text is None:
|
| 93 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 94 |
+
continue
|
| 95 |
+
try:
|
| 96 |
+
submitted_answer = agent(question_text)
|
| 97 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 98 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 101 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 102 |
+
|
| 103 |
+
if not answers_payload:
|
| 104 |
+
print("Agent did not produce any answers to submit.")
|
| 105 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 106 |
+
|
| 107 |
+
# 4. Prepare Submission
|
| 108 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 109 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 110 |
+
print(status_update)
|
| 111 |
+
|
| 112 |
+
# 5. Submit
|
| 113 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 114 |
+
try:
|
| 115 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 116 |
+
response.raise_for_status()
|
| 117 |
+
result_data = response.json()
|
| 118 |
+
final_status = (
|
| 119 |
+
f"Submission Successful!\n"
|
| 120 |
+
f"User: {result_data.get('username')}\n"
|
| 121 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 122 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 123 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 124 |
+
)
|
| 125 |
+
print("Submission successful.")
|
| 126 |
+
results_df = pd.DataFrame(results_log)
|
| 127 |
+
return final_status, results_df
|
| 128 |
+
except requests.exceptions.HTTPError as e:
|
| 129 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 130 |
+
try:
|
| 131 |
+
error_json = e.response.json()
|
| 132 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 133 |
+
except requests.exceptions.JSONDecodeError:
|
| 134 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 135 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 136 |
+
print(status_message)
|
| 137 |
+
results_df = pd.DataFrame(results_log)
|
| 138 |
+
return status_message, results_df
|
| 139 |
+
except requests.exceptions.Timeout:
|
| 140 |
+
status_message = "Submission Failed: The request timed out."
|
| 141 |
+
print(status_message)
|
| 142 |
+
results_df = pd.DataFrame(results_log)
|
| 143 |
+
return status_message, results_df
|
| 144 |
+
except requests.exceptions.RequestException as e:
|
| 145 |
+
status_message = f"Submission Failed: Network error - {e}"
|
| 146 |
+
print(status_message)
|
| 147 |
+
results_df = pd.DataFrame(results_log)
|
| 148 |
+
return status_message, results_df
|
| 149 |
+
except Exception as e:
|
| 150 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 151 |
+
print(status_message)
|
| 152 |
+
results_df = pd.DataFrame(results_log)
|
| 153 |
+
return status_message, results_df
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# --- Build Gradio Interface using Blocks ---
|
| 157 |
+
with gr.Blocks() as demo:
|
| 158 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 159 |
+
gr.Markdown(
|
| 160 |
+
"""
|
| 161 |
+
**Instructions:**
|
| 162 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 163 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 164 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 165 |
+
---
|
| 166 |
+
**Disclaimers:**
|
| 167 |
+
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
| 168 |
+
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
| 169 |
+
"""
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
gr.LoginButton()
|
| 173 |
+
|
| 174 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 175 |
+
|
| 176 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 177 |
+
# Removed max_rows=10 from DataFrame constructor
|
| 178 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 179 |
+
|
| 180 |
+
run_button.click(
|
| 181 |
+
fn=run_and_submit_all,
|
| 182 |
+
outputs=[status_output, results_table]
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 187 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 188 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
| 189 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 190 |
+
|
| 191 |
+
if space_host_startup:
|
| 192 |
+
print(f"β
SPACE_HOST found: {space_host_startup}")
|
| 193 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 194 |
+
else:
|
| 195 |
+
print("βΉοΈ SPACE_HOST environment variable not found (running locally?).")
|
| 196 |
+
|
| 197 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 198 |
+
print(f"β
SPACE_ID found: {space_id_startup}")
|
| 199 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 200 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 201 |
+
else:
|
| 202 |
+
print("βΉοΈ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 203 |
+
|
| 204 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 205 |
+
|
| 206 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 207 |
+
demo.launch(debug=True, share=False)
|
data/metadata.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
requests
|
| 3 |
+
langchain
|
| 4 |
+
langchain-community
|
| 5 |
+
langchain-core
|
| 6 |
+
langchain-google-genai
|
| 7 |
+
langchain-huggingface
|
| 8 |
+
langchain-groq
|
| 9 |
+
langchain-tavily
|
| 10 |
+
langchain-chroma
|
| 11 |
+
langgraph
|
| 12 |
+
huggingface_hub
|
| 13 |
+
supabase
|
| 14 |
+
arxiv
|
| 15 |
+
pymupdf
|
| 16 |
+
wikipedia
|
| 17 |
+
pgvector
|
| 18 |
+
python-dotenv
|
| 19 |
+
pytesseract
|
| 20 |
+
matplotlib
|
system_prompt.txt
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
You are a helpful assistant tasked with answering questions using a set of tools.
|
| 3 |
+
If the tool is not available, you can try to find the information online. You can also use your own knowledge to answer the question.
|
| 4 |
+
You need to provide a step-by-step explanation of how you arrived at the answer.
|
| 5 |
+
==========================
|
| 6 |
+
Here is a few examples showing you how to answer the question step by step.
|
| 7 |
+
|
| 8 |
+
Question 1: In terms of geographical distance between capital cities, which 2 countries are the furthest from each other within the ASEAN bloc according to wikipedia? Answer using a comma separated list, ordering the countries by alphabetical order.
|
| 9 |
+
Steps:
|
| 10 |
+
1. Search the web for "ASEAN bloc".
|
| 11 |
+
2. Click the Wikipedia result for the ASEAN Free Trade Area.
|
| 12 |
+
3. Scroll down to find the list of member states.
|
| 13 |
+
4. Click into the Wikipedia pages for each member state, and note its capital.
|
| 14 |
+
5. Search the web for the distance between the first two capitals. The results give travel distance, not geographic distance, which might affect the answer.
|
| 15 |
+
6. Thinking it might be faster to judge the distance by looking at a map, search the web for "ASEAN bloc" and click into the images tab.
|
| 16 |
+
7. View a map of the member countries. Since they're clustered together in an arrangement that's not very linear, it's difficult to judge distances by eye.
|
| 17 |
+
8. Return to the Wikipedia page for each country. Click the GPS coordinates for each capital to get the coordinates in decimal notation.
|
| 18 |
+
9. Place all these coordinates into a spreadsheet.
|
| 19 |
+
10. Write formulas to calculate the distance between each capital.
|
| 20 |
+
11. Write formula to get the largest distance value in the spreadsheet.
|
| 21 |
+
12. Note which two capitals that value corresponds to: Jakarta and Naypyidaw.
|
| 22 |
+
13. Return to the Wikipedia pages to see which countries those respective capitals belong to: Indonesia, Myanmar.
|
| 23 |
+
Tools:
|
| 24 |
+
1. Search engine
|
| 25 |
+
2. Web browser
|
| 26 |
+
3. Microsoft Excel / Google Sheets
|
| 27 |
+
Final Answer: Indonesia, Myanmar
|
| 28 |
+
|
| 29 |
+
Question 2: Using bass clef notes, what is the age of someone who has experienced the word spelled out in the sheet music by the note letters the total number of lines and notes minus the number of notes on lines in the image?
|
| 30 |
+
Steps:
|
| 31 |
+
1. Open the file.
|
| 32 |
+
2. Translate the letters to bass notes ("D E C A D E").
|
| 33 |
+
3. Count the lines (5).
|
| 34 |
+
4. Count the notes (6).
|
| 35 |
+
5. Count the notes on lines (2).
|
| 36 |
+
6. Add the lines and notes (11).
|
| 37 |
+
7. Subtract the notes on lines (11 - 2).
|
| 38 |
+
8. Multiply 10 by 9 (90).
|
| 39 |
+
9. Note the age given.
|
| 40 |
+
Tools:
|
| 41 |
+
1. Image recognition
|
| 42 |
+
2. Bass note data
|
| 43 |
+
3. Calculator
|
| 44 |
+
Final Answer: 90
|
| 45 |
+
|
| 46 |
+
Question 3: In the year 2022, and before December, what does "R" stand for in the three core policies of the type of content that was violated in the public logs on the Legume Wikipedia page?
|
| 47 |
+
Steps:
|
| 48 |
+
1. Searched "legume wikipedia" on Google.
|
| 49 |
+
2. Opened "Legume" on Wikipedia.
|
| 50 |
+
3. Clicked "View history".
|
| 51 |
+
4. Clicked "View logs for this page".
|
| 52 |
+
5. Checked all types of logs.
|
| 53 |
+
6. Set the date to November 2022.
|
| 54 |
+
7. Followed the BLP link of the violation.
|
| 55 |
+
8. Noted the meaning of "R".
|
| 56 |
+
Tools:
|
| 57 |
+
1. Web browser
|
| 58 |
+
2. Search engine
|
| 59 |
+
Final Answer: research
|
| 60 |
+
|
| 61 |
+
==========================
|
| 62 |
+
Now, please answer the following question step by step.
|
test.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tools/__init__.py
ADDED
|
File without changes
|
tools/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (155 Bytes). View file
|
|
|
tools/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (169 Bytes). View file
|
|
|
tools/__pycache__/codetools.cpython-310.pyc
ADDED
|
Binary file (8.04 kB). View file
|
|
|
tools/__pycache__/codetools.cpython-312.pyc
ADDED
|
Binary file (14.4 kB). View file
|
|
|
tools/__pycache__/documenttools.cpython-310.pyc
ADDED
|
Binary file (3.81 kB). View file
|
|
|
tools/__pycache__/documenttools.cpython-312.pyc
ADDED
|
Binary file (6.01 kB). View file
|
|
|
tools/__pycache__/imagetools.cpython-310.pyc
ADDED
|
Binary file (8.58 kB). View file
|
|
|
tools/__pycache__/imagetools.cpython-312.pyc
ADDED
|
Binary file (14.5 kB). View file
|
|
|
tools/__pycache__/mathtools.cpython-310.pyc
ADDED
|
Binary file (2.05 kB). View file
|
|
|
tools/__pycache__/mathtools.cpython-312.pyc
ADDED
|
Binary file (2.49 kB). View file
|
|
|
tools/__pycache__/searchtools.cpython-310.pyc
ADDED
|
Binary file (3.32 kB). View file
|
|
|
tools/__pycache__/searchtools.cpython-312.pyc
ADDED
|
Binary file (4.78 kB). View file
|
|
|
tools/codetools.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.tools import tool
|
| 2 |
+
import os
|
| 3 |
+
import io
|
| 4 |
+
import sys
|
| 5 |
+
import uuid
|
| 6 |
+
import base64
|
| 7 |
+
import traceback
|
| 8 |
+
import contextlib
|
| 9 |
+
import tempfile
|
| 10 |
+
import subprocess
|
| 11 |
+
import sqlite3
|
| 12 |
+
from typing import Dict, List, Any, Optional, Union
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import matplotlib.pyplot as plt
|
| 16 |
+
from PIL import Image
|
| 17 |
+
|
| 18 |
+
class CodeInterpreter:
|
| 19 |
+
def __init__(self, allowed_modules=None, max_execution_time=30, working_directory=None):
|
| 20 |
+
"""Initialize the code interpreter with safety measures."""
|
| 21 |
+
self.allowed_modules = allowed_modules or [
|
| 22 |
+
"numpy", "pandas", "matplotlib", "scipy", "sklearn",
|
| 23 |
+
"math", "random", "statistics", "datetime", "collections",
|
| 24 |
+
"itertools", "functools", "operator", "re", "json",
|
| 25 |
+
"sympy", "networkx", "nltk", "PIL", "pytesseract",
|
| 26 |
+
"cmath", "uuid", "tempfile", "requests", "urllib"
|
| 27 |
+
]
|
| 28 |
+
self.max_execution_time = max_execution_time
|
| 29 |
+
self.working_directory = working_directory or os.path.join(os.getcwd())
|
| 30 |
+
if not os.path.exists(self.working_directory):
|
| 31 |
+
os.makedirs(self.working_directory)
|
| 32 |
+
|
| 33 |
+
self.globals = {
|
| 34 |
+
"__builtins__": __builtins__,
|
| 35 |
+
"np": np,
|
| 36 |
+
"pd": pd,
|
| 37 |
+
"plt": plt,
|
| 38 |
+
"Image": Image,
|
| 39 |
+
}
|
| 40 |
+
self.temp_sqlite_db = os.path.join(tempfile.gettempdir(), "code_exec.db")
|
| 41 |
+
|
| 42 |
+
def execute_code(self, code: str, language: str = "python") -> Dict[str, Any]:
|
| 43 |
+
"""Execute the provided code in the selected programming language."""
|
| 44 |
+
language = language.lower()
|
| 45 |
+
execution_id = str(uuid.uuid4())
|
| 46 |
+
|
| 47 |
+
result = {
|
| 48 |
+
"execution_id": execution_id,
|
| 49 |
+
"status": "error",
|
| 50 |
+
"stdout": "",
|
| 51 |
+
"stderr": "",
|
| 52 |
+
"result": None,
|
| 53 |
+
"plots": [],
|
| 54 |
+
"dataframes": []
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
if language == "python":
|
| 59 |
+
return self._execute_python(code, execution_id)
|
| 60 |
+
elif language == "bash":
|
| 61 |
+
return self._execute_bash(code, execution_id)
|
| 62 |
+
elif language == "sql":
|
| 63 |
+
return self._execute_sql(code, execution_id)
|
| 64 |
+
elif language == "c":
|
| 65 |
+
return self._execute_c(code, execution_id)
|
| 66 |
+
elif language == "java":
|
| 67 |
+
return self._execute_java(code, execution_id)
|
| 68 |
+
else:
|
| 69 |
+
result["stderr"] = f"Unsupported language: {language}"
|
| 70 |
+
except Exception as e:
|
| 71 |
+
result["stderr"] = str(e)
|
| 72 |
+
|
| 73 |
+
return result
|
| 74 |
+
|
| 75 |
+
def _execute_python(self, code: str, execution_id: str) -> dict:
|
| 76 |
+
output_buffer = io.StringIO()
|
| 77 |
+
error_buffer = io.StringIO()
|
| 78 |
+
result = {
|
| 79 |
+
"execution_id": execution_id,
|
| 80 |
+
"status": "error",
|
| 81 |
+
"stdout": "",
|
| 82 |
+
"stderr": "",
|
| 83 |
+
"result": None,
|
| 84 |
+
"plots": [],
|
| 85 |
+
"dataframes": []
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
exec_dir = os.path.join(self.working_directory, execution_id)
|
| 90 |
+
os.makedirs(exec_dir, exist_ok=True)
|
| 91 |
+
plt.switch_backend('Agg')
|
| 92 |
+
|
| 93 |
+
with contextlib.redirect_stdout(output_buffer), contextlib.redirect_stderr(error_buffer):
|
| 94 |
+
exec_result = exec(code, self.globals)
|
| 95 |
+
|
| 96 |
+
if plt.get_fignums():
|
| 97 |
+
for i, fig_num in enumerate(plt.get_fignums()):
|
| 98 |
+
fig = plt.figure(fig_num)
|
| 99 |
+
img_path = os.path.join(exec_dir, f"plot_{i}.png")
|
| 100 |
+
fig.savefig(img_path)
|
| 101 |
+
with open(img_path, "rb") as img_file:
|
| 102 |
+
img_data = base64.b64encode(img_file.read()).decode('utf-8')
|
| 103 |
+
result["plots"].append({
|
| 104 |
+
"figure_number": fig_num,
|
| 105 |
+
"data": img_data
|
| 106 |
+
})
|
| 107 |
+
|
| 108 |
+
for var_name, var_value in self.globals.items():
|
| 109 |
+
if isinstance(var_value, pd.DataFrame) and len(var_value) > 0:
|
| 110 |
+
result["dataframes"].append({
|
| 111 |
+
"name": var_name,
|
| 112 |
+
"head": var_value.head().to_dict(),
|
| 113 |
+
"shape": var_value.shape,
|
| 114 |
+
"dtypes": str(var_value.dtypes)
|
| 115 |
+
})
|
| 116 |
+
|
| 117 |
+
result["status"] = "success"
|
| 118 |
+
result["stdout"] = output_buffer.getvalue()
|
| 119 |
+
result["result"] = exec_result
|
| 120 |
+
|
| 121 |
+
except Exception as e:
|
| 122 |
+
result["status"] = "error"
|
| 123 |
+
result["stderr"] = f"{error_buffer.getvalue()}\n{traceback.format_exc()}"
|
| 124 |
+
|
| 125 |
+
return result
|
| 126 |
+
|
| 127 |
+
def _execute_bash(self, code: str, execution_id: str) -> dict:
|
| 128 |
+
try:
|
| 129 |
+
completed = subprocess.run(
|
| 130 |
+
code, shell=True, capture_output=True, text=True, timeout=self.max_execution_time
|
| 131 |
+
)
|
| 132 |
+
return {
|
| 133 |
+
"execution_id": execution_id,
|
| 134 |
+
"status": "success" if completed.returncode == 0 else "error",
|
| 135 |
+
"stdout": completed.stdout,
|
| 136 |
+
"stderr": completed.stderr,
|
| 137 |
+
"result": None,
|
| 138 |
+
"plots": [],
|
| 139 |
+
"dataframes": []
|
| 140 |
+
}
|
| 141 |
+
except subprocess.TimeoutExpired:
|
| 142 |
+
return {
|
| 143 |
+
"execution_id": execution_id,
|
| 144 |
+
"status": "error",
|
| 145 |
+
"stdout": "",
|
| 146 |
+
"stderr": "Execution timed out.",
|
| 147 |
+
"result": None,
|
| 148 |
+
"plots": [],
|
| 149 |
+
"dataframes": []
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
def _execute_sql(self, code: str, execution_id: str) -> dict:
|
| 153 |
+
result = {
|
| 154 |
+
"execution_id": execution_id,
|
| 155 |
+
"status": "error",
|
| 156 |
+
"stdout": "",
|
| 157 |
+
"stderr": "",
|
| 158 |
+
"result": None,
|
| 159 |
+
"plots": [],
|
| 160 |
+
"dataframes": []
|
| 161 |
+
}
|
| 162 |
+
try:
|
| 163 |
+
conn = sqlite3.connect(self.temp_sqlite_db)
|
| 164 |
+
cur = conn.cursor()
|
| 165 |
+
cur.execute(code)
|
| 166 |
+
if code.strip().lower().startswith("select"):
|
| 167 |
+
columns = [description[0] for description in cur.description]
|
| 168 |
+
rows = cur.fetchall()
|
| 169 |
+
df = pd.DataFrame(rows, columns=columns)
|
| 170 |
+
result["dataframes"].append({
|
| 171 |
+
"name": "query_result",
|
| 172 |
+
"head": df.head().to_dict(),
|
| 173 |
+
"shape": df.shape,
|
| 174 |
+
"dtypes": str(df.dtypes)
|
| 175 |
+
})
|
| 176 |
+
else:
|
| 177 |
+
conn.commit()
|
| 178 |
+
|
| 179 |
+
result["status"] = "success"
|
| 180 |
+
result["stdout"] = "Query executed successfully."
|
| 181 |
+
|
| 182 |
+
except Exception as e:
|
| 183 |
+
result["stderr"] = str(e)
|
| 184 |
+
finally:
|
| 185 |
+
conn.close()
|
| 186 |
+
|
| 187 |
+
return result
|
| 188 |
+
|
| 189 |
+
def _execute_c(self, code: str, execution_id: str) -> dict:
|
| 190 |
+
temp_dir = tempfile.mkdtemp()
|
| 191 |
+
source_path = os.path.join(temp_dir, "program.c")
|
| 192 |
+
binary_path = os.path.join(temp_dir, "program")
|
| 193 |
+
|
| 194 |
+
try:
|
| 195 |
+
with open(source_path, "w") as f:
|
| 196 |
+
f.write(code)
|
| 197 |
+
|
| 198 |
+
compile_proc = subprocess.run(
|
| 199 |
+
["gcc", source_path, "-o", binary_path],
|
| 200 |
+
capture_output=True, text=True, timeout=self.max_execution_time
|
| 201 |
+
)
|
| 202 |
+
if compile_proc.returncode != 0:
|
| 203 |
+
return {
|
| 204 |
+
"execution_id": execution_id,
|
| 205 |
+
"status": "error",
|
| 206 |
+
"stdout": compile_proc.stdout,
|
| 207 |
+
"stderr": compile_proc.stderr,
|
| 208 |
+
"result": None,
|
| 209 |
+
"plots": [],
|
| 210 |
+
"dataframes": []
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
run_proc = subprocess.run(
|
| 214 |
+
[binary_path],
|
| 215 |
+
capture_output=True, text=True, timeout=self.max_execution_time
|
| 216 |
+
)
|
| 217 |
+
return {
|
| 218 |
+
"execution_id": execution_id,
|
| 219 |
+
"status": "success" if run_proc.returncode == 0 else "error",
|
| 220 |
+
"stdout": run_proc.stdout,
|
| 221 |
+
"stderr": run_proc.stderr,
|
| 222 |
+
"result": None,
|
| 223 |
+
"plots": [],
|
| 224 |
+
"dataframes": []
|
| 225 |
+
}
|
| 226 |
+
except Exception as e:
|
| 227 |
+
return {
|
| 228 |
+
"execution_id": execution_id,
|
| 229 |
+
"status": "error",
|
| 230 |
+
"stdout": "",
|
| 231 |
+
"stderr": str(e),
|
| 232 |
+
"result": None,
|
| 233 |
+
"plots": [],
|
| 234 |
+
"dataframes": []
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
def _execute_java(self, code: str, execution_id: str) -> dict:
|
| 238 |
+
temp_dir = tempfile.mkdtemp()
|
| 239 |
+
source_path = os.path.join(temp_dir, "Main.java")
|
| 240 |
+
|
| 241 |
+
try:
|
| 242 |
+
with open(source_path, "w") as f:
|
| 243 |
+
f.write(code)
|
| 244 |
+
|
| 245 |
+
compile_proc = subprocess.run(
|
| 246 |
+
["javac", source_path],
|
| 247 |
+
capture_output=True, text=True, timeout=self.max_execution_time
|
| 248 |
+
)
|
| 249 |
+
if compile_proc.returncode != 0:
|
| 250 |
+
return {
|
| 251 |
+
"execution_id": execution_id,
|
| 252 |
+
"status": "error",
|
| 253 |
+
"stdout": compile_proc.stdout,
|
| 254 |
+
"stderr": compile_proc.stderr,
|
| 255 |
+
"result": None,
|
| 256 |
+
"plots": [],
|
| 257 |
+
"dataframes": []
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
run_proc = subprocess.run(
|
| 261 |
+
["java", "-cp", temp_dir, "Main"],
|
| 262 |
+
capture_output=True, text=True, timeout=self.max_execution_time
|
| 263 |
+
)
|
| 264 |
+
return {
|
| 265 |
+
"execution_id": execution_id,
|
| 266 |
+
"status": "success" if run_proc.returncode == 0 else "error",
|
| 267 |
+
"stdout": run_proc.stdout,
|
| 268 |
+
"stderr": run_proc.stderr,
|
| 269 |
+
"result": None,
|
| 270 |
+
"plots": [],
|
| 271 |
+
"dataframes": []
|
| 272 |
+
}
|
| 273 |
+
except Exception as e:
|
| 274 |
+
return {
|
| 275 |
+
"execution_id": execution_id,
|
| 276 |
+
"status": "error",
|
| 277 |
+
"stdout": "",
|
| 278 |
+
"stderr": str(e),
|
| 279 |
+
"result": None,
|
| 280 |
+
"plots": [],
|
| 281 |
+
"dataframes": []
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
interpreter_instance = CodeInterpreter()
|
| 286 |
+
|
| 287 |
+
@tool
|
| 288 |
+
def execute_code_multilang(code: str, language: str = "python") -> str:
|
| 289 |
+
"""Execute code in multiple languages (Python, Bash, SQL, C, Java) and return results.
|
| 290 |
+
Args:
|
| 291 |
+
code (str): The source code to execute.
|
| 292 |
+
language (str): The language of the code. Supported: "python", "bash", "sql", "c", "java".
|
| 293 |
+
Returns:
|
| 294 |
+
A string summarizing the execution results (stdout, stderr, errors, plots, dataframes if any).
|
| 295 |
+
"""
|
| 296 |
+
supported_languages = ["python", "bash", "sql", "c", "java"]
|
| 297 |
+
language = language.lower()
|
| 298 |
+
|
| 299 |
+
if language not in supported_languages:
|
| 300 |
+
return f"β Unsupported language: {language}. Supported languages are: {', '.join(supported_languages)}"
|
| 301 |
+
|
| 302 |
+
result = interpreter_instance.execute_code(code, language=language)
|
| 303 |
+
|
| 304 |
+
response = []
|
| 305 |
+
|
| 306 |
+
if result["status"] == "success":
|
| 307 |
+
response.append(f"β
Code executed successfully in **{language.upper()}**")
|
| 308 |
+
|
| 309 |
+
if result.get("stdout"):
|
| 310 |
+
response.append(
|
| 311 |
+
"\n**Standard Output:**\n```\n" + result["stdout"].strip() + "\n```"
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
if result.get("stderr"):
|
| 315 |
+
response.append(
|
| 316 |
+
"\n**Standard Error (if any):**\n```\n"
|
| 317 |
+
+ result["stderr"].strip()
|
| 318 |
+
+ "\n```"
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
if result.get("result") is not None:
|
| 322 |
+
response.append(
|
| 323 |
+
"\n**Execution Result:**\n```\n"
|
| 324 |
+
+ str(result["result"]).strip()
|
| 325 |
+
+ "\n```"
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
if result.get("dataframes"):
|
| 329 |
+
for df_info in result["dataframes"]:
|
| 330 |
+
response.append(
|
| 331 |
+
f"\n**DataFrame `{df_info['name']}` (Shape: {df_info['shape']})**"
|
| 332 |
+
)
|
| 333 |
+
df_preview = pd.DataFrame(df_info["head"])
|
| 334 |
+
response.append("First 5 rows:\n```\n" + str(df_preview) + "\n```")
|
| 335 |
+
|
| 336 |
+
if result.get("plots"):
|
| 337 |
+
response.append(
|
| 338 |
+
f"\n**Generated {len(result['plots'])} plot(s)** (Image data returned separately)"
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
else:
|
| 342 |
+
response.append(f"β Code execution failed in **{language.upper()}**")
|
| 343 |
+
if result.get("stderr"):
|
| 344 |
+
response.append(
|
| 345 |
+
"\n**Error Log:**\n```\n" + result["stderr"].strip() + "\n```"
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
return "\n".join(response)
|
tools/documenttools.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.tools import tool
|
| 2 |
+
from typing import List, Dict, Any, Optional
|
| 3 |
+
import tempfile
|
| 4 |
+
from urllib.parse import urlparse
|
| 5 |
+
import os
|
| 6 |
+
import uuid
|
| 7 |
+
import requests
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import pytesseract
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
@tool
|
| 13 |
+
def save_and_read_file(content: str, filename: Optional[str] = None) -> str:
|
| 14 |
+
"""
|
| 15 |
+
Save content to a file and return the path.
|
| 16 |
+
Args:
|
| 17 |
+
content (str): the content to save to the file
|
| 18 |
+
filename (str, optional): the name of the file. If not provided, a random name file will be created.
|
| 19 |
+
"""
|
| 20 |
+
temp_dir = tempfile.gettempdir()
|
| 21 |
+
if filename is None:
|
| 22 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, dir=temp_dir)
|
| 23 |
+
filepath = temp_file.name
|
| 24 |
+
else:
|
| 25 |
+
filepath = os.path.join(temp_dir, filename)
|
| 26 |
+
|
| 27 |
+
with open(filepath, "w") as f:
|
| 28 |
+
f.write(content)
|
| 29 |
+
|
| 30 |
+
return f"File saved to {filepath}. You can read this file to process its contents."
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@tool
|
| 34 |
+
def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
|
| 35 |
+
"""
|
| 36 |
+
Download a file from a URL and save it to a temporary location.
|
| 37 |
+
Args:
|
| 38 |
+
url (str): the URL of the file to download.
|
| 39 |
+
filename (str, optional): the name of the file. If not provided, a random name file will be created.
|
| 40 |
+
"""
|
| 41 |
+
try:
|
| 42 |
+
# Parse URL to get filename if not provided
|
| 43 |
+
if not filename:
|
| 44 |
+
path = urlparse(url).path
|
| 45 |
+
filename = os.path.basename(path)
|
| 46 |
+
if not filename:
|
| 47 |
+
filename = f"downloaded_{uuid.uuid4().hex[:8]}"
|
| 48 |
+
|
| 49 |
+
# Create temporary file
|
| 50 |
+
temp_dir = tempfile.gettempdir()
|
| 51 |
+
filepath = os.path.join(temp_dir, filename)
|
| 52 |
+
|
| 53 |
+
# Download the file
|
| 54 |
+
response = requests.get(url, stream=True)
|
| 55 |
+
response.raise_for_status()
|
| 56 |
+
|
| 57 |
+
# Save the file
|
| 58 |
+
with open(filepath, "wb") as f:
|
| 59 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 60 |
+
f.write(chunk)
|
| 61 |
+
|
| 62 |
+
return f"File downloaded to {filepath}. You can read this file to process its contents."
|
| 63 |
+
except Exception as e:
|
| 64 |
+
return f"Error downloading file: {str(e)}"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@tool
|
| 68 |
+
def extract_text_from_image(image_path: str) -> str:
|
| 69 |
+
"""
|
| 70 |
+
Extract text from an image using OCR library pytesseract (if available).
|
| 71 |
+
Args:
|
| 72 |
+
image_path (str): the path to the image file.
|
| 73 |
+
"""
|
| 74 |
+
try:
|
| 75 |
+
# Open the image
|
| 76 |
+
image = Image.open(image_path)
|
| 77 |
+
|
| 78 |
+
# Extract text from the image
|
| 79 |
+
text = pytesseract.image_to_string(image)
|
| 80 |
+
|
| 81 |
+
return f"Extracted text from image:\n\n{text}"
|
| 82 |
+
except Exception as e:
|
| 83 |
+
return f"Error extracting text from image: {str(e)}"
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@tool
|
| 87 |
+
def analyze_csv_file(file_path: str, query: str) -> str:
|
| 88 |
+
"""
|
| 89 |
+
Analyze a CSV file using pandas and answer a question about it.
|
| 90 |
+
Args:
|
| 91 |
+
file_path (str): the path to the CSV file.
|
| 92 |
+
query (str): Question about the data
|
| 93 |
+
"""
|
| 94 |
+
try:
|
| 95 |
+
# Read the CSV file
|
| 96 |
+
df = pd.read_csv(file_path)
|
| 97 |
+
|
| 98 |
+
# Run various analyses based on the query
|
| 99 |
+
result = f"CSV file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
| 100 |
+
result += f"Columns: {', '.join(df.columns)}\n\n"
|
| 101 |
+
|
| 102 |
+
# Add summary statistics
|
| 103 |
+
result += "Summary statistics:\n"
|
| 104 |
+
result += str(df.describe())
|
| 105 |
+
|
| 106 |
+
return result
|
| 107 |
+
|
| 108 |
+
except Exception as e:
|
| 109 |
+
return f"Error analyzing CSV file: {str(e)}"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@tool
|
| 113 |
+
def analyze_excel_file(file_path: str, query: str) -> str:
|
| 114 |
+
"""
|
| 115 |
+
Analyze an Excel file using pandas and answer a question about it.
|
| 116 |
+
Args:
|
| 117 |
+
file_path (str): the path to the Excel file.
|
| 118 |
+
query (str): Question about the data
|
| 119 |
+
"""
|
| 120 |
+
try:
|
| 121 |
+
# Read the Excel file
|
| 122 |
+
df = pd.read_excel(file_path)
|
| 123 |
+
|
| 124 |
+
# Run various analyses based on the query
|
| 125 |
+
result = (
|
| 126 |
+
f"Excel file loaded with {len(df)} rows and {len(df.columns)} columns.\n"
|
| 127 |
+
)
|
| 128 |
+
result += f"Columns: {', '.join(df.columns)}\n\n"
|
| 129 |
+
|
| 130 |
+
# Add summary statistics
|
| 131 |
+
result += "Summary statistics:\n"
|
| 132 |
+
result += str(df.describe())
|
| 133 |
+
|
| 134 |
+
return result
|
| 135 |
+
|
| 136 |
+
except Exception as e:
|
| 137 |
+
return f"Error analyzing Excel file: {str(e)}"
|
tools/imagetools.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.tools import tool
|
| 2 |
+
import os
|
| 3 |
+
import io
|
| 4 |
+
import base64
|
| 5 |
+
import uuid
|
| 6 |
+
from PIL import Image
|
| 7 |
+
from typing import List, Dict, Any, Optional
|
| 8 |
+
import numpy as np
|
| 9 |
+
from PIL import Image, ImageDraw, ImageFont, ImageEnhance, ImageFilter
|
| 10 |
+
|
| 11 |
+
# Helper functions for image processing
|
| 12 |
+
def encode_image(image_path: str) -> str:
|
| 13 |
+
"""Convert an image file to base64 string."""
|
| 14 |
+
with open(image_path, "rb") as image_file:
|
| 15 |
+
return base64.b64encode(image_file.read()).decode("utf-8")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def decode_image(base64_string: str) -> Image.Image:
|
| 19 |
+
"""Convert a base64 string to a PIL Image."""
|
| 20 |
+
image_data = base64.b64decode(base64_string)
|
| 21 |
+
return Image.open(io.BytesIO(image_data))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def save_image(image: Image.Image, directory: str = "image_outputs") -> str:
|
| 25 |
+
"""Save a PIL Image to disk and return the path."""
|
| 26 |
+
os.makedirs(directory, exist_ok=True)
|
| 27 |
+
image_id = str(uuid.uuid4())
|
| 28 |
+
image_path = os.path.join(directory, f"{image_id}.png")
|
| 29 |
+
image.save(image_path)
|
| 30 |
+
return image_path
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@tool
|
| 34 |
+
def analyze_image(image_base64: str) -> Dict[str, Any]:
|
| 35 |
+
"""
|
| 36 |
+
Analyze basic properties of an image (size, mode, color analysis, thumbnail preview).
|
| 37 |
+
Args:
|
| 38 |
+
image_base64 (str): Base64 encoded image string
|
| 39 |
+
Returns:
|
| 40 |
+
Dictionary with analysis result
|
| 41 |
+
"""
|
| 42 |
+
try:
|
| 43 |
+
img = decode_image(image_base64)
|
| 44 |
+
width, height = img.size
|
| 45 |
+
mode = img.mode
|
| 46 |
+
|
| 47 |
+
if mode in ("RGB", "RGBA"):
|
| 48 |
+
arr = np.array(img)
|
| 49 |
+
avg_colors = arr.mean(axis=(0, 1))
|
| 50 |
+
dominant = ["Red", "Green", "Blue"][np.argmax(avg_colors[:3])]
|
| 51 |
+
brightness = avg_colors.mean()
|
| 52 |
+
color_analysis = {
|
| 53 |
+
"average_rgb": avg_colors.tolist(),
|
| 54 |
+
"brightness": brightness,
|
| 55 |
+
"dominant_color": dominant,
|
| 56 |
+
}
|
| 57 |
+
else:
|
| 58 |
+
color_analysis = {"note": f"No color analysis for mode {mode}"}
|
| 59 |
+
|
| 60 |
+
thumbnail = img.copy()
|
| 61 |
+
thumbnail.thumbnail((100, 100))
|
| 62 |
+
thumb_path = save_image(thumbnail, "thumbnails")
|
| 63 |
+
thumbnail_base64 = encode_image(thumb_path)
|
| 64 |
+
|
| 65 |
+
return {
|
| 66 |
+
"dimensions": (width, height),
|
| 67 |
+
"mode": mode,
|
| 68 |
+
"color_analysis": color_analysis,
|
| 69 |
+
"thumbnail": thumbnail_base64,
|
| 70 |
+
}
|
| 71 |
+
except Exception as e:
|
| 72 |
+
return {"error": str(e)}
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@tool
|
| 76 |
+
def transform_image(
|
| 77 |
+
image_base64: str, operation: str, params: Optional[Dict[str, Any]] = None
|
| 78 |
+
) -> Dict[str, Any]:
|
| 79 |
+
"""
|
| 80 |
+
Apply transformations: resize, rotate, crop, flip, brightness, contrast, blur, sharpen, grayscale.
|
| 81 |
+
Args:
|
| 82 |
+
image_base64 (str): Base64 encoded input image
|
| 83 |
+
operation (str): Transformation operation
|
| 84 |
+
params (Dict[str, Any], optional): Parameters for the operation
|
| 85 |
+
Returns:
|
| 86 |
+
Dictionary with transformed image (base64)
|
| 87 |
+
"""
|
| 88 |
+
try:
|
| 89 |
+
img = decode_image(image_base64)
|
| 90 |
+
params = params or {}
|
| 91 |
+
|
| 92 |
+
if operation == "resize":
|
| 93 |
+
img = img.resize(
|
| 94 |
+
(
|
| 95 |
+
params.get("width", img.width // 2),
|
| 96 |
+
params.get("height", img.height // 2),
|
| 97 |
+
)
|
| 98 |
+
)
|
| 99 |
+
elif operation == "rotate":
|
| 100 |
+
img = img.rotate(params.get("angle", 90), expand=True)
|
| 101 |
+
elif operation == "crop":
|
| 102 |
+
img = img.crop(
|
| 103 |
+
(
|
| 104 |
+
params.get("left", 0),
|
| 105 |
+
params.get("top", 0),
|
| 106 |
+
params.get("right", img.width),
|
| 107 |
+
params.get("bottom", img.height),
|
| 108 |
+
)
|
| 109 |
+
)
|
| 110 |
+
elif operation == "flip":
|
| 111 |
+
if params.get("direction", "horizontal") == "horizontal":
|
| 112 |
+
img = img.transpose(Image.FLIP_LEFT_RIGHT)
|
| 113 |
+
else:
|
| 114 |
+
img = img.transpose(Image.FLIP_TOP_BOTTOM)
|
| 115 |
+
elif operation == "adjust_brightness":
|
| 116 |
+
img = ImageEnhance.Brightness(img).enhance(params.get("factor", 1.5))
|
| 117 |
+
elif operation == "adjust_contrast":
|
| 118 |
+
img = ImageEnhance.Contrast(img).enhance(params.get("factor", 1.5))
|
| 119 |
+
elif operation == "blur":
|
| 120 |
+
img = img.filter(ImageFilter.GaussianBlur(params.get("radius", 2)))
|
| 121 |
+
elif operation == "sharpen":
|
| 122 |
+
img = img.filter(ImageFilter.SHARPEN)
|
| 123 |
+
elif operation == "grayscale":
|
| 124 |
+
img = img.convert("L")
|
| 125 |
+
else:
|
| 126 |
+
return {"error": f"Unknown operation: {operation}"}
|
| 127 |
+
|
| 128 |
+
result_path = save_image(img)
|
| 129 |
+
result_base64 = encode_image(result_path)
|
| 130 |
+
return {"transformed_image": result_base64}
|
| 131 |
+
|
| 132 |
+
except Exception as e:
|
| 133 |
+
return {"error": str(e)}
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@tool
|
| 137 |
+
def draw_on_image(
|
| 138 |
+
image_base64: str, drawing_type: str, params: Dict[str, Any]
|
| 139 |
+
) -> Dict[str, Any]:
|
| 140 |
+
"""
|
| 141 |
+
Draw shapes (rectangle, circle, line) or text onto an image.
|
| 142 |
+
Args:
|
| 143 |
+
image_base64 (str): Base64 encoded input image
|
| 144 |
+
drawing_type (str): Drawing type
|
| 145 |
+
params (Dict[str, Any]): Drawing parameters
|
| 146 |
+
Returns:
|
| 147 |
+
Dictionary with result image (base64)
|
| 148 |
+
"""
|
| 149 |
+
try:
|
| 150 |
+
img = decode_image(image_base64)
|
| 151 |
+
draw = ImageDraw.Draw(img)
|
| 152 |
+
color = params.get("color", "red")
|
| 153 |
+
|
| 154 |
+
if drawing_type == "rectangle":
|
| 155 |
+
draw.rectangle(
|
| 156 |
+
[params["left"], params["top"], params["right"], params["bottom"]],
|
| 157 |
+
outline=color,
|
| 158 |
+
width=params.get("width", 2),
|
| 159 |
+
)
|
| 160 |
+
elif drawing_type == "circle":
|
| 161 |
+
x, y, r = params["x"], params["y"], params["radius"]
|
| 162 |
+
draw.ellipse(
|
| 163 |
+
(x - r, y - r, x + r, y + r),
|
| 164 |
+
outline=color,
|
| 165 |
+
width=params.get("width", 2),
|
| 166 |
+
)
|
| 167 |
+
elif drawing_type == "line":
|
| 168 |
+
draw.line(
|
| 169 |
+
(
|
| 170 |
+
params["start_x"],
|
| 171 |
+
params["start_y"],
|
| 172 |
+
params["end_x"],
|
| 173 |
+
params["end_y"],
|
| 174 |
+
),
|
| 175 |
+
fill=color,
|
| 176 |
+
width=params.get("width", 2),
|
| 177 |
+
)
|
| 178 |
+
elif drawing_type == "text":
|
| 179 |
+
font_size = params.get("font_size", 20)
|
| 180 |
+
try:
|
| 181 |
+
font = ImageFont.truetype("arial.ttf", font_size)
|
| 182 |
+
except IOError:
|
| 183 |
+
font = ImageFont.load_default()
|
| 184 |
+
draw.text(
|
| 185 |
+
(params["x"], params["y"]),
|
| 186 |
+
params.get("text", "Text"),
|
| 187 |
+
fill=color,
|
| 188 |
+
font=font,
|
| 189 |
+
)
|
| 190 |
+
else:
|
| 191 |
+
return {"error": f"Unknown drawing type: {drawing_type}"}
|
| 192 |
+
|
| 193 |
+
result_path = save_image(img)
|
| 194 |
+
result_base64 = encode_image(result_path)
|
| 195 |
+
return {"result_image": result_base64}
|
| 196 |
+
|
| 197 |
+
except Exception as e:
|
| 198 |
+
return {"error": str(e)}
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@tool
|
| 202 |
+
def generate_simple_image(
|
| 203 |
+
image_type: str,
|
| 204 |
+
width: int = 500,
|
| 205 |
+
height: int = 500,
|
| 206 |
+
params: Optional[Dict[str, Any]] = None,
|
| 207 |
+
) -> Dict[str, Any]:
|
| 208 |
+
"""
|
| 209 |
+
Generate a simple image (gradient, noise, pattern, chart).
|
| 210 |
+
Args:
|
| 211 |
+
image_type (str): Type of image
|
| 212 |
+
width (int), height (int)
|
| 213 |
+
params (Dict[str, Any], optional): Specific parameters
|
| 214 |
+
Returns:
|
| 215 |
+
Dictionary with generated image (base64)
|
| 216 |
+
"""
|
| 217 |
+
try:
|
| 218 |
+
params = params or {}
|
| 219 |
+
|
| 220 |
+
if image_type == "gradient":
|
| 221 |
+
direction = params.get("direction", "horizontal")
|
| 222 |
+
start_color = params.get("start_color", (255, 0, 0))
|
| 223 |
+
end_color = params.get("end_color", (0, 0, 255))
|
| 224 |
+
|
| 225 |
+
img = Image.new("RGB", (width, height))
|
| 226 |
+
draw = ImageDraw.Draw(img)
|
| 227 |
+
|
| 228 |
+
if direction == "horizontal":
|
| 229 |
+
for x in range(width):
|
| 230 |
+
r = int(
|
| 231 |
+
start_color[0] + (end_color[0] - start_color[0]) * x / width
|
| 232 |
+
)
|
| 233 |
+
g = int(
|
| 234 |
+
start_color[1] + (end_color[1] - start_color[1]) * x / width
|
| 235 |
+
)
|
| 236 |
+
b = int(
|
| 237 |
+
start_color[2] + (end_color[2] - start_color[2]) * x / width
|
| 238 |
+
)
|
| 239 |
+
draw.line([(x, 0), (x, height)], fill=(r, g, b))
|
| 240 |
+
else:
|
| 241 |
+
for y in range(height):
|
| 242 |
+
r = int(
|
| 243 |
+
start_color[0] + (end_color[0] - start_color[0]) * y / height
|
| 244 |
+
)
|
| 245 |
+
g = int(
|
| 246 |
+
start_color[1] + (end_color[1] - start_color[1]) * y / height
|
| 247 |
+
)
|
| 248 |
+
b = int(
|
| 249 |
+
start_color[2] + (end_color[2] - start_color[2]) * y / height
|
| 250 |
+
)
|
| 251 |
+
draw.line([(0, y), (width, y)], fill=(r, g, b))
|
| 252 |
+
|
| 253 |
+
elif image_type == "noise":
|
| 254 |
+
noise_array = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)
|
| 255 |
+
img = Image.fromarray(noise_array, "RGB")
|
| 256 |
+
|
| 257 |
+
else:
|
| 258 |
+
return {"error": f"Unsupported image_type {image_type}"}
|
| 259 |
+
|
| 260 |
+
result_path = save_image(img)
|
| 261 |
+
result_base64 = encode_image(result_path)
|
| 262 |
+
return {"generated_image": result_base64}
|
| 263 |
+
|
| 264 |
+
except Exception as e:
|
| 265 |
+
return {"error": str(e)}
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
@tool
|
| 269 |
+
def combine_images(
|
| 270 |
+
images_base64: List[str], operation: str, params: Optional[Dict[str, Any]] = None
|
| 271 |
+
) -> Dict[str, Any]:
|
| 272 |
+
"""
|
| 273 |
+
Combine multiple images (collage, stack, blend).
|
| 274 |
+
Args:
|
| 275 |
+
images_base64 (List[str]): List of base64 images
|
| 276 |
+
operation (str): Combination type
|
| 277 |
+
params (Dict[str, Any], optional)
|
| 278 |
+
Returns:
|
| 279 |
+
Dictionary with combined image (base64)
|
| 280 |
+
"""
|
| 281 |
+
try:
|
| 282 |
+
images = [decode_image(b64) for b64 in images_base64]
|
| 283 |
+
params = params or {}
|
| 284 |
+
|
| 285 |
+
if operation == "stack":
|
| 286 |
+
direction = params.get("direction", "horizontal")
|
| 287 |
+
if direction == "horizontal":
|
| 288 |
+
total_width = sum(img.width for img in images)
|
| 289 |
+
max_height = max(img.height for img in images)
|
| 290 |
+
new_img = Image.new("RGB", (total_width, max_height))
|
| 291 |
+
x = 0
|
| 292 |
+
for img in images:
|
| 293 |
+
new_img.paste(img, (x, 0))
|
| 294 |
+
x += img.width
|
| 295 |
+
else:
|
| 296 |
+
max_width = max(img.width for img in images)
|
| 297 |
+
total_height = sum(img.height for img in images)
|
| 298 |
+
new_img = Image.new("RGB", (max_width, total_height))
|
| 299 |
+
y = 0
|
| 300 |
+
for img in images:
|
| 301 |
+
new_img.paste(img, (0, y))
|
| 302 |
+
y += img.height
|
| 303 |
+
else:
|
| 304 |
+
return {"error": f"Unsupported combination operation {operation}"}
|
| 305 |
+
|
| 306 |
+
result_path = save_image(new_img)
|
| 307 |
+
result_base64 = encode_image(result_path)
|
| 308 |
+
return {"combined_image": result_base64}
|
| 309 |
+
|
| 310 |
+
except Exception as e:
|
| 311 |
+
return {"error": str(e)}
|
tools/mathtools.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.tools import tool
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
@tool
|
| 5 |
+
def multiply(a: float, b: float) -> float:
|
| 6 |
+
"""
|
| 7 |
+
Multiplies two numbers.
|
| 8 |
+
Args:
|
| 9 |
+
a (float): the first number
|
| 10 |
+
b (float): the second number
|
| 11 |
+
"""
|
| 12 |
+
return a * b
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@tool
|
| 16 |
+
def add(a: float, b: float) -> float:
|
| 17 |
+
"""
|
| 18 |
+
Adds two numbers.
|
| 19 |
+
Args:
|
| 20 |
+
a (float): the first number
|
| 21 |
+
b (float): the second number
|
| 22 |
+
"""
|
| 23 |
+
return a + b
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@tool
|
| 27 |
+
def subtract(a: float, b: float) -> int:
|
| 28 |
+
"""
|
| 29 |
+
Subtracts two numbers.
|
| 30 |
+
Args:
|
| 31 |
+
a (float): the first number
|
| 32 |
+
b (float): the second number
|
| 33 |
+
"""
|
| 34 |
+
return a - b
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@tool
|
| 38 |
+
def divide(a: float, b: float) -> float:
|
| 39 |
+
"""
|
| 40 |
+
Divides two numbers.
|
| 41 |
+
Args:
|
| 42 |
+
a (float): the first float number
|
| 43 |
+
b (float): the second float number
|
| 44 |
+
"""
|
| 45 |
+
if b == 0:
|
| 46 |
+
raise ValueError("Cannot divided by zero.")
|
| 47 |
+
return a / b
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@tool
|
| 51 |
+
def modulus(a: int, b: int) -> int:
|
| 52 |
+
"""
|
| 53 |
+
Get the modulus of two numbers.
|
| 54 |
+
Args:
|
| 55 |
+
a (int): the first number
|
| 56 |
+
b (int): the second number
|
| 57 |
+
"""
|
| 58 |
+
return a % b
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@tool
|
| 62 |
+
def power(a: float, b: float) -> float:
|
| 63 |
+
"""
|
| 64 |
+
Get the power of two numbers.
|
| 65 |
+
Args:
|
| 66 |
+
a (float): the first number
|
| 67 |
+
b (float): the second number
|
| 68 |
+
"""
|
| 69 |
+
return a**b
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@tool
|
| 73 |
+
def square_root(a: float) -> float | complex:
|
| 74 |
+
"""
|
| 75 |
+
Get the square root of a number.
|
| 76 |
+
Args:
|
| 77 |
+
a (float): the number to get the square root of
|
| 78 |
+
"""
|
| 79 |
+
if a >= 0:
|
| 80 |
+
return a**0.5
|
| 81 |
+
return cmath.sqrt(a)
|
tools/searchtools.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from langchain_core.tools import tool
|
| 2 |
+
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 3 |
+
from langchain_community.document_loaders import WikipediaLoader
|
| 4 |
+
from langchain_community.document_loaders import ArxivLoader
|
| 5 |
+
import os
|
| 6 |
+
from supabase.client import Client, create_client
|
| 7 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 8 |
+
from langchain_community.vectorstores import SupabaseVectorStore
|
| 9 |
+
from langchain_core.tools.retriever import create_retriever_tool
|
| 10 |
+
|
| 11 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # dim=768
|
| 12 |
+
|
| 13 |
+
supabase_url = os.environ.get("SUPABASE_URL")
|
| 14 |
+
supabase_key = os.environ.get("SUPABASE_SERVICE_KEY")
|
| 15 |
+
supabase: Client = create_client(supabase_url, supabase_key)
|
| 16 |
+
vector_store = SupabaseVectorStore(
|
| 17 |
+
client=supabase,
|
| 18 |
+
embedding= embeddings,
|
| 19 |
+
table_name="documents",
|
| 20 |
+
query_name="match_documents",
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
question_retrieve_tool = create_retriever_tool(
|
| 24 |
+
vector_store.as_retriever(),
|
| 25 |
+
"Question_Retriever",
|
| 26 |
+
"Find similar questions in the vector database for the given question.",
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@tool
|
| 32 |
+
def wiki_search(query: str) -> str:
|
| 33 |
+
"""Search Wikipedia for a query and return maximum 2 results.
|
| 34 |
+
Args:
|
| 35 |
+
query: The search query."""
|
| 36 |
+
search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
| 37 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
| 38 |
+
[
|
| 39 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
|
| 40 |
+
for doc in search_docs
|
| 41 |
+
]
|
| 42 |
+
)
|
| 43 |
+
return {"wiki_results": formatted_search_docs}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@tool
|
| 47 |
+
def web_search(query: str) -> str:
|
| 48 |
+
"""Search Tavily for a query and return maximum 3 results.
|
| 49 |
+
Args:
|
| 50 |
+
query: The search query."""
|
| 51 |
+
search_docs = TavilySearchResults(max_results=3).invoke(query=query)
|
| 52 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
| 53 |
+
[
|
| 54 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
|
| 55 |
+
for doc in search_docs
|
| 56 |
+
]
|
| 57 |
+
)
|
| 58 |
+
return {"web_results": formatted_search_docs}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@tool
|
| 62 |
+
def arxiv_search(query: str) -> str:
|
| 63 |
+
"""Search Arxiv for a query and return maximum 3 result.
|
| 64 |
+
Args:
|
| 65 |
+
query: The search query."""
|
| 66 |
+
search_docs = ArxivLoader(query=query, load_max_docs=3).load()
|
| 67 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
| 68 |
+
[
|
| 69 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
|
| 70 |
+
for doc in search_docs
|
| 71 |
+
]
|
| 72 |
+
)
|
| 73 |
+
return {"arxiv_results": formatted_search_docs}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@tool
|
| 77 |
+
def similar_question_search(question: str) -> str:
|
| 78 |
+
"""Search the vector database for similar questions and return the first results.
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
question: the question human provided."""
|
| 82 |
+
matched_docs = vector_store.similarity_search(question, 3)
|
| 83 |
+
formatted_search_docs = "\n\n---\n\n".join(
|
| 84 |
+
[
|
| 85 |
+
f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
|
| 86 |
+
for doc in matched_docs
|
| 87 |
+
])
|
| 88 |
+
return {"similar_questions": formatted_search_docs}
|
x.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from smolagents import DuckDuckGoSearchTool
|
| 2 |
+
|
| 3 |
+
web_search_tool = DuckDuckGoSearchTool(max_results=5, rate_limit=2.0)
|
| 4 |
+
|
| 5 |
+
# In v1.22+, call with query=...
|
| 6 |
+
results = web_search_tool(query="Hugging Face")
|
| 7 |
+
print(results)
|