mabelwang21 commited on
Commit
6e2fb37
·
1 Parent(s): d98d919

add read_jsonl, update websearch and calculate tools

Browse files
Files changed (1) hide show
  1. agent.py +51 -29
agent.py CHANGED
@@ -1,6 +1,7 @@
1
  import os
2
  import ast
3
  import re
 
4
  import operator as op
5
  from pathlib import Path
6
  from typing import List, TypedDict, Annotated, Optional
@@ -38,37 +39,51 @@ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma sepa
38
 
39
  @tool
40
  def calculate(expr: str) -> str:
41
- """Evaluate a simple math expression and return the result."""
42
- _OPERATORS = {
43
- ast.Add: op.add,
44
- ast.Sub: op.sub,
45
- ast.Mult: op.mul,
46
- ast.Div: op.truediv,
47
- ast.Pow: op.pow,
48
- ast.USub: op.neg,
49
- }
50
- def _eval(node):
51
- if isinstance(node, ast.Num):
52
- return node.n
53
- elif isinstance(node, ast.BinOp):
54
- return _OPERATORS[type(node.op)](_eval(node.left), _eval(node.right))
55
- elif isinstance(node, ast.UnaryOp):
56
- return _OPERATORS[type(node.op)](_eval(node.operand))
57
- else:
58
- raise ValueError(f"Unsupported expression: {ast.dump(node)}")
59
  try:
60
- parsed = ast.parse(expr, mode='eval').body
61
- result = _eval(parsed)
62
- return str(result)
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  except Exception as e:
64
  return f"Error calculating expression: {e}"
65
 
66
  @tool
67
  def web_search(query: str) -> str:
68
- """Search the web for current information using DuckDuckGo."""
69
  try:
70
  from langchain.utilities import DuckDuckGoSearchRun
71
- return DuckDuckGoSearchRun().run(query)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  except Exception as e:
73
  return f"Error performing web search: {e}"
74
 
@@ -150,18 +165,25 @@ def transcribe_audio(audio_path: str) -> str:
150
  return "\n".join(doc.page_content for doc in docs)
151
  except Exception as e:
152
  return f"Error transcribing audio: {e}"
153
-
154
-
155
- #o3_mini = init_chat_model("openai:o3-mini", temperature=0)
156
- #claude_sonnet = init_chat_model(anthropic:claude-3-5-sonnet-latest", temperature=0)
157
- #gemini_2_flash = init_chat_model("google_vertexai:gemini-2.0-flash", temperature=0)
158
 
159
 
 
 
 
 
 
 
 
 
 
 
 
160
 
 
161
  tools: List[StructuredTool] = [
162
  calculate, web_search, wikipedia_search, image_recognition,
163
  read_pdf, read_csv, read_spreadsheet, transcribe_audio,
164
- youtube_transcript_tool, youtube_transcript_api
165
  ]
166
 
167
  class AgentState(TypedDict):
 
1
  import os
2
  import ast
3
  import re
4
+ import json
5
  import operator as op
6
  from pathlib import Path
7
  from typing import List, TypedDict, Annotated, Optional
 
39
 
40
  @tool
41
  def calculate(expr: str) -> str:
42
+ """Evaluate a math expression. Supports basic operations (+,-,*,/,**) and functions (sin,cos,sqrt,etc)."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  try:
44
+ import math
45
+ # Create safe math namespace
46
+ safe_dict = {
47
+ k: v for k, v in math.__dict__.items()
48
+ if not k.startswith('_')
49
+ }
50
+ safe_dict.update({
51
+ 'abs': abs,
52
+ 'round': round,
53
+ 'max': max,
54
+ 'min': min
55
+ })
56
+
57
+ # Evaluate expression in safe environment
58
+ result = eval(expr, {"__builtins__": {}}, safe_dict)
59
+ return str(float(result))
60
  except Exception as e:
61
  return f"Error calculating expression: {e}"
62
 
63
  @tool
64
  def web_search(query: str) -> str:
65
+ """Search the web using DuckDuckGo and SerpAPI for comprehensive results."""
66
  try:
67
  from langchain.utilities import DuckDuckGoSearchRun
68
+ from langchain_community.utilities import SerpAPIWrapper
69
+
70
+ # Try multiple search engines
71
+ results = []
72
+
73
+ # DuckDuckGo search
74
+ ddg = DuckDuckGoSearchRun()
75
+ ddg_results = ddg.run(query)
76
+ results.append(ddg_results)
77
+
78
+ # SerpAPI search if API key available
79
+ if os.getenv("SERPAPI_API_KEY"):
80
+ serpapi = SerpAPIWrapper()
81
+ serp_results = serpapi.run(query)
82
+ results.append(serp_results)
83
+
84
+ # Combine and summarize results
85
+ combined_results = "\n\n".join(results)
86
+ return combined_results[:1000] # Limit length for better handling
87
  except Exception as e:
88
  return f"Error performing web search: {e}"
89
 
 
165
  return "\n".join(doc.page_content for doc in docs)
166
  except Exception as e:
167
  return f"Error transcribing audio: {e}"
 
 
 
 
 
168
 
169
 
170
+ @tool
171
+ def read_jsonl(jsonl_path: str) -> str:
172
+ """Read and extract data from a JSONL (JSON Lines) file."""
173
+ try:
174
+ data = []
175
+ with open(jsonl_path, 'r', encoding='utf-8') as file:
176
+ for line in file:
177
+ data.append(json.loads(line))
178
+ return json.dumps(data, indent=2)
179
+ except Exception as e:
180
+ return f"Error reading JSONL file: {e}"
181
 
182
+ # Update tools list
183
  tools: List[StructuredTool] = [
184
  calculate, web_search, wikipedia_search, image_recognition,
185
  read_pdf, read_csv, read_spreadsheet, transcribe_audio,
186
+ youtube_transcript_tool, youtube_transcript_api, read_jsonl # Add read_jsonl
187
  ]
188
 
189
  class AgentState(TypedDict):