Spaces:
Build error
Build error
Initial Repo
Browse files- README.md +1 -1
- agent.py +419 -0
- app.py +196 -0
- requirements.txt +0 -0
- test_agent.py +69 -0
- tests/test_base.py +21 -0
- tests/test_calculator.py +31 -0
- tests/test_search.py +35 -0
README.md
CHANGED
|
@@ -10,4 +10,4 @@ pinned: false
|
|
| 10 |
license: apache-2.0
|
| 11 |
---
|
| 12 |
|
| 13 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 10 |
license: apache-2.0
|
| 11 |
---
|
| 12 |
|
| 13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
agent.py
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import json
|
| 4 |
+
import arxiv
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
from duckduckgo_search import DDGS
|
| 9 |
+
from brave import Brave
|
| 10 |
+
|
| 11 |
+
from langchain_groq import ChatGroq
|
| 12 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 13 |
+
from langchain_mistralai.chat_models import ChatMistralAI
|
| 14 |
+
from langchain_core.tools import tool
|
| 15 |
+
from langchain_core.messages import SystemMessage, AIMessage
|
| 16 |
+
from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
|
| 17 |
+
|
| 18 |
+
from langgraph.graph import StateGraph, MessagesState, START
|
| 19 |
+
from langgraph.prebuilt import tools_condition, ToolNode
|
| 20 |
+
|
| 21 |
+
load_dotenv()
|
| 22 |
+
logging.basicConfig(
|
| 23 |
+
level=logging.INFO,
|
| 24 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 25 |
+
datefmt="%H:%M:%S"
|
| 26 |
+
)
|
| 27 |
+
logger = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# ------ ARITHMATIC TOOLS ------
|
| 31 |
+
@tool
|
| 32 |
+
def add(a: int, b: int) -> int:
|
| 33 |
+
"""Add two integers."""
|
| 34 |
+
return a + b
|
| 35 |
+
|
| 36 |
+
@tool
|
| 37 |
+
def subtract(a: int, b: int) -> int:
|
| 38 |
+
"""Subtract two integers."""
|
| 39 |
+
return a - b
|
| 40 |
+
|
| 41 |
+
@tool
|
| 42 |
+
def divide(a: int, b: int) -> int:
|
| 43 |
+
"""Divide two integers."""
|
| 44 |
+
if b == 0:
|
| 45 |
+
raise ValueError("Cannot divide by zero.")
|
| 46 |
+
return a / b
|
| 47 |
+
|
| 48 |
+
@tool
|
| 49 |
+
def multiply(a: int, b: int) -> int:
|
| 50 |
+
"""Multiply two integers."""
|
| 51 |
+
return a * b
|
| 52 |
+
|
| 53 |
+
@tool
|
| 54 |
+
def modulus(a: int, b: int) -> int:
|
| 55 |
+
"""Modulus two integers."""
|
| 56 |
+
return a % b
|
| 57 |
+
|
| 58 |
+
# --- SEARCH TOOLS ---
|
| 59 |
+
@tool
|
| 60 |
+
def wikipedia_search(query: str) -> str:
|
| 61 |
+
"""Search Wikipedia and return summaries of the top 3 articles."""
|
| 62 |
+
try:
|
| 63 |
+
docs = WikipediaLoader(query=query, load_max_docs=3).load()
|
| 64 |
+
if not docs:
|
| 65 |
+
return "<Document>Error: No Wikipedia results found.</Document>"
|
| 66 |
+
formatted = "\n\n---\n\n".join(
|
| 67 |
+
f"<Document source='{doc.metadata.get('source', 'unknown')}'>\n{doc.page_content.strip()}\n</Document>"
|
| 68 |
+
for doc in docs
|
| 69 |
+
)
|
| 70 |
+
return formatted
|
| 71 |
+
except Exception as e:
|
| 72 |
+
logger.error(f"Wikipedia tool failed: {e}")
|
| 73 |
+
return f"<Document>Error: Wikipedia search failed — {e}</Document>"
|
| 74 |
+
|
| 75 |
+
@tool
|
| 76 |
+
def arxiv_search(query: str) -> str:
|
| 77 |
+
"""Search Arxiv and return summaries of the top 3 results."""
|
| 78 |
+
try:
|
| 79 |
+
client = arxiv.Client()
|
| 80 |
+
search = arxiv.Search(
|
| 81 |
+
query=query,
|
| 82 |
+
max_results=3,
|
| 83 |
+
sort_by=arxiv.SortCriterion.Relevance
|
| 84 |
+
)
|
| 85 |
+
results = list(client.results(search))
|
| 86 |
+
if not results:
|
| 87 |
+
return "<Document>Error: No arXiv results found.</Document>"
|
| 88 |
+
formatted = "\n\n---\n\n".join(
|
| 89 |
+
f"<Document source='{result.entry_id}'>\nTitle: {result.title.strip()}\nSummary: {result.summary.strip()}\n</Document>"
|
| 90 |
+
for result in results
|
| 91 |
+
)
|
| 92 |
+
return formatted
|
| 93 |
+
except Exception as e:
|
| 94 |
+
logger.error(f"Arxiv tool failed: {e}")
|
| 95 |
+
return f"<Document>Error: arXiv search failed — {e}</Document>"
|
| 96 |
+
|
| 97 |
+
# --- WEB SEARCH TOOLS ---
|
| 98 |
+
def _perform_brave_search_attempt(query: str, api_key: str) -> str | None:
|
| 99 |
+
"""
|
| 100 |
+
Performs one Brave Search (raw) attempt.
|
| 101 |
+
Returns:
|
| 102 |
+
- formatted results string on success,
|
| 103 |
+
- critical-error string if library missing,
|
| 104 |
+
- None on retryable failure or no results.
|
| 105 |
+
"""
|
| 106 |
+
local_logger = logging.getLogger(f"{__name__}._perform_brave_search_attempt")
|
| 107 |
+
try:
|
| 108 |
+
client = Brave(api_key=api_key)
|
| 109 |
+
raw = client.search(q=query, count=3, raw=True) or {}
|
| 110 |
+
# Extract hits from raw JSON
|
| 111 |
+
hits = (
|
| 112 |
+
raw.get("web", {}).get("results")
|
| 113 |
+
or raw.get("results")
|
| 114 |
+
or []
|
| 115 |
+
)
|
| 116 |
+
# Build <Document> entries
|
| 117 |
+
docs = []
|
| 118 |
+
for h in hits:
|
| 119 |
+
if not isinstance(h, dict):
|
| 120 |
+
continue
|
| 121 |
+
url = h.get("url")
|
| 122 |
+
if not url:
|
| 123 |
+
continue
|
| 124 |
+
title = h.get("title", "No Title")
|
| 125 |
+
snippet = h.get("description", h.get("snippet", ""))
|
| 126 |
+
docs.append(
|
| 127 |
+
f"<Document source='{url}'>\n"
|
| 128 |
+
f"Title: {title}\n"
|
| 129 |
+
f"{snippet}\n"
|
| 130 |
+
f"</Document>"
|
| 131 |
+
)
|
| 132 |
+
if docs:
|
| 133 |
+
return "\n\n---\n\n".join(docs)
|
| 134 |
+
local_logger.warning("Brave Search returned no usable results.")
|
| 135 |
+
return None
|
| 136 |
+
except ImportError:
|
| 137 |
+
local_logger.error("Brave Search library not installed.")
|
| 138 |
+
return "<Document>Error: Brave Search library not installed. Cannot perform search.</Document>"
|
| 139 |
+
except Exception as e:
|
| 140 |
+
local_logger.exception("Brave Search attempt failed")
|
| 141 |
+
return None # Retryable
|
| 142 |
+
|
| 143 |
+
def _perform_duckduckgo_search(query: str) -> str:
|
| 144 |
+
"""
|
| 145 |
+
Performs up to 2 DDG searches as fallback.
|
| 146 |
+
Returns formatted results or an error <Document>.
|
| 147 |
+
"""
|
| 148 |
+
local_logger = logging.getLogger(f"{__name__}._perform_duckduckgo_search")
|
| 149 |
+
headers = {"Accept-Encoding": "gzip, deflate, br"}
|
| 150 |
+
try:
|
| 151 |
+
with DDGS(headers=headers, timeout=30) as ddgs:
|
| 152 |
+
for attempt in range(1, 3):
|
| 153 |
+
local_logger.info(f"DDG attempt {attempt} for '{query}'")
|
| 154 |
+
try:
|
| 155 |
+
results = ddgs.text(query, max_results=3) or []
|
| 156 |
+
except Exception as e:
|
| 157 |
+
local_logger.warning(f"DDG error on attempt {attempt}: {e}")
|
| 158 |
+
results = []
|
| 159 |
+
if results:
|
| 160 |
+
docs = []
|
| 161 |
+
for r in results:
|
| 162 |
+
href = r.get("href")
|
| 163 |
+
if not href:
|
| 164 |
+
continue
|
| 165 |
+
title = r.get("title", "No Title")
|
| 166 |
+
body = r.get("body", "")
|
| 167 |
+
docs.append(
|
| 168 |
+
f"<Document source='{href}'>\n"
|
| 169 |
+
f"Title: {title}\n"
|
| 170 |
+
f"{body}\n"
|
| 171 |
+
f"</Document>"
|
| 172 |
+
)
|
| 173 |
+
if docs:
|
| 174 |
+
return "\n\n---\n\n".join(docs)
|
| 175 |
+
local_logger.warning("DDG returned no docs with URLs.")
|
| 176 |
+
# back-off before next try
|
| 177 |
+
time.sleep(7 * attempt)
|
| 178 |
+
return "<Document>Error: All web search attempts (including fallback) failed to find results.</Document>"
|
| 179 |
+
except Exception as e:
|
| 180 |
+
local_logger.exception("DuckDuckGo fallback search failed catastrophically")
|
| 181 |
+
return f"<Document>Error: DuckDuckGo fallback search failed — {type(e).__name__}: {e}</Document>"
|
| 182 |
+
|
| 183 |
+
@tool
|
| 184 |
+
def web_search(query: str) -> str:
|
| 185 |
+
"""
|
| 186 |
+
Searches the web and returns top-3 search results formatted as <Document> blocks.
|
| 187 |
+
"""
|
| 188 |
+
main_logger = logging.getLogger(__name__ + ".web_search")
|
| 189 |
+
api_key = os.getenv("BRAVE_API_KEY")
|
| 190 |
+
|
| 191 |
+
if api_key:
|
| 192 |
+
main_logger.info(f"Trying Brave Search for '{query}'")
|
| 193 |
+
for attempt in range(1, 3):
|
| 194 |
+
res = _perform_brave_search_attempt(query, api_key)
|
| 195 |
+
if res:
|
| 196 |
+
if res.startswith("<Document>Error: Brave Search library not installed"):
|
| 197 |
+
main_logger.error("Brave library missing; skipping to fallback.")
|
| 198 |
+
break
|
| 199 |
+
main_logger.info("Brave Search succeeded.")
|
| 200 |
+
return res
|
| 201 |
+
main_logger.warning(f"Brave attempt {attempt} failed; retrying...")
|
| 202 |
+
time.sleep(3)
|
| 203 |
+
main_logger.warning("Brave Search failed; falling back.")
|
| 204 |
+
else:
|
| 205 |
+
main_logger.warning("No BRAVE_API_KEY; skipping Brave Search.")
|
| 206 |
+
|
| 207 |
+
main_logger.info(f"Using DuckDuckGo fallback for '{query}'")
|
| 208 |
+
return _perform_duckduckgo_search(query)
|
| 209 |
+
|
| 210 |
+
tools = [
|
| 211 |
+
add,
|
| 212 |
+
subtract,
|
| 213 |
+
divide,
|
| 214 |
+
multiply,
|
| 215 |
+
modulus,
|
| 216 |
+
wikipedia_search,
|
| 217 |
+
arxiv_search,
|
| 218 |
+
web_search,
|
| 219 |
+
]
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# ------ Build the graph ------
|
| 223 |
+
def build_graph(test_mode=False, system_prompt=None, model_backend="gemini"):
|
| 224 |
+
"""Builds the state graph for the agent with fallback model support."""
|
| 225 |
+
|
| 226 |
+
# ------ Model Selector ------
|
| 227 |
+
if model_backend == "groq":
|
| 228 |
+
model_name = "llama3-70b-8192" if test_mode else "qwen-qwq-32b"
|
| 229 |
+
llm = ChatGroq(model=model_name, temperature=0.1, max_tokens=8192)
|
| 230 |
+
elif model_backend == "mistral":
|
| 231 |
+
model_name = "mistral-small-latest"
|
| 232 |
+
llm = ChatMistralAI(model=model_name, temperature=0.1, max_tokens=8192)
|
| 233 |
+
elif model_backend == "gemini":
|
| 234 |
+
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0.1) # gemini-2.5-flash-preview-04-17 # gemini-2.0-flash
|
| 235 |
+
else:
|
| 236 |
+
raise ValueError(f"Unsupported model backend: {model_backend}")
|
| 237 |
+
llm_with_tools = llm.bind_tools(tools)
|
| 238 |
+
|
| 239 |
+
sys_msg = SystemMessage(content=system_prompt or """
|
| 240 |
+
You are a precise and helpful agent that uses tools.
|
| 241 |
+
|
| 242 |
+
Key Instructions:
|
| 243 |
+
1. Use tools for calculations and information retrieval (web, Wikipedia, ArXiv). Do NOT answer from internal knowledge for these tasks.
|
| 244 |
+
2. Use ONLY the specified tool parameters (e.g., `a`, `b` for arithmetic; `query` for search).
|
| 245 |
+
3. If a search tool (`wikipedia_search`, `arxiv_search`, `web_search`) returns `<Document>...</Document>` content (including errors in this format), your FINAL response to the user MUST BE the verbatim content from the tool, including all `<Document>` tags and their full content.
|
| 246 |
+
4. For multi-step calculations, call tools sequentially. Use the output of one tool call as input for the next. Your FINAL answer for calculations MUST BE ONLY THE NUMERICAL RESULT after all steps are complete.
|
| 247 |
+
|
| 248 |
+
Examples:
|
| 249 |
+
|
| 250 |
+
---
|
| 251 |
+
Example 1: Single Step Calculation
|
| 252 |
+
User: What is 15 divided by 3?
|
| 253 |
+
|
| 254 |
+
Tool Call:
|
| 255 |
+
```json
|
| 256 |
+
{
|
| 257 |
+
"tool_name": "divide",
|
| 258 |
+
"parameters": {
|
| 259 |
+
"a": 15,
|
| 260 |
+
"b": 3
|
| 261 |
+
}
|
| 262 |
+
}
|
| 263 |
+
```
|
| 264 |
+
Tool Output:
|
| 265 |
+
```
|
| 266 |
+
5
|
| 267 |
+
```
|
| 268 |
+
Final Answer: 15 divided by 3 is 5
|
| 269 |
+
---
|
| 270 |
+
Example 2: Multi-Step Calculation
|
| 271 |
+
User: What is (5 plus 3) then multiplied by 2?
|
| 272 |
+
|
| 273 |
+
Tool Call: # First operation
|
| 274 |
+
```json
|
| 275 |
+
{
|
| 276 |
+
"tool_name": "add",
|
| 277 |
+
"parameters": {
|
| 278 |
+
"a": 5,
|
| 279 |
+
"b": 3
|
| 280 |
+
}
|
| 281 |
+
}
|
| 282 |
+
```
|
| 283 |
+
Tool Output: # Result of the first operation
|
| 284 |
+
```# 8
|
| 285 |
+
```
|
| 286 |
+
|
| 287 |
+
# Given the previous output '8', the next operation is 8 * 2.
|
| 288 |
+
Tool Call: # Second operation, using previous output
|
| 289 |
+
```json
|
| 290 |
+
{
|
| 291 |
+
"tool_name": "multiply",
|
| 292 |
+
"parameters": {
|
| 293 |
+
"a": 8, # Output from the 'add' tool
|
| 294 |
+
"b": 2
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
```
|
| 298 |
+
Tool Output: # Result of the second operation
|
| 299 |
+
```
|
| 300 |
+
16
|
| 301 |
+
```
|
| 302 |
+
Final Answer: 16 # Only the final numerical result
|
| 303 |
+
---
|
| 304 |
+
Example 3: Information Retrieval
|
| 305 |
+
User: Tell me about the Eiffel tower
|
| 306 |
+
|
| 307 |
+
# Assistant's intended action: Call wikipedia_search
|
| 308 |
+
# Assistant's response if it were to put JSON in content (which your code handles):
|
| 309 |
+
```json
|
| 310 |
+
{
|
| 311 |
+
"tool_name": "wikipedia_search",
|
| 312 |
+
"parameters": {
|
| 313 |
+
"query": "Eiffel Tower"
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
```
|
| 317 |
+
|
| 318 |
+
# Correct Final Answer (after tool execution and if assistant is responding correctly):
|
| 319 |
+
<Document source='https://en.wikipedia.org/wiki/Eiffel_Tower'>
|
| 320 |
+
Title: Eiffel Tower
|
| 321 |
+
The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France.
|
| 322 |
+
</Document>
|
| 323 |
+
---
|
| 324 |
+
<Document source='https://en.wikipedia.org/wiki/Eiffel_Tower_in_popular_culture'>
|
| 325 |
+
Title: Eiffel Tower in popular culture
|
| 326 |
+
The Eiffel Tower has been the subject of numerous references in popular culture.
|
| 327 |
+
</Document>
|
| 328 |
+
---
|
| 329 |
+
""")
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
# ------ Define decision node ------
|
| 333 |
+
def decision_node(state: MessagesState) -> dict:
|
| 334 |
+
"""Decides which tool to use based on the task or parses content if needed."""
|
| 335 |
+
logger.info("Deciding which tool to use...")
|
| 336 |
+
response: AIMessage = llm_with_tools.invoke([sys_msg] + state["messages"])
|
| 337 |
+
|
| 338 |
+
logger.info(f"LLM raw response object: {response!r}")
|
| 339 |
+
logger.info(f"LLM response content: '{response.content}'")
|
| 340 |
+
|
| 341 |
+
parsed_tool_calls: List[Dict[str, Any]] = []
|
| 342 |
+
|
| 343 |
+
if response.tool_calls:
|
| 344 |
+
logger.info(f"LLM response tool_calls (native): {response.tool_calls}")
|
| 345 |
+
for tc in response.tool_calls:
|
| 346 |
+
parsed_tool_calls.append({"name": tc["name"], "args": tc["args"], "id": tc.get("id")})
|
| 347 |
+
|
| 348 |
+
# Only attempt if native tool_calls is empty AND content seems like a JSON block (Gemini workaround)
|
| 349 |
+
elif not response.tool_calls and isinstance(response.content, str) and \
|
| 350 |
+
response.content.strip().startswith("```json") and response.content.strip().endswith("```"):
|
| 351 |
+
|
| 352 |
+
logger.warning("Native tool_calls empty, attempting to parse JSON from content for Gemini-like behavior.")
|
| 353 |
+
content_str = response.content.strip()
|
| 354 |
+
# Strip the ```json and ``` markers
|
| 355 |
+
json_str = content_str[len("```json"): -len("```")].strip()
|
| 356 |
+
|
| 357 |
+
try:
|
| 358 |
+
# The JSON might be a single tool call object or a list of them
|
| 359 |
+
parsed_json_content = json.loads(json_str)
|
| 360 |
+
|
| 361 |
+
# Standardize to a list of tool call like dicts
|
| 362 |
+
tool_requests_from_content = []
|
| 363 |
+
if isinstance(parsed_json_content, dict): # Single tool call
|
| 364 |
+
tool_requests_from_content.append(parsed_json_content)
|
| 365 |
+
elif isinstance(parsed_json_content, list): # List of tool calls (less common for this workaround)
|
| 366 |
+
tool_requests_from_content.extend(parsed_json_content)
|
| 367 |
+
|
| 368 |
+
for tool_data in tool_requests_from_content:
|
| 369 |
+
if "tool_name" in tool_data and "parameters" in tool_data:
|
| 370 |
+
# Convert to the format Langchain expects for AIMessage.tool_calls
|
| 371 |
+
tool_call_id = tool_data.get("id", f"call_json_content_{os.urandom(4).hex()}")
|
| 372 |
+
parsed_tool_calls.append({
|
| 373 |
+
"name": tool_data["tool_name"],
|
| 374 |
+
"args": tool_data["parameters"], # Langchain expects 'args'
|
| 375 |
+
"id": tool_call_id
|
| 376 |
+
})
|
| 377 |
+
logger.info(f"Successfully parsed tool call from content: {tool_data['tool_name']}")
|
| 378 |
+
else:
|
| 379 |
+
logger.warning(f"Parsed JSON from content does not match expected tool call structure: {tool_data}")
|
| 380 |
+
|
| 381 |
+
if parsed_tool_calls:
|
| 382 |
+
# We create a new AIMessage with the parsed tool_calls.
|
| 383 |
+
response = AIMessage(
|
| 384 |
+
content="", # Clear content as it's now processed as a tool call
|
| 385 |
+
tool_calls=parsed_tool_calls,
|
| 386 |
+
id=response.id,
|
| 387 |
+
response_metadata=response.response_metadata,
|
| 388 |
+
usage_metadata=response.usage_metadata,
|
| 389 |
+
)
|
| 390 |
+
logger.info(f"Modified AIMessage with tool_calls parsed from content: {response.tool_calls}")
|
| 391 |
+
else:
|
| 392 |
+
logger.warning("Attempted to parse JSON from content, but no valid tool calls found.")
|
| 393 |
+
|
| 394 |
+
except json.JSONDecodeError as e:
|
| 395 |
+
logger.error(f"Failed to decode JSON from content: {e}. Content was: '{json_str}'")
|
| 396 |
+
except Exception as e:
|
| 397 |
+
logger.error(f"Unexpected error parsing tool call from content: {e}")
|
| 398 |
+
|
| 399 |
+
else: # No native tool_calls and content doesn't look like our target JSON block
|
| 400 |
+
logger.info(f"LLM response additional_kwargs: {response.additional_kwargs if hasattr(response, 'additional_kwargs') else 'N/A'}")
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
# Logging tool names based on successfully parsed tool_calls (either native or from content)
|
| 404 |
+
tool_names_to_log = [tc["name"] for tc in response.tool_calls] if response.tool_calls else []
|
| 405 |
+
if tool_names_to_log:
|
| 406 |
+
logger.info(f"Used tool(s) after parsing/checking: {', '.join(tool_names_to_log)}")
|
| 407 |
+
else:
|
| 408 |
+
logger.info("No tool used in this step (after parsing/checking).")
|
| 409 |
+
|
| 410 |
+
return {"messages": state["messages"] + [response]}
|
| 411 |
+
|
| 412 |
+
graph = StateGraph(MessagesState)
|
| 413 |
+
graph.add_node("decision_node", decision_node)
|
| 414 |
+
graph.add_node("tools", ToolNode(tools))
|
| 415 |
+
graph.add_edge(START, "decision_node")
|
| 416 |
+
graph.add_conditional_edges("decision_node", tools_condition)
|
| 417 |
+
graph.add_edge("tools", "decision_node")
|
| 418 |
+
|
| 419 |
+
return graph.compile()
|
app.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
import inspect
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
# (Keep Constants as is)
|
| 8 |
+
# --- Constants ---
|
| 9 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
+
|
| 11 |
+
# --- Basic Agent Definition ---
|
| 12 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
+
class BasicAgent:
|
| 14 |
+
def __init__(self):
|
| 15 |
+
print("BasicAgent initialized.")
|
| 16 |
+
def __call__(self, question: str) -> str:
|
| 17 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
+
fixed_answer = "This is a default answer."
|
| 19 |
+
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
+
return fixed_answer
|
| 21 |
+
|
| 22 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
+
"""
|
| 24 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 25 |
+
and displays the results.
|
| 26 |
+
"""
|
| 27 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 28 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 29 |
+
|
| 30 |
+
if profile:
|
| 31 |
+
username= f"{profile.username}"
|
| 32 |
+
print(f"User logged in: {username}")
|
| 33 |
+
else:
|
| 34 |
+
print("User not logged in.")
|
| 35 |
+
return "Please Login to Hugging Face with the button.", None
|
| 36 |
+
|
| 37 |
+
api_url = DEFAULT_API_URL
|
| 38 |
+
questions_url = f"{api_url}/questions"
|
| 39 |
+
submit_url = f"{api_url}/submit"
|
| 40 |
+
|
| 41 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
+
try:
|
| 43 |
+
agent = BasicAgent()
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Error instantiating agent: {e}")
|
| 46 |
+
return f"Error initializing agent: {e}", None
|
| 47 |
+
# 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)
|
| 48 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
+
print(agent_code)
|
| 50 |
+
|
| 51 |
+
# 2. Fetch Questions
|
| 52 |
+
print(f"Fetching questions from: {questions_url}")
|
| 53 |
+
try:
|
| 54 |
+
response = requests.get(questions_url, timeout=15)
|
| 55 |
+
response.raise_for_status()
|
| 56 |
+
questions_data = response.json()
|
| 57 |
+
if not questions_data:
|
| 58 |
+
print("Fetched questions list is empty.")
|
| 59 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 60 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 61 |
+
except requests.exceptions.RequestException as e:
|
| 62 |
+
print(f"Error fetching questions: {e}")
|
| 63 |
+
return f"Error fetching questions: {e}", None
|
| 64 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 65 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 66 |
+
print(f"Response text: {response.text[:500]}")
|
| 67 |
+
return f"Error decoding server response for questions: {e}", None
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 70 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 71 |
+
|
| 72 |
+
# 3. Run your Agent
|
| 73 |
+
results_log = []
|
| 74 |
+
answers_payload = []
|
| 75 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 76 |
+
for item in questions_data:
|
| 77 |
+
task_id = item.get("task_id")
|
| 78 |
+
question_text = item.get("question")
|
| 79 |
+
if not task_id or question_text is None:
|
| 80 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
+
continue
|
| 82 |
+
try:
|
| 83 |
+
submitted_answer = agent(question_text)
|
| 84 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 85 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 86 |
+
except Exception as e:
|
| 87 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 88 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 89 |
+
|
| 90 |
+
if not answers_payload:
|
| 91 |
+
print("Agent did not produce any answers to submit.")
|
| 92 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 93 |
+
|
| 94 |
+
# 4. Prepare Submission
|
| 95 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 96 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 97 |
+
print(status_update)
|
| 98 |
+
|
| 99 |
+
# 5. Submit
|
| 100 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 101 |
+
try:
|
| 102 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 103 |
+
response.raise_for_status()
|
| 104 |
+
result_data = response.json()
|
| 105 |
+
final_status = (
|
| 106 |
+
f"Submission Successful!\n"
|
| 107 |
+
f"User: {result_data.get('username')}\n"
|
| 108 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 109 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 110 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 111 |
+
)
|
| 112 |
+
print("Submission successful.")
|
| 113 |
+
results_df = pd.DataFrame(results_log)
|
| 114 |
+
return final_status, results_df
|
| 115 |
+
except requests.exceptions.HTTPError as e:
|
| 116 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 117 |
+
try:
|
| 118 |
+
error_json = e.response.json()
|
| 119 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 120 |
+
except requests.exceptions.JSONDecodeError:
|
| 121 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 122 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 123 |
+
print(status_message)
|
| 124 |
+
results_df = pd.DataFrame(results_log)
|
| 125 |
+
return status_message, results_df
|
| 126 |
+
except requests.exceptions.Timeout:
|
| 127 |
+
status_message = "Submission Failed: The request timed out."
|
| 128 |
+
print(status_message)
|
| 129 |
+
results_df = pd.DataFrame(results_log)
|
| 130 |
+
return status_message, results_df
|
| 131 |
+
except requests.exceptions.RequestException as e:
|
| 132 |
+
status_message = f"Submission Failed: Network error - {e}"
|
| 133 |
+
print(status_message)
|
| 134 |
+
results_df = pd.DataFrame(results_log)
|
| 135 |
+
return status_message, results_df
|
| 136 |
+
except Exception as e:
|
| 137 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 138 |
+
print(status_message)
|
| 139 |
+
results_df = pd.DataFrame(results_log)
|
| 140 |
+
return status_message, results_df
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# --- Build Gradio Interface using Blocks ---
|
| 144 |
+
with gr.Blocks() as demo:
|
| 145 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 146 |
+
gr.Markdown(
|
| 147 |
+
"""
|
| 148 |
+
**Instructions:**
|
| 149 |
+
|
| 150 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 151 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 152 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
+
|
| 154 |
+
---
|
| 155 |
+
**Disclaimers:**
|
| 156 |
+
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).
|
| 157 |
+
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.
|
| 158 |
+
"""
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
gr.LoginButton()
|
| 162 |
+
|
| 163 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
+
|
| 165 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 166 |
+
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
+
|
| 169 |
+
run_button.click(
|
| 170 |
+
fn=run_and_submit_all,
|
| 171 |
+
outputs=[status_output, results_table]
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 177 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
| 178 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 179 |
+
|
| 180 |
+
if space_host_startup:
|
| 181 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
+
else:
|
| 184 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
+
|
| 186 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 187 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 188 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 189 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 190 |
+
else:
|
| 191 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 192 |
+
|
| 193 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
+
|
| 195 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
+
demo.launch(debug=True, share=False)
|
requirements.txt
ADDED
|
Binary file (3.97 kB). View file
|
|
|
test_agent.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from agent import build_graph
|
| 3 |
+
from langchain_core.messages import HumanMessage
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class BaseLangGraphTest(unittest.TestCase):
|
| 7 |
+
"""Base test class for all agent unit-tests"""
|
| 8 |
+
# Base prompt (will be given a default prompt from the agent file if none)
|
| 9 |
+
system_prompt = None
|
| 10 |
+
|
| 11 |
+
@classmethod
|
| 12 |
+
def setUpClass(cls):
|
| 13 |
+
cls.graph = build_graph(test_mode=True, system_prompt=system_prompt_calculator)
|
| 14 |
+
|
| 15 |
+
def run_agent(self, query: str) -> str:
|
| 16 |
+
messages = [HumanMessage(content=query)]
|
| 17 |
+
result = self.graph.invoke({"messages": messages})
|
| 18 |
+
return result["messages"][-1].content.strip().lower()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TestLangGraphCalculator(BaseLangGraphTest):
|
| 22 |
+
"""Tests the calculation capabilities of the llm
|
| 23 |
+
by utilizing its pre-built tools"""
|
| 24 |
+
|
| 25 |
+
system_prompt = """You are a calculator assistant. Use the available tools to perform arithmetic.
|
| 26 |
+
Always use the correct parameter names: a and b. Never invent new parameter names.
|
| 27 |
+
Only respond to the user query by selecting the correct tool with appropriate inputs.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def test_combined_add_multiply(self):
|
| 31 |
+
response = self.run_agent("What is 5 plus 3 then multiplied by 2?")
|
| 32 |
+
self.assertIn("16", response)
|
| 33 |
+
|
| 34 |
+
def test_combined_subtract_modulus(self):
|
| 35 |
+
response = self.run_agent("What is (23 - 7) % 5")
|
| 36 |
+
self.assertIn("1", response)
|
| 37 |
+
|
| 38 |
+
def test_nested_expression(self):
|
| 39 |
+
response = self.run_agent("What is (4 plus 6)/2 * 3 modulus 4?")
|
| 40 |
+
self.assertIn("3", response)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class TestLangGraphSearch(BaseLangGraphTest):
|
| 44 |
+
"""Tests for search tools (wikipedia, arxiv, web)"""
|
| 45 |
+
|
| 46 |
+
system_prompt = """You are a searching assistant. Use the available tools to perform arithmetic.
|
| 47 |
+
Always use the correct parameter names! Never invent new parameter names.
|
| 48 |
+
Only respond to the user query by selecting the correct tool with appropriate inputs.
|
| 49 |
+
Follow the structured formatting when delivering the output.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def test_wikipedia_search(self):
|
| 53 |
+
response = self.run_agent("search wikipedia for Alan Turing")
|
| 54 |
+
self.assertIn("alan turing", response)
|
| 55 |
+
self.assertIn("<document", response)
|
| 56 |
+
|
| 57 |
+
def test_arxiv_search(self):
|
| 58 |
+
response = self.run_agent("Find arxiv papers on quantum computing")
|
| 59 |
+
self.assertIn("quantum", response)
|
| 60 |
+
self.assertIn("<document", response)
|
| 61 |
+
|
| 62 |
+
def test_web_search(self):
|
| 63 |
+
response = self.run_agent("Search the web for current news on AI safety")
|
| 64 |
+
self.assertIn("<document", response)
|
| 65 |
+
self.assertGreater(len(response), 50)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
unittest.main()
|
tests/test_base.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
| 4 |
+
|
| 5 |
+
import unittest
|
| 6 |
+
from agent import build_graph
|
| 7 |
+
from langchain_core.messages import HumanMessage
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class BaseLangGraphTest(unittest.TestCase):
|
| 11 |
+
"""Default to a weak but higher rate model for testing agentic tool usage."""
|
| 12 |
+
system_prompt = None
|
| 13 |
+
|
| 14 |
+
@classmethod
|
| 15 |
+
def setUpClass(cls):
|
| 16 |
+
cls.graph = build_graph(test_mode=True, system_prompt=cls.system_prompt)
|
| 17 |
+
|
| 18 |
+
def run_agent(self, query: str) -> str:
|
| 19 |
+
messages = [HumanMessage(content=query)]
|
| 20 |
+
result = self.graph.invoke({"messages": messages})
|
| 21 |
+
return result["messages"][-1].content.strip().lower()
|
tests/test_calculator.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import unittest
|
| 3 |
+
from test_base import BaseLangGraphTest
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestLangGraphCalculator(BaseLangGraphTest):
|
| 7 |
+
"""Tests the calculation capabilities of the llm
|
| 8 |
+
by utilizing its pre-built tools"""
|
| 9 |
+
|
| 10 |
+
# system_prompt = """You are a calculator assistant. Use the available tools to perform arithmetic.
|
| 11 |
+
# Always use the correct parameter names: a and b. Never invent new parameter names.
|
| 12 |
+
# Only respond to the user query by selecting the correct tool with appropriate inputs.
|
| 13 |
+
# """
|
| 14 |
+
def tearDown(self):
|
| 15 |
+
time.sleep(4)
|
| 16 |
+
|
| 17 |
+
def test_combined_add_multiply(self):
|
| 18 |
+
response = self.run_agent("What is 5 plus 3 then multiplied by 2?")
|
| 19 |
+
self.assertIn("16", response)
|
| 20 |
+
|
| 21 |
+
def test_combined_subtract_modulus(self):
|
| 22 |
+
response = self.run_agent("What is (23 - 7) % 5")
|
| 23 |
+
self.assertIn("1", response)
|
| 24 |
+
|
| 25 |
+
def test_nested_expression(self):
|
| 26 |
+
response = self.run_agent("What is (4 plus 6)/2 * 3 modulus 4?")
|
| 27 |
+
self.assertIn("3", response)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if __name__ == "__main__":
|
| 31 |
+
unittest.main()
|
tests/test_search.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
import unittest
|
| 3 |
+
from test_base import BaseLangGraphTest
|
| 4 |
+
|
| 5 |
+
class TestLangGraphSearch(BaseLangGraphTest):
|
| 6 |
+
"""Tests for search tools (wikipedia, arxiv, web)"""
|
| 7 |
+
|
| 8 |
+
# system_prompt = """You are a searching assistant. Use the available tools to perform arithmetic.
|
| 9 |
+
# Always use the correct parameter names! Never invent new parameter names.
|
| 10 |
+
# Only respond to the user query by selecting the correct tool with appropriate inputs.
|
| 11 |
+
# Follow the structured formatting when delivering the output.
|
| 12 |
+
# """
|
| 13 |
+
def tearDown(self):
|
| 14 |
+
time.sleep(2)
|
| 15 |
+
|
| 16 |
+
def test_wikipedia_search(self):
|
| 17 |
+
response = self.run_agent("search wikipedia for Alan Turing")
|
| 18 |
+
response_lower = response.lower()
|
| 19 |
+
self.assertIn("alan", response_lower)
|
| 20 |
+
self.assertIn("turing", response_lower)
|
| 21 |
+
self.assertIn("<document", response_lower)
|
| 22 |
+
|
| 23 |
+
def test_arxiv_search(self):
|
| 24 |
+
response = self.run_agent("Find arxiv papers on quantum computing")
|
| 25 |
+
response_lower = response.lower()
|
| 26 |
+
self.assertIn("quantum", response_lower)
|
| 27 |
+
self.assertIn("<document", response_lower)
|
| 28 |
+
|
| 29 |
+
def test_web_search(self):
|
| 30 |
+
response = self.run_agent("Search the web for current news on AI safety")
|
| 31 |
+
self.assertIn("<document", response.lower())
|
| 32 |
+
self.assertGreater(len(response), 50)
|
| 33 |
+
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
unittest.main()
|