Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -4,181 +4,45 @@ import requests
|
|
4 |
import pandas as pd
|
5 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
6 |
|
7 |
-
# ---------- Imports for Advanced Agent ----------
|
8 |
-
import re
|
9 |
-
from langgraph.graph import StateGraph, MessagesState
|
10 |
-
from langgraph.prebuilt import tools_condition, ToolNode
|
11 |
-
from langchain_core.messages import SystemMessage, HumanMessage
|
12 |
-
from langchain_core.tools import tool
|
13 |
-
from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
|
14 |
-
from langchain_community.tools.tavily_search import TavilySearchResults
|
15 |
-
from groq import Groq
|
16 |
-
|
17 |
# --- Constants ---
|
18 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
19 |
|
20 |
-
#
|
21 |
-
from langchain_core.tools import tool
|
22 |
-
from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
|
23 |
-
from langchain_community.tools.tavily_search import TavilySearchResults
|
24 |
-
|
25 |
-
@tool
|
26 |
-
def wiki_search(query: str) -> str:
|
27 |
-
"""Search Wikipedia for a given query and return content from up to 2 relevant pages."""
|
28 |
-
docs = WikipediaLoader(query=query, load_max_docs=2).load()
|
29 |
-
return "\n\n".join([doc.page_content for doc in docs])
|
30 |
-
|
31 |
-
@tool
|
32 |
-
def web_search(query: str) -> str:
|
33 |
-
"""Search the web using the Tavily API and return content from up to 3 search results."""
|
34 |
-
docs = TavilySearchResults(max_results=3).invoke(query)
|
35 |
-
return "\n\n".join([doc.page_content for doc in docs])
|
36 |
-
|
37 |
-
@tool
|
38 |
-
def arvix_search(query: str) -> str:
|
39 |
-
"""Search academic papers on Arxiv for a given query and return up to 3 result summaries."""
|
40 |
-
docs = ArxivLoader(query=query, load_max_docs=3).load()
|
41 |
-
return "\n\n".join([doc.page_content[:1000] for doc in docs])
|
42 |
-
|
43 |
-
# Tool-based LangGraph builder
|
44 |
-
def build_tool_graph(system_prompt):
|
45 |
-
llm = AutoModelForCausalLM.from_pretrained("gpt2") # Load Hugging Face GPT-2 model
|
46 |
-
tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
47 |
-
|
48 |
-
def assistant(state: MessagesState):
|
49 |
-
input_text = state["messages"][-1]["content"]
|
50 |
-
inputs = tokenizer(input_text, return_tensors="pt")
|
51 |
-
outputs = llm.generate(**inputs)
|
52 |
-
result = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
53 |
-
return {"messages": [{"content": result}]}
|
54 |
-
|
55 |
-
builder = StateGraph(MessagesState)
|
56 |
-
builder.add_node("assistant", assistant)
|
57 |
-
builder.add_node("tools", ToolNode([wiki_search, web_search, arvix_search]))
|
58 |
-
builder.set_entry_point("assistant")
|
59 |
-
builder.set_finish_point("assistant")
|
60 |
-
builder.add_conditional_edges("assistant", tools_condition)
|
61 |
-
builder.add_edge("tools", "assistant")
|
62 |
-
return builder.compile()
|
63 |
-
|
64 |
-
|
65 |
-
# --- Advanced BasicAgent Class ---
|
66 |
class BasicAgent:
|
67 |
def __init__(self):
|
68 |
print("BasicAgent initialized.")
|
69 |
-
self.client = Groq
|
70 |
self.agent_prompt = (
|
71 |
"""You are a general AI assistant. I will ask you a question. Report your thoughts, and
|
72 |
-
finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
|
73 |
-
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated
|
74 |
-
list of numbers and/or strings.
|
75 |
-
If you are asked for a number, don't use comma to write your number neither use units such as $
|
76 |
-
or percent sign unless specified otherwise.
|
77 |
-
If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the
|
78 |
-
digits in plain text unless specified otherwise.
|
79 |
-
If you are asked for a comma separated list, apply the above rules depending of whether the element
|
80 |
-
to be put in the list is a number or a string."""
|
81 |
)
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
return f"FINAL ANSWER: {match.group(1).strip()}" if match else f"FINAL ANSWER: {cleaned}"
|
88 |
-
|
89 |
def query_groq(self, question: str) -> str:
|
90 |
-
|
91 |
-
|
92 |
-
response = self.client.chat.completions.create(
|
93 |
-
model="llama3-8b-8192",
|
94 |
-
messages=[{"role": "user", "content": full_prompt}]
|
95 |
-
)
|
96 |
-
answer = response.choices[0].message.content
|
97 |
-
print(f"[Groq Raw Response]: {answer}")
|
98 |
-
return self.format_final_answer(answer).upper()
|
99 |
-
except Exception as e:
|
100 |
-
print(f"[Groq ERROR]: {e}")
|
101 |
-
return self.format_final_answer("GROQ_ERROR")
|
102 |
|
103 |
def query_tools(self, question: str) -> str:
|
104 |
-
|
105 |
-
|
106 |
-
"messages": [
|
107 |
-
SystemMessage(content=self.agent_prompt),
|
108 |
-
HumanMessage(content=question)
|
109 |
-
]
|
110 |
-
}
|
111 |
-
result = self.tool_chain.invoke(input_state)
|
112 |
-
final_msg = result["messages"][-1].content
|
113 |
-
print(f"[LangGraph Final Response]: {final_msg}")
|
114 |
-
return self.format_final_answer(final_msg)
|
115 |
-
except Exception as e:
|
116 |
-
print(f"[LangGraph ERROR]: {e}")
|
117 |
-
return self.format_final_answer("TOOL_ERROR")
|
118 |
|
119 |
def __call__(self, question: str) -> str:
|
120 |
-
|
121 |
-
if "commutative" in question.lower():
|
122 |
-
return self.check_commutativity()
|
123 |
-
if self.maybe_reversed(question):
|
124 |
-
print("Detected likely reversed riddle.")
|
125 |
-
return self.solve_riddle(question)
|
126 |
if "use tools" in question.lower():
|
127 |
return self.query_tools(question)
|
128 |
return self.query_groq(question)
|
129 |
|
130 |
-
|
131 |
-
|
132 |
-
counter_example_elements = set()
|
133 |
-
index = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}
|
134 |
-
self.operation_table = [
|
135 |
-
['a', 'b', 'c', 'b', 'd'],
|
136 |
-
['b', 'c', 'a', 'e', 'c'],
|
137 |
-
['c', 'a', 'b', 'b', 'a'],
|
138 |
-
['b', 'e', 'b', 'e', 'd'],
|
139 |
-
['d', 'b', 'a', 'd', 'c']
|
140 |
-
]
|
141 |
-
for x in S:
|
142 |
-
for y in S:
|
143 |
-
x_idx = index[x]
|
144 |
-
y_idx = index[y]
|
145 |
-
if self.operation_table[x_idx][y_idx] != self.operation_table[y_idx][x_idx]:
|
146 |
-
counter_example_elements.add(x)
|
147 |
-
counter_example_elements.add(y)
|
148 |
-
return self.format_final_answer(", ".join(sorted(counter_example_elements)))
|
149 |
-
|
150 |
-
def maybe_reversed(self, text: str) -> bool:
|
151 |
-
words = text.split()
|
152 |
-
reversed_ratio = sum(
|
153 |
-
1 for word in words if word[::-1].lower() in {
|
154 |
-
"if", "you", "understand", "this", "sentence", "write",
|
155 |
-
"opposite", "of", "the", "word", "left", "answer"
|
156 |
-
}
|
157 |
-
) / len(words)
|
158 |
-
return reversed_ratio > 0.3
|
159 |
-
|
160 |
-
def solve_riddle(self, question: str) -> str:
|
161 |
-
question = question[::-1]
|
162 |
-
if "opposite of the word" in question:
|
163 |
-
match = re.search(r"opposite of the word ['\"](\w+)['\"]", question)
|
164 |
-
if match:
|
165 |
-
word = match.group(1).lower()
|
166 |
-
opposites = {
|
167 |
-
"left": "right", "up": "down", "hot": "cold",
|
168 |
-
"true": "false", "yes": "no", "black": "white"
|
169 |
-
}
|
170 |
-
opposite = opposites.get(word, f"UNKNOWN_OPPOSITE_OF_{word}")
|
171 |
-
return f"FINAL ANSWER: {opposite.upper()}"
|
172 |
-
return self.format_final_answer("COULD_NOT_SOLVE")
|
173 |
-
|
174 |
-
# --- Evaluation Logic ---
|
175 |
-
def run_and_submit_all(profile, test_mode):
|
176 |
space_id = os.getenv("SPACE_ID")
|
177 |
if profile:
|
178 |
username = profile
|
179 |
print(f"User logged in: {username}")
|
180 |
else:
|
181 |
-
return "Please
|
182 |
|
183 |
api_url = DEFAULT_API_URL
|
184 |
questions_url = f"{api_url}/questions"
|
@@ -249,19 +113,14 @@ with gr.Blocks() as demo:
|
|
249 |
3. Click the button to run evaluation and submit your answers.
|
250 |
"""
|
251 |
)
|
252 |
-
|
253 |
-
# Simulate OAuth profile with a textbox for user
|
254 |
-
test_checkbox = gr.Checkbox(label="Enable Test Mode (Skip Submission)", value=False)
|
255 |
run_button = gr.Button("Run Evaluation")
|
256 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
257 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
258 |
-
|
259 |
-
# Simulate OAuth Profile with a mock profile for now
|
260 |
-
mock_oauth_profile = gr.Textbox(label="Simulated OAuth Profile", value="mock_user", interactive=False)
|
261 |
|
262 |
run_button.click(
|
263 |
fn=run_and_submit_all,
|
264 |
-
inputs=[
|
265 |
outputs=[status_output, results_table]
|
266 |
)
|
267 |
|
|
|
4 |
import pandas as pd
|
5 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
# --- Constants ---
|
8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
9 |
|
10 |
+
# --- Advanced Agent Logic ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
class BasicAgent:
|
12 |
def __init__(self):
|
13 |
print("BasicAgent initialized.")
|
14 |
+
self.client = None # Placeholder for Groq or another API client
|
15 |
self.agent_prompt = (
|
16 |
"""You are a general AI assistant. I will ask you a question. Report your thoughts, and
|
17 |
+
finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
)
|
19 |
+
|
20 |
+
# Assuming some model for queries
|
21 |
+
self.llm = AutoModelForCausalLM.from_pretrained("gpt2")
|
22 |
+
self.tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
23 |
+
|
|
|
|
|
24 |
def query_groq(self, question: str) -> str:
|
25 |
+
# Placeholder for Groq query handling
|
26 |
+
return f"FINAL ANSWER: {question}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
def query_tools(self, question: str) -> str:
|
29 |
+
# Placeholder for using tools
|
30 |
+
return f"FINAL ANSWER: {question}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
def __call__(self, question: str) -> str:
|
33 |
+
# Decide based on the question type, here we use placeholder logic
|
|
|
|
|
|
|
|
|
|
|
34 |
if "use tools" in question.lower():
|
35 |
return self.query_tools(question)
|
36 |
return self.query_groq(question)
|
37 |
|
38 |
+
# --- Evaluation and Submission Logic ---
|
39 |
+
def run_and_submit_all(profile):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
space_id = os.getenv("SPACE_ID")
|
41 |
if profile:
|
42 |
username = profile
|
43 |
print(f"User logged in: {username}")
|
44 |
else:
|
45 |
+
return "Please provide a username.", None
|
46 |
|
47 |
api_url = DEFAULT_API_URL
|
48 |
questions_url = f"{api_url}/questions"
|
|
|
113 |
3. Click the button to run evaluation and submit your answers.
|
114 |
"""
|
115 |
)
|
116 |
+
profile_input = gr.Textbox(label="Enter Username", placeholder="Enter your username", interactive=True)
|
|
|
|
|
117 |
run_button = gr.Button("Run Evaluation")
|
118 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
119 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
|
|
|
|
|
|
120 |
|
121 |
run_button.click(
|
122 |
fn=run_and_submit_all,
|
123 |
+
inputs=[profile_input],
|
124 |
outputs=[status_output, results_table]
|
125 |
)
|
126 |
|