LamiaYT commited on
Commit
15b5735
·
1 Parent(s): 22a9aed
Files changed (1) hide show
  1. app.py +73 -2
app.py CHANGED
@@ -34,24 +34,74 @@ def serper_search(query: str) -> str:
34
  return "Serper key missing, please set SERPER_API_KEY."
35
 
36
  # --- Other Tools (unchanged) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  @tool
38
  def wikipedia_search(query: str) -> str:
39
- """Search Wikipedia for a summary or search results."""
 
 
 
 
 
 
 
 
40
  try:
41
  url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
42
  r = requests.get(url, timeout=10)
43
  if r.status_code == 200:
44
  d = r.json()
45
  return f"{d.get('title')}\n{d.get('extract')}\n{d['content_urls']['desktop']['page']}"
46
- # fallback
47
  params = {"action": "query", "format": "json", "list": "search", "srsearch": query, "srlimit": 3}
48
  r = requests.get("https://en.wikipedia.org/w/api.php", params=params, timeout=10)
49
  return "\n\n".join(f"{i['title']}: {i['snippet']}" for i in r.json().get("query", {}).get("search", []))
50
  except Exception as e:
51
  return f"Wikipedia error: {e}"
52
 
 
53
  @tool
54
  def text_processor(text: str, operation: str = "analyze") -> str:
 
 
 
 
 
 
 
 
 
 
55
  if operation == "reverse":
56
  return text[::-1]
57
  if operation == "parse":
@@ -59,14 +109,35 @@ def text_processor(text: str, operation: str = "analyze") -> str:
59
  return f"Words: {len(words)}; First: {words[0] if words else ''}; Last: {words[-1] if words else ''}"
60
  return f"Length: {len(text)}, words: {len(text.split())}"
61
 
 
62
  @tool
63
  def math_solver(problem: str) -> str:
 
 
 
 
 
 
 
 
 
64
  if "commutative" in problem.lower():
65
  return "Check examples a*b vs b*a; look for counterexamples."
66
  return f"Need math analysis: {problem[:100]}..."
67
 
 
68
  @tool
69
  def data_extractor(source: str, target: str) -> str:
 
 
 
 
 
 
 
 
 
 
70
  if "botanical" in target.lower() and "vegetable" in source:
71
  items = [i.strip() for i in source.split(",")]
72
  true_veg = sorted(i for i in items if i.lower() in ["broccoli", "celery", "lettuce", "basil", "sweet potato"])
 
34
  return "Serper key missing, please set SERPER_API_KEY."
35
 
36
  # --- Other Tools (unchanged) ---
37
+ @tool
38
+ def serper_search(query: str) -> str:
39
+ """
40
+ Search the web using the Serper API to find current factual information.
41
+
42
+ Args:
43
+ query (str): The search query string.
44
+
45
+ Returns:
46
+ str: A formatted string of top search results, or an error message.
47
+ """
48
+ api_key = os.getenv("SERPER_API_KEY")
49
+ if api_key:
50
+ try:
51
+ url = "https://google.serper.dev/search"
52
+ payload = {"q": query, "num": 10}
53
+ headers = {'X-API-KEY': api_key}
54
+ r = requests.post(url, headers=headers, json=payload, timeout=15)
55
+ r.raise_for_status()
56
+ data = r.json()
57
+ snippets = []
58
+ if kg := data.get("knowledgeGraph"):
59
+ snippets.append(f"{kg.get('title')}: {kg.get('description')}")
60
+ for item in data.get("organic", [])[:5]:
61
+ snippets.append(f"{item.get('title')}\n{item.get('snippet')}\n{item.get('link')}")
62
+ return "\n\n".join(snippets) if snippets else "No results."
63
+ except Exception as e:
64
+ return f"Serper error: {e}"
65
+ else:
66
+ return "Serper key missing, please set SERPER_API_KEY."
67
+
68
+
69
  @tool
70
  def wikipedia_search(query: str) -> str:
71
+ """
72
+ Search Wikipedia for a summary or basic search results.
73
+
74
+ Args:
75
+ query (str): The search term to look up on Wikipedia.
76
+
77
+ Returns:
78
+ str: A summary of the topic or a list of search result snippets.
79
+ """
80
  try:
81
  url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + query.replace(" ", "_")
82
  r = requests.get(url, timeout=10)
83
  if r.status_code == 200:
84
  d = r.json()
85
  return f"{d.get('title')}\n{d.get('extract')}\n{d['content_urls']['desktop']['page']}"
 
86
  params = {"action": "query", "format": "json", "list": "search", "srsearch": query, "srlimit": 3}
87
  r = requests.get("https://en.wikipedia.org/w/api.php", params=params, timeout=10)
88
  return "\n\n".join(f"{i['title']}: {i['snippet']}" for i in r.json().get("query", {}).get("search", []))
89
  except Exception as e:
90
  return f"Wikipedia error: {e}"
91
 
92
+
93
  @tool
94
  def text_processor(text: str, operation: str = "analyze") -> str:
95
+ """
96
+ Perform a text operation like reversing or analyzing a string.
97
+
98
+ Args:
99
+ text (str): The input string to process.
100
+ operation (str): The operation to perform. Options: 'reverse', 'parse', 'analyze'.
101
+
102
+ Returns:
103
+ str: The result of the text processing.
104
+ """
105
  if operation == "reverse":
106
  return text[::-1]
107
  if operation == "parse":
 
109
  return f"Words: {len(words)}; First: {words[0] if words else ''}; Last: {words[-1] if words else ''}"
110
  return f"Length: {len(text)}, words: {len(text.split())}"
111
 
112
+
113
  @tool
114
  def math_solver(problem: str) -> str:
115
+ """
116
+ Solve or explain a math-related problem in natural language.
117
+
118
+ Args:
119
+ problem (str): A math question or prompt.
120
+
121
+ Returns:
122
+ str: An explanation or analysis related to the math topic.
123
+ """
124
  if "commutative" in problem.lower():
125
  return "Check examples a*b vs b*a; look for counterexamples."
126
  return f"Need math analysis: {problem[:100]}..."
127
 
128
+
129
  @tool
130
  def data_extractor(source: str, target: str) -> str:
131
+ """
132
+ Extract data elements from a text source based on the target keyword.
133
+
134
+ Args:
135
+ source (str): The raw input text to extract data from.
136
+ target (str): The type of data to extract (e.g., 'botanical vegetables').
137
+
138
+ Returns:
139
+ str: A filtered list or extracted segment from the input.
140
+ """
141
  if "botanical" in target.lower() and "vegetable" in source:
142
  items = [i.strip() for i in source.split(",")]
143
  true_veg = sorted(i for i in items if i.lower() in ["broccoli", "celery", "lettuce", "basil", "sweet potato"])