ekabaruh commited on
Commit
71fa338
·
verified ·
1 Parent(s): 1d6f0e7

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +17 -68
agent.py CHANGED
@@ -2,100 +2,50 @@ import os
2
  from dotenv import load_dotenv
3
  from typing import List, Dict, Any, Optional
4
  import tempfile
5
- import requests
6
- from urllib.parse import urlparse
7
  import pandas as pd
8
  import numpy as np
9
 
10
  """Langraph"""
11
  from langgraph.graph import START, StateGraph, MessagesState
12
- from langchain_community.tools import DuckDuckGoSearchResults
13
- from langchain_community.document_loaders import WikipediaLoader
14
- from langchain_community.document_loaders import ArxivLoader
15
  from langgraph.prebuilt import ToolNode, tools_condition
16
  from langchain_google_genai import ChatGoogleGenerativeAI
17
  from langchain_groq import ChatGroq
18
  from langchain_huggingface import (
19
  ChatHuggingFace,
20
  HuggingFaceEndpoint,
21
- HuggingFaceEmbeddings,
22
  )
23
- from langchain_community.vectorstores import SupabaseVectorStore
24
  from langchain_core.messages import SystemMessage, HumanMessage
25
  from langchain_core.tools import tool
26
- from langchain.tools.retriever import create_retriever_tool
27
- from supabase.client import Client, create_client
28
  from langchain_openai import ChatOpenAI
 
29
 
30
  load_dotenv()
31
 
32
  ### =============== SEARCH TOOLS =============== ###
33
 
34
  @tool
35
- def web_search(query: str) -> str:
36
- """Search DuckDuckGo for a query and return maximum 3 results.
37
  Args:
38
  query: The search query."""
39
  try:
40
- search_results = DuckDuckGoSearchResults(max_results=3).invoke(query=query)
41
- # DuckDuckGo returns results as a string, so we need to parse it
42
- # The format is typically [snippet: text, title: title, link: url]
43
- formatted_results = []
44
 
45
- # Remove outer quotes if present and format properly
46
- if isinstance(search_results, str):
47
- # Simple parsing of the DuckDuckGo result format
48
- result_entries = search_results.split('], [')
49
- for entry in result_entries:
50
- # Clean up the entry
51
- entry = entry.replace('[', '').replace(']', '').strip()
52
- if entry:
53
- # Extract components
54
- parts = {}
55
- for part in entry.split(', '):
56
- if ': ' in part:
57
- key, value = part.split(': ', 1)
58
- parts[key] = value
59
-
60
- # Format as document
61
- if 'snippet' in parts and 'link' in parts:
62
- doc_content = parts.get('snippet', '')
63
- doc_source = parts.get('link', '')
64
- formatted_results.append(
65
- f'<Document source="{doc_source}" page=""/>\n{doc_content}\n</Document>'
66
- )
67
 
68
- if not formatted_results:
69
- return {"web_results": "No results found for the query. Try using wikipedia_search instead."}
70
 
71
- return {"web_results": "\n\n---\n\n".join(formatted_results)}
72
- except Exception as e:
73
- return {"web_results": f"Error performing web search: {str(e)}. Try using wikipedia_search instead."}
74
-
75
- @tool
76
- def wikipedia_search(query: str) -> str:
77
- """Search Wikipedia for a query.
78
- Args:
79
- query: The search query."""
80
- try:
81
- # Use WikipediaLoader which works better in restricted environments
82
- docs = WikipediaLoader(query=query, load_max_docs=2).load()
83
-
84
- if not docs:
85
- return {"wikipedia_results": "No Wikipedia results found for the query."}
86
-
87
- formatted_results = []
88
- for doc in docs:
89
- title = doc.metadata.get('title', 'Unknown Title')
90
- source = doc.metadata.get('source', 'Wikipedia')
91
- content = doc.page_content[:1000] + "..." if len(doc.page_content) > 1000 else doc.page_content
92
- formatted_results.append(
93
- f'<Document source="{source}" title="{title}">\n{content}\n</Document>'
94
- )
95
 
96
- return {"wikipedia_results": "\n\n---\n\n".join(formatted_results)}
97
  except Exception as e:
98
- return {"wikipedia_results": f"Error searching Wikipedia: {str(e)}."}
99
 
100
  ### =============== DOCUMENT PROCESSING TOOLS =============== ###
101
  # File handling still requires external tools
@@ -130,8 +80,7 @@ print(system_prompt)
130
  sys_msg = SystemMessage(content=system_prompt)
131
 
132
  tools = [
133
- web_search,
134
- wikipedia_search,
135
  save_and_read_file,
136
  ]
137
 
@@ -141,7 +90,7 @@ def build_graph(provider: str = "openai"):
141
  """Build the graph"""
142
  # Load environment variables from .env file
143
  if provider == "openai":
144
- llm = ChatOpenAI(model="gpt-4.1", temperature=0)
145
  elif provider == "groq":
146
  llm = ChatGroq(model="qwen-qwq-32b", temperature=0)
147
  elif provider == "huggingface":
 
2
  from dotenv import load_dotenv
3
  from typing import List, Dict, Any, Optional
4
  import tempfile
 
 
5
  import pandas as pd
6
  import numpy as np
7
 
8
  """Langraph"""
9
  from langgraph.graph import START, StateGraph, MessagesState
 
 
 
10
  from langgraph.prebuilt import ToolNode, tools_condition
11
  from langchain_google_genai import ChatGoogleGenerativeAI
12
  from langchain_groq import ChatGroq
13
  from langchain_huggingface import (
14
  ChatHuggingFace,
15
  HuggingFaceEndpoint,
 
16
  )
 
17
  from langchain_core.messages import SystemMessage, HumanMessage
18
  from langchain_core.tools import tool
 
 
19
  from langchain_openai import ChatOpenAI
20
+ from langchain_community.utilities import SerpAPIWrapper
21
 
22
  load_dotenv()
23
 
24
  ### =============== SEARCH TOOLS =============== ###
25
 
26
  @tool
27
+ def serpapi_search(query: str) -> str:
28
+ """Search the web using SerpAPI.
29
  Args:
30
  query: The search query."""
31
  try:
32
+ # Get API key from environment variable
33
+ api_key = os.getenv("SERPAPI_API_KEY")
34
+ if not api_key:
35
+ return {"search_results": "Error: SERPAPI_API_KEY not found in environment variables."}
36
 
37
+ # Initialize SerpAPIWrapper with the API key
38
+ search = SerpAPIWrapper(serpapi_api_key=api_key)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ # Perform the search
41
+ results = search.run(query)
42
 
43
+ if not results or results.strip() == "":
44
+ return {"search_results": "No search results found."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ return {"search_results": results}
47
  except Exception as e:
48
+ return {"search_results": f"Error performing search: {str(e)}"}
49
 
50
  ### =============== DOCUMENT PROCESSING TOOLS =============== ###
51
  # File handling still requires external tools
 
80
  sys_msg = SystemMessage(content=system_prompt)
81
 
82
  tools = [
83
+ serpapi_search,
 
84
  save_and_read_file,
85
  ]
86
 
 
90
  """Build the graph"""
91
  # Load environment variables from .env file
92
  if provider == "openai":
93
+ llm = ChatOpenAI(model="gpt-4o", temperature=0)
94
  elif provider == "groq":
95
  llm = ChatGroq(model="qwen-qwq-32b", temperature=0)
96
  elif provider == "huggingface":