ErdemTheFixer commited on
Commit
a88e47f
·
verified ·
1 Parent(s): 0cd0932

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -117
app.py CHANGED
@@ -3,138 +3,35 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
6
- from typing import Dict, Any, List
7
- from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel, Tool
8
-
9
  # (Keep Constants as is)
10
  # --- Constants ---
11
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
 
13
- # --- Wikipedia Tool ---
14
- from smolagents import Tool
15
-
16
- class WikipediaTool(Tool):
17
- name = "wikipedia_search"
18
- description = "Searches Wikipedia and returns concise extracts from top results."
19
- output_type = "string" # REQUIRED by smolagents
20
-
21
- inputs = {
22
- "query": {
23
- "type": "string",
24
- "description": "The search query to look up on Wikipedia."
25
- }
26
- }
27
-
28
- def __init__(self, top_k: int = 3, language: str = "en"):
29
- super().__init__()
30
- self.top_k = max(1, min(top_k, 5))
31
- self.api = f"https://{language}.wikipedia.org/w/api.php"
32
-
33
- def forward(self, query: str) -> str:
34
- import requests
35
- try:
36
- # search
37
- r = requests.get(self.api, params={
38
- "action": "query",
39
- "list": "search",
40
- "srsearch": query,
41
- "srlimit": self.top_k,
42
- "utf8": "1",
43
- "format": "json",
44
- }, timeout=10)
45
- r.raise_for_status()
46
- hits = r.json().get("query", {}).get("search", [])
47
- pageids = [h.get("pageid") for h in hits if isinstance(h.get("pageid"), int)]
48
- if not pageids:
49
- return "No relevant Wikipedia snippets found."
50
-
51
- # extracts
52
- r2 = requests.get(self.api, params={
53
- "action": "query",
54
- "prop": "extracts",
55
- "explaintext": "1",
56
- "exintro": "1",
57
- "pageids": "|".join(str(pid) for pid in pageids),
58
- "format": "json",
59
- "utf8": "1",
60
- }, timeout=10)
61
- r2.raise_for_status()
62
- pages = r2.json().get("query", {}).get("pages", {})
63
-
64
- snippets = []
65
- for h in hits:
66
- pid = h.get("pageid")
67
- meta = pages.get(str(pid)) or pages.get(pid)
68
- text = (meta or {}).get("extract", "") if pid is not None else ""
69
- title = h.get("title", "")
70
- if text and title:
71
- sentences = text.split(". ")
72
- preview = ". ".join(sentences[:2]).strip()
73
- if preview:
74
- snippets.append(f"{title}: {preview}")
75
- return "\n".join(snippets) if snippets else "No relevant Wikipedia snippets found."
76
- except Exception as e:
77
- return f"Wikipedia error: {e}"
78
 
79
  # --- Basic Agent Definition ---
80
  class BasicAgent:
81
  def __init__(self):
82
  print("BasicAgent initialized.")
 
 
83
 
84
- # Provider selection (force away from OpenAI if quota-exceeded)
85
- force = (os.getenv("FORCE_PROVIDER") or "").strip().lower()
86
- openrouter_key = os.getenv("OPENROUTER_API_KEY")
87
- together_key = os.getenv("TOGETHER_API_KEY")
88
-
89
- provider = None
90
- model_id = None
91
- if force == "openrouter" or (openrouter_key and force != "together"):
92
- os.environ["OPENAI_API_KEY"] = openrouter_key
93
- os.environ["OPENAI_API_BASE"] = "https://openrouter.ai/api/v1"
94
- os.environ["OPENAI_BASE_URL"] = "https://openrouter.ai/api/v1"
95
- provider = "openrouter"
96
- model_id = os.getenv("OPENROUTER_MODEL", "meta-llama/Meta-Llama-3-8B-Instruct")
97
- elif force == "together" or together_key:
98
- os.environ["OPENAI_API_KEY"] = together_key
99
- os.environ["OPENAI_API_BASE"] = "https://api.together.xyz/v1"
100
- os.environ["OPENAI_BASE_URL"] = "https://api.together.xyz/v1"
101
- provider = "together"
102
- model_id = os.getenv("TOGETHER_MODEL", "meta-llama/Meta-Llama-3-8B-Instruct")
103
- else:
104
- # No non-OpenAI key available → use Wikipedia-only fallback
105
- self.wikipedia_only = True
106
- wiki_top_k = int(os.getenv("WIKI_TOP_K", "3"))
107
- wiki_lang = os.getenv("WIKI_LANG", "en")
108
- self.wikipedia_tool = WikipediaTool(top_k=wiki_top_k, language=wiki_lang)
109
- print("No non-OpenAI key set; running in Wikipedia-only mode.")
110
- return
111
-
112
- print(f"Using provider={provider}, model_id={model_id}")
113
- model = OpenAIServerModel(model_id=model_id)
114
-
115
- search_tool = DuckDuckGoSearchTool()
116
- wiki_top_k = int(os.getenv("WIKI_TOP_K", "3"))
117
- wiki_lang = os.getenv("WIKI_LANG", "en")
118
- wikipedia_tool = WikipediaTool(top_k=wiki_top_k, language=wiki_lang)
119
 
120
- self.agent = CodeAgent(model=model, tools=[search_tool, wikipedia_tool])
121
- self.wikipedia_only = False
 
 
 
122
 
123
  def __call__(self, question: str) -> str:
124
  print(f"Agent received question (first 50 chars): {question[:50]}...")
125
- if self.wikipedia_only:
126
- # Direct Wikipedia fallback
127
- return self.wikipedia_tool.forward(question)
128
 
129
- try:
130
- return self.agent.run(question)
131
- except Exception as e:
132
- # If provider throws (e.g., 429/insufficient_quota), fall back to Wikipedia
133
- print(f"LLM error, falling back to Wikipedia: {e}")
134
- try:
135
- return self.agent.tools[1].forward(question) # WikipediaTool as second tool
136
- except Exception:
137
- return "I cannot determine the answer."
138
 
139
  def run_and_submit_all( profile: gr.OAuthProfile | None):
140
  """
@@ -279,6 +176,7 @@ with gr.Blocks() as demo:
279
  run_button = gr.Button("Run Evaluation & Submit All Answers")
280
 
281
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
282
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
283
 
284
  run_button.click(
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel, WikipediaSearchTool
 
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  # --- Basic Agent Definition ---
13
  class BasicAgent:
14
  def __init__(self):
15
  print("BasicAgent initialized.")
16
+ # Initialize the model
17
+ model = OpenAIServerModel(model_id="gpt-4o-mini")
18
 
19
+ # Initialize search tools
20
+ duckduckgo = DuckDuckGoSearchTool()
21
+ wikipedia = WikipediaSearchTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Initialize Agent with both tools
24
+ self.agent = CodeAgent(
25
+ model=model,
26
+ tools=[duckduckgo, wikipedia]
27
+ )
28
 
29
  def __call__(self, question: str) -> str:
30
  print(f"Agent received question (first 50 chars): {question[:50]}...")
31
+ fixed_answer = self.agent.run(question)
32
+ print(f"Agent returning fixed answer: {fixed_answer}")
33
+ return fixed_answer
34
 
 
 
 
 
 
 
 
 
 
35
 
36
  def run_and_submit_all( profile: gr.OAuthProfile | None):
37
  """
 
176
  run_button = gr.Button("Run Evaluation & Submit All Answers")
177
 
178
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
179
+ # Removed max_rows=10 from DataFrame constructor
180
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
181
 
182
  run_button.click(