Spaces:
Runtime error
Runtime error
Initial commit with LlamaIndex-based agent
Browse files- app.py +76 -36
- data/knowledge.txt +0 -0
- requirements.txt +7 -1
app.py
CHANGED
@@ -1,27 +1,79 @@
|
|
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 ---
|
9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
10 |
|
11 |
-
# ---
|
12 |
-
|
13 |
-
class BasicAgent:
|
14 |
def __init__(self):
|
15 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
def __call__(self, question: str) -> str:
|
17 |
-
print(f"
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
21 |
|
22 |
-
|
|
|
23 |
"""
|
24 |
-
Fetches all questions, runs the
|
25 |
and displays the results.
|
26 |
"""
|
27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
@@ -38,13 +90,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
38 |
questions_url = f"{api_url}/questions"
|
39 |
submit_url = f"{api_url}/submit"
|
40 |
|
41 |
-
# 1. Instantiate Agent
|
42 |
try:
|
43 |
-
agent =
|
44 |
except Exception as e:
|
45 |
print(f"Error instantiating agent: {e}")
|
46 |
return f"Error initializing agent: {e}", None
|
47 |
-
|
48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
49 |
print(agent_code)
|
50 |
|
@@ -139,31 +191,21 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
139 |
results_df = pd.DataFrame(results_log)
|
140 |
return status_message, results_df
|
141 |
|
142 |
-
|
143 |
-
# --- Build Gradio Interface using Blocks ---
|
144 |
with gr.Blocks() as demo:
|
145 |
-
gr.Markdown("#
|
146 |
gr.Markdown(
|
147 |
"""
|
148 |
**Instructions:**
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
153 |
-
|
154 |
-
---
|
155 |
-
**Disclaimers:**
|
156 |
-
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
157 |
-
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
158 |
"""
|
159 |
)
|
160 |
|
161 |
gr.LoginButton()
|
162 |
-
|
163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
164 |
-
|
165 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
166 |
-
# Removed max_rows=10 from DataFrame constructor
|
167 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
168 |
|
169 |
run_button.click(
|
@@ -173,9 +215,8 @@ with gr.Blocks() as demo:
|
|
173 |
|
174 |
if __name__ == "__main__":
|
175 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
176 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
177 |
space_host_startup = os.getenv("SPACE_HOST")
|
178 |
-
space_id_startup = os.getenv("SPACE_ID")
|
179 |
|
180 |
if space_host_startup:
|
181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
@@ -183,14 +224,13 @@ if __name__ == "__main__":
|
|
183 |
else:
|
184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
185 |
|
186 |
-
if space_id_startup:
|
187 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
188 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
189 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
190 |
else:
|
191 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?).
|
192 |
|
193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
194 |
-
|
195 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
196 |
demo.launch(debug=True, share=False)
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
import requests
|
|
|
4 |
import pandas as pd
|
5 |
+
from llama_index.llms.huggingface import HuggingFaceLLM
|
6 |
+
from llama_index.core.agent import ReActAgent
|
7 |
+
from llama_index.core.tools import FunctionTool
|
8 |
+
from transformers import AutoTokenizer
|
9 |
|
|
|
10 |
# --- Constants ---
|
11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
12 |
|
13 |
+
# --- Advanced Agent Definition ---
|
14 |
+
class SmartAgent:
|
|
|
15 |
def __init__(self):
|
16 |
+
print("Initializing Local LLM Agent...")
|
17 |
+
|
18 |
+
# Initialize Zephyr-7B model
|
19 |
+
self.llm = HuggingFaceLLM(
|
20 |
+
model_name="HuggingFaceH4/zephyr-7b-beta",
|
21 |
+
tokenizer_name="HuggingFaceH4/zephyr-7b-beta",
|
22 |
+
context_window=2048,
|
23 |
+
max_new_tokens=256,
|
24 |
+
generate_kwargs={"temperature": 0.7, "do_sample": True},
|
25 |
+
device_map="auto"
|
26 |
+
)
|
27 |
+
|
28 |
+
# Define tools
|
29 |
+
self.tools = [
|
30 |
+
FunctionTool.from_defaults(
|
31 |
+
fn=self.web_search,
|
32 |
+
name="web_search",
|
33 |
+
description="Searches the web for current information when questions require up-to-date knowledge"
|
34 |
+
),
|
35 |
+
FunctionTool.from_defaults(
|
36 |
+
fn=self.math_calculator,
|
37 |
+
name="math_calculator",
|
38 |
+
description="Performs mathematical calculations when questions involve numbers or equations"
|
39 |
+
)
|
40 |
+
]
|
41 |
+
|
42 |
+
# Create agent
|
43 |
+
self.agent = ReActAgent.from_tools(
|
44 |
+
tools=self.tools,
|
45 |
+
llm=self.llm,
|
46 |
+
verbose=True
|
47 |
+
)
|
48 |
+
print("Local LLM Agent initialized successfully.")
|
49 |
+
|
50 |
+
def web_search(self, query: str) -> str:
|
51 |
+
"""Simulated web search tool (replace with actual API)"""
|
52 |
+
print(f"Web search triggered for: {query[:50]}...")
|
53 |
+
return f"Web results for: {query} (implement actual search API here)"
|
54 |
+
|
55 |
+
def math_calculator(self, expression: str) -> str:
|
56 |
+
"""Simple math calculator"""
|
57 |
+
print(f"Math calculation triggered for: {expression}")
|
58 |
+
try:
|
59 |
+
result = eval(expression) # Note: In production, use safer eval alternatives
|
60 |
+
return str(result)
|
61 |
+
except:
|
62 |
+
return "Error: Could not evaluate the mathematical expression"
|
63 |
+
|
64 |
def __call__(self, question: str) -> str:
|
65 |
+
print(f"Processing question (first 50 chars): {question[:50]}...")
|
66 |
+
try:
|
67 |
+
response = self.agent.query(question)
|
68 |
+
return str(response)
|
69 |
+
except Exception as e:
|
70 |
+
print(f"Agent error: {str(e)}")
|
71 |
+
return f"Error processing question: {str(e)}"
|
72 |
|
73 |
+
# --- Original Submission Logic (Keep unchanged) ---
|
74 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
75 |
"""
|
76 |
+
Fetches all questions, runs the agent on them, submits all answers,
|
77 |
and displays the results.
|
78 |
"""
|
79 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
|
|
90 |
questions_url = f"{api_url}/questions"
|
91 |
submit_url = f"{api_url}/submit"
|
92 |
|
93 |
+
# 1. Instantiate Agent
|
94 |
try:
|
95 |
+
agent = SmartAgent() # Using our new SmartAgent instead of BasicAgent
|
96 |
except Exception as e:
|
97 |
print(f"Error instantiating agent: {e}")
|
98 |
return f"Error initializing agent: {e}", None
|
99 |
+
|
100 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
101 |
print(agent_code)
|
102 |
|
|
|
191 |
results_df = pd.DataFrame(results_log)
|
192 |
return status_message, results_df
|
193 |
|
194 |
+
# --- Build Gradio Interface ---
|
|
|
195 |
with gr.Blocks() as demo:
|
196 |
+
gr.Markdown("# Local LLM Agent Evaluation Runner")
|
197 |
gr.Markdown(
|
198 |
"""
|
199 |
**Instructions:**
|
200 |
+
1. Log in to your Hugging Face account
|
201 |
+
2. Click 'Run Evaluation & Submit All Answers'
|
202 |
+
3. Wait for the local LLM to process all questions
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
"""
|
204 |
)
|
205 |
|
206 |
gr.LoginButton()
|
|
|
207 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
208 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
209 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
210 |
|
211 |
run_button.click(
|
|
|
215 |
|
216 |
if __name__ == "__main__":
|
217 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
218 |
space_host_startup = os.getenv("SPACE_HOST")
|
219 |
+
space_id_startup = os.getenv("SPACE_ID")
|
220 |
|
221 |
if space_host_startup:
|
222 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
224 |
else:
|
225 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
226 |
|
227 |
+
if space_id_startup:
|
228 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
229 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
230 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
231 |
else:
|
232 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?).")
|
233 |
|
234 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
235 |
+
print("Launching Gradio Interface for Local LLM Agent Evaluation...")
|
|
|
236 |
demo.launch(debug=True, share=False)
|
data/knowledge.txt
ADDED
File without changes
|
requirements.txt
CHANGED
@@ -1,2 +1,8 @@
|
|
1 |
gradio
|
2 |
-
requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
gradio
|
2 |
+
requests
|
3 |
+
llama-index
|
4 |
+
transformers
|
5 |
+
torch
|
6 |
+
accelerate
|
7 |
+
duckduckgo-search # For web search tools
|
8 |
+
python-dotenv # For API keys (if needed)
|