krim798 commited on
hopefully works
Browse files- app.py +235 -43
- pyproject.toml +5 -0
- requirements.txt +6 -0
- uv.lock +0 -0
app.py
CHANGED
|
@@ -9,7 +9,193 @@ from langchain_core.tools import tool
|
|
| 9 |
from dotenv import load_dotenv
|
| 10 |
import wikipedia
|
| 11 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
@tool
|
| 14 |
def current_datetime(_: str = "") -> str:
|
| 15 |
"""
|
|
@@ -73,57 +259,63 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 73 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 74 |
|
| 75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
class BasicAgent:
|
| 77 |
def __init__(self):
|
| 78 |
print("BasicAgent initialized.")
|
| 79 |
|
| 80 |
def __call__(self, question: str) -> str:
|
| 81 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
cleaned = question.lower().replace("wikipedia", "").replace("wiki", "").strip()
|
| 104 |
-
return wikipedia_search(cleaned if cleaned else question)
|
| 105 |
-
except Exception as e:
|
| 106 |
-
print(f"Wikipedia tool failed: {e}")
|
| 107 |
-
|
| 108 |
-
# 4. Web search + scrape logic
|
| 109 |
-
try:
|
| 110 |
-
search_result = web_search(question)
|
| 111 |
-
# Try to extract a URL from the search result for scraping
|
| 112 |
-
import re
|
| 113 |
-
url_match = re.search(r"\((https?://[^\s)]+)\)", search_result)
|
| 114 |
-
if url_match:
|
| 115 |
-
url = url_match.group(1)
|
| 116 |
-
scraped = scraper(url)
|
| 117 |
-
# Combine search snippet and scraped content for a richer answer
|
| 118 |
-
return f"{search_result}\n\nScraped content:\n{scraped}"
|
| 119 |
else:
|
| 120 |
-
return
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
|
| 126 |
-
|
| 127 |
|
| 128 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 129 |
"""
|
|
|
|
| 9 |
from dotenv import load_dotenv
|
| 10 |
import wikipedia
|
| 11 |
from datetime import datetime
|
| 12 |
+
from smolagents import Tool
|
| 13 |
+
from docling.document_converter import DocumentConverter
|
| 14 |
+
from docling.chunking import HierarchicalChunker
|
| 15 |
+
from sentence_transformers import SentenceTransformer, util
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ContentRetrieverTool(Tool):
|
| 20 |
+
name = "retrieve_content"
|
| 21 |
+
description = """Retrieve the content of a webpage or document in markdown format. Supports PDF, DOCX, XLSX, HTML, images, and more."""
|
| 22 |
+
inputs = {
|
| 23 |
+
"url": {
|
| 24 |
+
"type": "string",
|
| 25 |
+
"description": "The URL or local path of the webpage or document to retrieve.",
|
| 26 |
+
},
|
| 27 |
+
"query": {
|
| 28 |
+
"type": "string",
|
| 29 |
+
"description": "The subject on the page you are looking for. The shorter the more relevant content is returned.",
|
| 30 |
+
},
|
| 31 |
+
}
|
| 32 |
+
output_type = "string"
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
model_name: str | None = None,
|
| 37 |
+
threshold: float = 0.2,
|
| 38 |
+
**kwargs,
|
| 39 |
+
):
|
| 40 |
+
self.threshold = threshold
|
| 41 |
+
self._document_converter = DocumentConverter()
|
| 42 |
+
self._model = SentenceTransformer(
|
| 43 |
+
model_name if model_name is not None else "all-MiniLM-L6-v2"
|
| 44 |
+
)
|
| 45 |
+
self._chunker = HierarchicalChunker()
|
| 46 |
+
|
| 47 |
+
super().__init__(**kwargs)
|
| 48 |
+
|
| 49 |
+
def forward(self, url: str, query: str) -> str:
|
| 50 |
+
document = self._document_converter.convert(url).document
|
| 51 |
+
|
| 52 |
+
chunks = list(self._chunker.chunk(dl_doc=document))
|
| 53 |
+
if len(chunks) == 0:
|
| 54 |
+
return "No content found."
|
| 55 |
+
|
| 56 |
+
chunks_text = [chunk.text for chunk in chunks]
|
| 57 |
+
chunks_with_context = [self._chunker.contextualize(chunk) for chunk in chunks]
|
| 58 |
+
chunks_context = [
|
| 59 |
+
chunks_with_context[i].replace(chunks_text[i], "").strip()
|
| 60 |
+
for i in range(len(chunks))
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
chunk_embeddings = self._model.encode(chunks_text, convert_to_tensor=True)
|
| 64 |
+
context_embeddings = self._model.encode(chunks_context, convert_to_tensor=True)
|
| 65 |
+
query_embedding = self._model.encode(
|
| 66 |
+
[term.strip() for term in query.split(",") if term.strip()],
|
| 67 |
+
convert_to_tensor=True,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
selected_indices = [] # aggregate indexes across chunks and context matches and for all queries
|
| 71 |
+
for embeddings in [
|
| 72 |
+
context_embeddings,
|
| 73 |
+
chunk_embeddings,
|
| 74 |
+
]:
|
| 75 |
+
# Compute cosine similarities (returns 1D tensor)
|
| 76 |
+
for cos_scores in util.pytorch_cos_sim(query_embedding, embeddings):
|
| 77 |
+
# Convert to softmax probabilities
|
| 78 |
+
probabilities = torch.nn.functional.softmax(cos_scores, dim=0)
|
| 79 |
+
# Sort by probability descending
|
| 80 |
+
sorted_indices = torch.argsort(probabilities, descending=True)
|
| 81 |
+
# Accumulate until total probability reaches threshold
|
| 82 |
+
|
| 83 |
+
cumulative = 0.0
|
| 84 |
+
for i in sorted_indices:
|
| 85 |
+
cumulative += probabilities[i].item()
|
| 86 |
+
selected_indices.append(i.item())
|
| 87 |
+
if cumulative >= self.threshold:
|
| 88 |
+
break
|
| 89 |
+
|
| 90 |
+
selected_indices = list(
|
| 91 |
+
dict.fromkeys(selected_indices)
|
| 92 |
+
) # remove duplicates and preserve order
|
| 93 |
+
selected_indices = selected_indices[
|
| 94 |
+
::-1
|
| 95 |
+
] # make most relevant items last for better focus
|
| 96 |
+
|
| 97 |
+
if len(selected_indices) == 0:
|
| 98 |
+
return "No content found."
|
| 99 |
+
|
| 100 |
+
return "\n\n".join([chunks_with_context[idx] for idx in selected_indices])
|
| 101 |
+
from smolagents import Tool
|
| 102 |
+
from googleapiclient.discovery import build
|
| 103 |
+
import os
|
| 104 |
|
| 105 |
+
|
| 106 |
+
class GoogleSearchTool(Tool):
|
| 107 |
+
name = "web_search"
|
| 108 |
+
description = """Performs a google web search for query then returns top search results in markdown format."""
|
| 109 |
+
inputs = {
|
| 110 |
+
"query": {
|
| 111 |
+
"type": "string",
|
| 112 |
+
"description": "The query to perform search.",
|
| 113 |
+
},
|
| 114 |
+
}
|
| 115 |
+
output_type = "string"
|
| 116 |
+
|
| 117 |
+
skip_forward_signature_validation = True
|
| 118 |
+
|
| 119 |
+
def __init__(
|
| 120 |
+
self,
|
| 121 |
+
api_key: str | None = None,
|
| 122 |
+
search_engine_id: str | None = None,
|
| 123 |
+
num_results: int = 10,
|
| 124 |
+
**kwargs,
|
| 125 |
+
):
|
| 126 |
+
api_key = api_key if api_key is not None else os.getenv("GOOGLE_SEARCH_API_KEY")
|
| 127 |
+
if not api_key:
|
| 128 |
+
raise ValueError(
|
| 129 |
+
"Please set the GOOGLE_SEARCH_API_KEY environment variable."
|
| 130 |
+
)
|
| 131 |
+
search_engine_id = (
|
| 132 |
+
search_engine_id
|
| 133 |
+
if search_engine_id is not None
|
| 134 |
+
else os.getenv("GOOGLE_SEARCH_ENGINE_ID")
|
| 135 |
+
)
|
| 136 |
+
if not search_engine_id:
|
| 137 |
+
raise ValueError(
|
| 138 |
+
"Please set the GOOGLE_SEARCH_ENGINE_ID environment variable."
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
self.cse = build("customsearch", "v1", developerKey=api_key).cse()
|
| 142 |
+
self.cx = search_engine_id
|
| 143 |
+
self.num = num_results
|
| 144 |
+
super().__init__(**kwargs)
|
| 145 |
+
|
| 146 |
+
def _collect_params(self) -> dict:
|
| 147 |
+
return {}
|
| 148 |
+
|
| 149 |
+
def forward(self, query: str, *args, **kwargs) -> str:
|
| 150 |
+
params = {
|
| 151 |
+
"q": query,
|
| 152 |
+
"cx": self.cx,
|
| 153 |
+
"fields": "items(title,link,snippet)",
|
| 154 |
+
"num": self.num,
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
params = params | self._collect_params(*args, **kwargs)
|
| 158 |
+
|
| 159 |
+
response = self.cse.list(**params).execute()
|
| 160 |
+
if "items" not in response:
|
| 161 |
+
return "No results found."
|
| 162 |
+
|
| 163 |
+
result = "\n\n".join(
|
| 164 |
+
[
|
| 165 |
+
f"[{item['title']}]({item['link']})\n{item['snippet']}"
|
| 166 |
+
for item in response["items"]
|
| 167 |
+
]
|
| 168 |
+
)
|
| 169 |
+
return result
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class GoogleSiteSearchTool(GoogleSearchTool):
|
| 173 |
+
name = "site_search"
|
| 174 |
+
description = """Performs a google search within the website for query then returns top search results in markdown format."""
|
| 175 |
+
inputs = {
|
| 176 |
+
"query": {
|
| 177 |
+
"type": "string",
|
| 178 |
+
"description": "The query to perform search.",
|
| 179 |
+
},
|
| 180 |
+
"site": {
|
| 181 |
+
"type": "string",
|
| 182 |
+
"description": "The domain of the site on which to search.",
|
| 183 |
+
},
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
def _collect_params(self, site: str) -> dict:
|
| 187 |
+
return {
|
| 188 |
+
"siteSearch": site,
|
| 189 |
+
"siteSearchFilter": "i",
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def get_one_word_answer(text: str) -> str:
|
| 195 |
+
# Try to extract a single word (alphanumeric) from the response
|
| 196 |
+
import re
|
| 197 |
+
words = re.findall(r'\b\w+\b', text)
|
| 198 |
+
return words[0] if words else text.strip()
|
| 199 |
@tool
|
| 200 |
def current_datetime(_: str = "") -> str:
|
| 201 |
"""
|
|
|
|
| 259 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 260 |
|
| 261 |
|
| 262 |
+
# ...existing code...
|
| 263 |
+
|
| 264 |
+
TOOL_REGISTRY = {
|
| 265 |
+
"calculator": calculator,
|
| 266 |
+
"current_datetime": current_datetime,
|
| 267 |
+
"wikipedia_search": wikipedia_search,
|
| 268 |
+
"scraper": scraper,
|
| 269 |
+
"web_search": web_search,
|
| 270 |
+
"site_search": GoogleSiteSearchTool().forward,
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
def select_tool(question: str):
|
| 274 |
+
import re
|
| 275 |
+
# Tool selection logic (can be replaced by LLM prompt in advanced setups)
|
| 276 |
+
if any(kw in question.lower() for kw in ["calculate", "compute", "evaluate", "+", "-", "*", "/", "^", "sqrt", "log", "sum", "product"]):
|
| 277 |
+
return "calculator"
|
| 278 |
+
if any(kw in question.lower() for kw in ["date", "time", "day", "month", "year", "current time", "current date"]):
|
| 279 |
+
return "current_datetime"
|
| 280 |
+
if "wikipedia" in question.lower() or "wiki" in question.lower():
|
| 281 |
+
return "wikipedia_search"
|
| 282 |
+
# Add more rules as needed
|
| 283 |
+
return "web_search"
|
| 284 |
+
|
| 285 |
class BasicAgent:
|
| 286 |
def __init__(self):
|
| 287 |
print("BasicAgent initialized.")
|
| 288 |
|
| 289 |
def __call__(self, question: str) -> str:
|
| 290 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 291 |
+
import re
|
| 292 |
+
|
| 293 |
+
tool_name = select_tool(question)
|
| 294 |
+
tool = TOOL_REGISTRY.get(tool_name, web_search)
|
| 295 |
+
# For other tools, pass the question or relevant part
|
| 296 |
+
if tool_name == "wikipedia_search":
|
| 297 |
+
cleaned = question.lower().replace("wikipedia", "").replace("wiki", "").strip()
|
| 298 |
+
return get_one_word_answer(tool(cleaned if cleaned else question))
|
| 299 |
+
if tool_name == "calculator":
|
| 300 |
+
return get_one_word_answer(tool(question))
|
| 301 |
+
if tool_name == "current_datetime":
|
| 302 |
+
return get_one_word_answer(tool())
|
| 303 |
+
if tool_name == "scraper":
|
| 304 |
+
return get_one_word_answer(tool(question))
|
| 305 |
+
if tool_name == "site_search":
|
| 306 |
+
# Example: expects "site:example.com query"
|
| 307 |
+
parts = question.split("site:")
|
| 308 |
+
if len(parts) == 2:
|
| 309 |
+
site = parts[1].split()[0]
|
| 310 |
+
query = parts[1][len(site):].strip()
|
| 311 |
+
return get_one_word_answer(tool(query, site))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
else:
|
| 313 |
+
return "No site specified."
|
| 314 |
+
# Default: web_search
|
| 315 |
+
result = tool(question)
|
| 316 |
+
return get_one_word_answer(result)
|
|
|
|
| 317 |
|
| 318 |
+
# ...existing code...
|
| 319 |
|
| 320 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 321 |
"""
|
pyproject.toml
CHANGED
|
@@ -5,13 +5,18 @@ description = "Add your description here"
|
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.11"
|
| 7 |
dependencies = [
|
|
|
|
| 8 |
"dotenv>=0.9.9",
|
| 9 |
"firecrawl-py>=2.12.0",
|
|
|
|
| 10 |
"gradio>=5.35.0",
|
| 11 |
"huggingface-hub>=0.33.1",
|
| 12 |
"langchain>=0.3.26",
|
| 13 |
"langchain-community>=0.3.26",
|
| 14 |
"requests>=2.32.4",
|
| 15 |
"ruff>=0.12.1",
|
|
|
|
|
|
|
|
|
|
| 16 |
"wikipedia>=1.4.0",
|
| 17 |
]
|
|
|
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.11"
|
| 7 |
dependencies = [
|
| 8 |
+
"docling>=2.39.0",
|
| 9 |
"dotenv>=0.9.9",
|
| 10 |
"firecrawl-py>=2.12.0",
|
| 11 |
+
"google>=3.0.0",
|
| 12 |
"gradio>=5.35.0",
|
| 13 |
"huggingface-hub>=0.33.1",
|
| 14 |
"langchain>=0.3.26",
|
| 15 |
"langchain-community>=0.3.26",
|
| 16 |
"requests>=2.32.4",
|
| 17 |
"ruff>=0.12.1",
|
| 18 |
+
"sentence-transformers>=4.1.0",
|
| 19 |
+
"smolagents>=1.19.0",
|
| 20 |
+
"torch>=2.7.1",
|
| 21 |
"wikipedia>=1.4.0",
|
| 22 |
]
|
requirements.txt
CHANGED
|
@@ -5,3 +5,9 @@ dotenv
|
|
| 5 |
langchain_community
|
| 6 |
firecrawl_py
|
| 7 |
wikipedia
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
langchain_community
|
| 6 |
firecrawl_py
|
| 7 |
wikipedia
|
| 8 |
+
torch
|
| 9 |
+
transformers
|
| 10 |
+
sentence_transformers
|
| 11 |
+
docling
|
| 12 |
+
smolagents
|
| 13 |
+
google
|
uv.lock
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|