wt002 commited on
Commit
13e0c44
·
verified ·
1 Parent(s): bfc16ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -27
app.py CHANGED
@@ -8,7 +8,8 @@ import requests
8
  from typing import List, Dict, Union
9
  import pandas as pd
10
  import wikipediaapi
11
- from duckduckgo_search import ddg
 
12
 
13
  load_dotenv()
14
 
@@ -20,36 +21,81 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
20
  # --- Basic Agent Definition ---
21
 
22
  class BasicAgent:
23
- def __init__(self):
24
- print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
25
 
26
- def __call__(self, question: str) -> str:
27
- print(f"Agent received question: {question[:50]}...")
28
- answer = self.basic_search(question)
29
- print(f"Answer: {answer}")
30
- return answer
 
 
 
 
31
 
32
- def basic_search(self, query):
33
  try:
34
- # Get search results from DuckDuckGo
35
- results = ddg(query, max_results=3)
36
-
37
- # Format the results
38
- if not results:
39
- return "No results found"
40
-
41
- formatted_results = []
42
- for i, result in enumerate(results, 1):
43
- formatted_results.append(
44
- f"{i}. {result['title']}\n"
45
- f" {result['link']}\n"
46
- f" {result['body']}"
47
- )
48
-
49
- return "\n\n".join(formatted_results)
50
-
51
  except Exception as e:
52
- return f"Search error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
 
55
  def run_and_submit_all( profile: gr.OAuthProfile | None):
 
8
  from typing import List, Dict, Union
9
  import pandas as pd
10
  import wikipediaapi
11
+ from serpapi import GoogleSearch
12
+ from typing import List, Dict, Optional
13
 
14
  load_dotenv()
15
 
 
21
  # --- Basic Agent Definition ---
22
 
23
  class BasicAgent:
24
+ import os
25
+ from serpapi import GoogleSearch
26
+ from typing import List, Dict, Optional
27
+
28
+ class BasicAgent:
29
+ def __init__(self, api_key: str = None):
30
+ self.api_key = api_key or os.getenv("SERP_API_KEY")
31
+ if not self.api_key:
32
+ raise ValueError("Missing SERPAPI_API_KEY. Get one at https://serpapi.com/")
33
+ print("SerpAPI Agent initialized")
34
 
35
+ def search(self, query: str, num_results: int = 3) -> List[Dict]:
36
+ """Execute search and return structured results"""
37
+ params = {
38
+ "q": query,
39
+ "api_key": self.api_key,
40
+ "num": num_results,
41
+ "hl": "en", # Language: English
42
+ "gl": "us" # Country: United States
43
+ }
44
 
 
45
  try:
46
+ search = GoogleSearch(params)
47
+ results = search.get_dict()
48
+ return self._format_results(results)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  except Exception as e:
50
+ print(f"Search failed: {str(e)}")
51
+ return []
52
+
53
+ def _format_results(self, raw_results: Dict) -> List[Dict]:
54
+ """Extract and format organic results"""
55
+ formatted = []
56
+ for result in raw_results.get("organic_results", []):
57
+ formatted.append({
58
+ "position": result.get("position"),
59
+ "title": result.get("title"),
60
+ "link": result.get("link"),
61
+ "snippet": result.get("snippet"),
62
+ "source": result.get("source")
63
+ })
64
+ return formatted
65
+
66
+ def __call__(self, query: str) -> str:
67
+ """Callable interface that returns a string"""
68
+ results = self.search(query)
69
+ if not results:
70
+ return "No results found"
71
+
72
+ output = []
73
+ for res in results:
74
+ output.append(
75
+ f"{res['position']}. {res['title']}\n"
76
+ f" {res['link']}\n"
77
+ f" {res['snippet']}\n"
78
+ f" Source: {res['source']}"
79
+ )
80
+ return "\n\n".join(output)
81
+
82
+
83
+ # Usage Example
84
+ if __name__ == "__main__":
85
+ # Initialize with API key (or set SERPAPI_API_KEY environment variable)
86
+ agent = BasicAgent()
87
+
88
+ # Perform search
89
+ query = "What is Python programming language?"
90
+ print(f"Searching for: {query}")
91
+
92
+ # Option 1: Get structured data
93
+ structured_results = agent.search(query)
94
+ print("\nStructured Results:", structured_results[0]) # Print first result
95
+
96
+ # Option 2: Get printable string
97
+ printable_results = agent(query)
98
+ print("\nFormatted Results:\n", printable_results)
99
 
100
 
101
  def run_and_submit_all( profile: gr.OAuthProfile | None):