patricksamuel commited on
Commit
b8d6f51
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -4
app.py CHANGED
@@ -1,8 +1,101 @@
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 ---
@@ -15,9 +108,57 @@ class BasicAgent:
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
  """
 
1
  import os
2
  import gradio as gr
 
3
  import inspect
4
  import pandas as pd
5
+ from agents import Agent, Runner, function_tool
6
+ from duckduckgo_search import DDGS
7
+ from agents import Agent, Runner
8
+ from markdownify import markdownify
9
+ from duckduckgo_search import DDGS
10
+ from bs4 import BeautifulSoup
11
+ from pydantic import BaseModel, Field
12
+ import nest_asyncio
13
+ import requests
14
+ import os, re
15
+ import litellm
16
+
17
+ os.getenv("OPENAI_API_KEY")
18
+ os.getenv("GEMINI_API_KEY")
19
+ os.environ["LITELLM_PROVIDER"] = "gemini"
20
+
21
+ # add this
22
+ nest_asyncio.apply()
23
+
24
+
25
+ #Tools
26
+
27
+ @function_tool
28
+ def web_search(query: str) -> str:
29
+ """
30
+ Perform a web search.
31
+ Args:
32
+ query (str): The search query string.
33
+ Returns:
34
+ str: The search results formatted in markdown.
35
+ """
36
+
37
+ try:
38
+ results = DDGS().text(query, max_results=10)
39
+
40
+ if not results:
41
+ raise Exception("No search results found.")
42
+
43
+ formatted_results = []
44
+ for i, result in enumerate(results, 1):
45
+ title = result.get("title", "No title available.")
46
+ link = result.get("href", "No link available.")
47
+ snippet = result.get("body", "No description available.")
48
+
49
+ entry = " \n".join([
50
+ f"**Title**: {title}",
51
+ f"**Link**: {link}",
52
+ f"**Snippet**: {snippet}"
53
+ ])
54
+
55
+ formatted_results.append(entry)
56
+
57
+ return "\n\n".join(formatted_results)
58
+
59
+ except Exception as e:
60
+ return f"Error executing the query: {e}"
61
+
62
+ @function_tool
63
+ def visit_website(url: str) -> str:
64
+ """
65
+ Extract the contents of a website.
66
+ Args:
67
+ url (str): The URL of the website to visit.
68
+ Returns:
69
+ str: Formatted markdown ready for LLM consumption.
70
+ """
71
+
72
+ headers = {
73
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
74
+ }
75
+
76
+ try:
77
+ response = requests.get(url, headers=headers, timeout=10)
78
+ response.raise_for_status()
79
+
80
+ html_content = response.text
81
+ soup = BeautifulSoup(html_content, 'html.parser')
82
+
83
+ for tag in soup(['script', 'style', 'nav', 'header', 'footer', 'aside', 'meta']):
84
+ tag.decompose()
85
+
86
+ main_content = soup.body
87
+ markdown_text = markdownify(str(main_content), strip=['img', 'iframe', 'script', 'meta', 'button', 'input', 'svg'])
88
+
89
+ max_length = 10000
90
+ markdown_text = re.sub(r'\n\s*\n', '\n\n', markdown_text[:max_length])
91
+
92
+ return markdown_text
93
+
94
+ except requests.RequestException as e:
95
+ return f"Error fetching the website: {e}"
96
+
97
+
98
+
99
 
100
  # (Keep Constants as is)
101
  # --- Constants ---
 
108
  print("BasicAgent initialized.")
109
  def __call__(self, question: str) -> str:
110
  print(f"Agent received question (first 50 chars): {question[:50]}...")
111
+
112
+ instructions = """
113
+ You are a ReAct (Reason-Act-Observe) agent that searches the internet to find accurate answers to questions.
114
+ ## Available Tools
115
+ - **web_search**: Search the web for information
116
+ - **visit_website**: Visit specific webpages for detailed content
117
+ ## Output Format Rules
118
+ Your final answer must be **exactly one** of these formats:
119
+ - **Single number**: No commas, units, or symbols (unless explicitly requested)
120
+ - **Single word/phrase**: No abbreviations (write "Los Angeles" not "LA")
121
+ - **Comma-separated list**: Each item follows the above rules
122
+ **Important**: Provide ONLY the final answer - no explanations, markdown, or extra text.
123
+ ## ReAct Process
124
+ Follow this cycle until you find the answer:
125
+ **Thought**: [Internal reasoning about your next step]
126
+ **Action**: [Single tool call]
127
+ **Observation**: [Tool result will appear here]
128
+ ## Quality Guidelines
129
+ - Use multiple sources when possible to verify accuracy
130
+ - For recent events, prioritize newer sources
131
+ - If information conflicts between sources, use the most authoritative source
132
+ - For numerical data, ensure you're using the most current figures
133
+ ## Before Final Answer
134
+ - Internally verify: "Does my answer violate format rules (extra text, wrong units, abbreviations)?"
135
+ - Before providing a final answer, always ensure it contains the minimal amount of text possible.
136
+ ## Examples
137
+ - Q: What is 15 + 27? → 42
138
+ - Q: What is the capital of France? → Paris
139
+ - Q: What are the top 3 most populous US states? → California, Texas, Florida
140
+ """
141
+
142
+ my_agent = Agent(
143
+ name="Expert Question Answering Agent",
144
+ instructions=instructions,
145
+ tools = [
146
+ web_search,
147
+ visit_website
148
+ ],
149
+ model="gpt-4o-mini"
150
+ )
151
+
152
+ result = Runner.run_sync(
153
+ my_agent,
154
+ input=question,
155
+ max_turns=25
156
+ )
157
+
158
+
159
+
160
+ print(f"Agent returning fixed answer(first 50 chars): {result.final_output[:50]}...")
161
+ return result.final_output
162
 
163
  def run_and_submit_all( profile: gr.OAuthProfile | None):
164
  """