req_pydantic
Browse files- app.py +66 -55
- requirements.txt +1 -1
app.py
CHANGED
@@ -6,6 +6,7 @@ import pandas as pd
|
|
6 |
from typing import Dict, Any, List, TypedDict
|
7 |
from langgraph.graph import Graph, StateGraph
|
8 |
from langgraph.prebuilt import ToolNode
|
|
|
9 |
from tools import create_calculator_tool, create_search_tool
|
10 |
print("trial")
|
11 |
# (Keep Constants as is)
|
@@ -14,6 +15,16 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
14 |
MODEL_API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-Coder-32B-Instruct"
|
15 |
HF_TOKEN = os.getenv("HF_TOKEN") # Make sure to set this environment variable
|
16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
class BasicAgent:
|
18 |
def __init__(self):
|
19 |
print("Initializing BasicAgent with Qwen2.5-Coder-32B-Instruct API...")
|
@@ -36,8 +47,8 @@ class BasicAgent:
|
|
36 |
|
37 |
def _create_workflow(self) -> Graph:
|
38 |
"""Create the agent workflow using LangGraph."""
|
39 |
-
# Create the workflow with
|
40 |
-
workflow = StateGraph(
|
41 |
|
42 |
# Add nodes
|
43 |
workflow.add_node("analyze", self._analyze_question)
|
@@ -53,12 +64,12 @@ class BasicAgent:
|
|
53 |
workflow.add_edge("search", "final_answer")
|
54 |
|
55 |
# Define conditional edges
|
56 |
-
def router(state:
|
57 |
-
if state.
|
58 |
return 'calculator'
|
59 |
-
elif state.
|
60 |
return 'search'
|
61 |
-
elif state.
|
62 |
return 'final_answer'
|
63 |
return 'analyze'
|
64 |
|
@@ -92,9 +103,9 @@ class BasicAgent:
|
|
92 |
print(f"Error calling LLM API: {e}")
|
93 |
return f"Error getting response from LLM: {str(e)}"
|
94 |
|
95 |
-
def _analyze_question(self, state:
|
96 |
"""Analyze the question and determine the next step."""
|
97 |
-
prompt = f"""Analyze this question and determine what needs to be done: {state
|
98 |
Return your analysis in this format:
|
99 |
{{
|
100 |
"needs_calculation": true/false,
|
@@ -108,67 +119,67 @@ class BasicAgent:
|
|
108 |
"""
|
109 |
|
110 |
analysis = eval(self._call_llm_api(prompt))
|
111 |
-
state
|
112 |
-
state
|
113 |
|
114 |
if analysis.get('needs_calculation', False):
|
115 |
-
state
|
116 |
-
state
|
117 |
elif analysis.get('needs_search', False):
|
118 |
-
state
|
119 |
else:
|
120 |
-
state
|
121 |
|
122 |
return state
|
123 |
|
124 |
-
def _use_calculator(self, state:
|
125 |
"""Use the calculator tool."""
|
126 |
try:
|
127 |
-
result = self.calculator.invoke({"input": eval(state
|
128 |
-
state
|
129 |
'step': 'calculator',
|
130 |
-
'input': state
|
131 |
'output': str(result['output'].result)
|
132 |
})
|
133 |
-
state
|
134 |
except Exception as e:
|
135 |
-
state
|
136 |
'step': 'calculator_error',
|
137 |
'error': str(e)
|
138 |
})
|
139 |
-
state
|
140 |
return state
|
141 |
|
142 |
-
def _use_search(self, state:
|
143 |
"""Use the search tool."""
|
144 |
try:
|
145 |
result = self.search_tool.invoke({
|
146 |
"input": {
|
147 |
-
"query": state
|
148 |
"max_results": 3
|
149 |
}
|
150 |
})
|
151 |
-
state
|
152 |
'step': 'search',
|
153 |
-
'query': state
|
154 |
'results': [str(r) for r in result['output'].results]
|
155 |
})
|
156 |
-
state
|
157 |
-
state
|
158 |
except Exception as e:
|
159 |
-
state
|
160 |
'step': 'search_error',
|
161 |
'error': str(e)
|
162 |
})
|
163 |
-
state
|
164 |
return state
|
165 |
|
166 |
-
def _generate_final_answer(self, state:
|
167 |
"""Generate the final answer based on all gathered information."""
|
168 |
history_str = "\n".join([f"{h['step']}: {h.get('output', h.get('results', h.get('error', '')))}"
|
169 |
-
for h in state
|
170 |
|
171 |
-
prompt = f"""Based on the following information and history, provide a final answer to the question: {state
|
172 |
|
173 |
History of steps taken:
|
174 |
{history_str}
|
@@ -176,7 +187,7 @@ class BasicAgent:
|
|
176 |
Provide a clear, concise answer that addresses the original question.
|
177 |
"""
|
178 |
|
179 |
-
state
|
180 |
return state
|
181 |
|
182 |
def __call__(self, question: str) -> str:
|
@@ -185,19 +196,19 @@ class BasicAgent:
|
|
185 |
|
186 |
try:
|
187 |
# Initialize the state
|
188 |
-
initial_state =
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
|
198 |
# Run the workflow
|
199 |
final_state = self.workflow.invoke(initial_state)
|
200 |
-
return final_state
|
201 |
|
202 |
except Exception as e:
|
203 |
print(f"Error in agent processing: {e}")
|
@@ -269,15 +280,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
269 |
|
270 |
try:
|
271 |
# Initialize the state for this question
|
272 |
-
initial_state =
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
|
282 |
# Run the workflow for this question
|
283 |
print(f"\nProcessing question {task_id}: {question_text[:50]}...")
|
@@ -288,11 +299,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
288 |
f"Step: {h['step']}\n" +
|
289 |
f"Input: {h.get('input', h.get('query', ''))}\n" +
|
290 |
f"Output: {h.get('output', h.get('results', h.get('error', '')))}"
|
291 |
-
for h in final_state
|
292 |
])
|
293 |
|
294 |
# Add to results
|
295 |
-
submitted_answer = final_state
|
296 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
297 |
results_log.append({
|
298 |
"Task ID": task_id,
|
@@ -301,7 +312,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
301 |
"Workflow History": workflow_history
|
302 |
})
|
303 |
|
304 |
-
print(f"Completed question {task_id} with {len(final_state
|
305 |
|
306 |
except Exception as e:
|
307 |
print(f"Error running agent workflow on task {task_id}: {e}")
|
|
|
6 |
from typing import Dict, Any, List, TypedDict
|
7 |
from langgraph.graph import Graph, StateGraph
|
8 |
from langgraph.prebuilt import ToolNode
|
9 |
+
from pydantic import BaseModel, Field
|
10 |
from tools import create_calculator_tool, create_search_tool
|
11 |
print("trial")
|
12 |
# (Keep Constants as is)
|
|
|
15 |
MODEL_API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-Coder-32B-Instruct"
|
16 |
HF_TOKEN = os.getenv("HF_TOKEN") # Make sure to set this environment variable
|
17 |
|
18 |
+
class AgentState(BaseModel):
|
19 |
+
"""Schema for the agent's state."""
|
20 |
+
question: str = Field(..., description="The original question")
|
21 |
+
current_step: str = Field(default="analyze", description="Current step in the workflow")
|
22 |
+
tool_output: str = Field(default="", description="Output from the last tool used")
|
23 |
+
final_answer: str = Field(default="", description="The final answer to be returned")
|
24 |
+
history: List[Dict[str, str]] = Field(default_factory=list, description="History of operations performed")
|
25 |
+
needs_more_info: bool = Field(default=False, description="Whether more information is needed")
|
26 |
+
search_query: str = Field(default="", description="Current search query if any")
|
27 |
+
|
28 |
class BasicAgent:
|
29 |
def __init__(self):
|
30 |
print("Initializing BasicAgent with Qwen2.5-Coder-32B-Instruct API...")
|
|
|
47 |
|
48 |
def _create_workflow(self) -> Graph:
|
49 |
"""Create the agent workflow using LangGraph."""
|
50 |
+
# Create the workflow with state schema
|
51 |
+
workflow = StateGraph(AgentState)
|
52 |
|
53 |
# Add nodes
|
54 |
workflow.add_node("analyze", self._analyze_question)
|
|
|
64 |
workflow.add_edge("search", "final_answer")
|
65 |
|
66 |
# Define conditional edges
|
67 |
+
def router(state: AgentState) -> str:
|
68 |
+
if state.current_step == 'calculator':
|
69 |
return 'calculator'
|
70 |
+
elif state.current_step == 'search':
|
71 |
return 'search'
|
72 |
+
elif state.current_step == 'final_answer':
|
73 |
return 'final_answer'
|
74 |
return 'analyze'
|
75 |
|
|
|
103 |
print(f"Error calling LLM API: {e}")
|
104 |
return f"Error getting response from LLM: {str(e)}"
|
105 |
|
106 |
+
def _analyze_question(self, state: AgentState) -> AgentState:
|
107 |
"""Analyze the question and determine the next step."""
|
108 |
+
prompt = f"""Analyze this question and determine what needs to be done: {state.question}
|
109 |
Return your analysis in this format:
|
110 |
{{
|
111 |
"needs_calculation": true/false,
|
|
|
119 |
"""
|
120 |
|
121 |
analysis = eval(self._call_llm_api(prompt))
|
122 |
+
state.needs_more_info = analysis.get('needs_search', False)
|
123 |
+
state.search_query = analysis.get('search_query', '')
|
124 |
|
125 |
if analysis.get('needs_calculation', False):
|
126 |
+
state.current_step = 'calculator'
|
127 |
+
state.tool_output = str(analysis['calculation'])
|
128 |
elif analysis.get('needs_search', False):
|
129 |
+
state.current_step = 'search'
|
130 |
else:
|
131 |
+
state.current_step = 'final_answer'
|
132 |
|
133 |
return state
|
134 |
|
135 |
+
def _use_calculator(self, state: AgentState) -> AgentState:
|
136 |
"""Use the calculator tool."""
|
137 |
try:
|
138 |
+
result = self.calculator.invoke({"input": eval(state.tool_output)})
|
139 |
+
state.history.append({
|
140 |
'step': 'calculator',
|
141 |
+
'input': state.tool_output,
|
142 |
'output': str(result['output'].result)
|
143 |
})
|
144 |
+
state.current_step = 'final_answer'
|
145 |
except Exception as e:
|
146 |
+
state.history.append({
|
147 |
'step': 'calculator_error',
|
148 |
'error': str(e)
|
149 |
})
|
150 |
+
state.current_step = 'final_answer'
|
151 |
return state
|
152 |
|
153 |
+
def _use_search(self, state: AgentState) -> AgentState:
|
154 |
"""Use the search tool."""
|
155 |
try:
|
156 |
result = self.search_tool.invoke({
|
157 |
"input": {
|
158 |
+
"query": state.search_query,
|
159 |
"max_results": 3
|
160 |
}
|
161 |
})
|
162 |
+
state.history.append({
|
163 |
'step': 'search',
|
164 |
+
'query': state.search_query,
|
165 |
'results': [str(r) for r in result['output'].results]
|
166 |
})
|
167 |
+
state.needs_more_info = False
|
168 |
+
state.current_step = 'final_answer'
|
169 |
except Exception as e:
|
170 |
+
state.history.append({
|
171 |
'step': 'search_error',
|
172 |
'error': str(e)
|
173 |
})
|
174 |
+
state.current_step = 'final_answer'
|
175 |
return state
|
176 |
|
177 |
+
def _generate_final_answer(self, state: AgentState) -> AgentState:
|
178 |
"""Generate the final answer based on all gathered information."""
|
179 |
history_str = "\n".join([f"{h['step']}: {h.get('output', h.get('results', h.get('error', '')))}"
|
180 |
+
for h in state.history])
|
181 |
|
182 |
+
prompt = f"""Based on the following information and history, provide a final answer to the question: {state.question}
|
183 |
|
184 |
History of steps taken:
|
185 |
{history_str}
|
|
|
187 |
Provide a clear, concise answer that addresses the original question.
|
188 |
"""
|
189 |
|
190 |
+
state.final_answer = self._call_llm_api(prompt)
|
191 |
return state
|
192 |
|
193 |
def __call__(self, question: str) -> str:
|
|
|
196 |
|
197 |
try:
|
198 |
# Initialize the state
|
199 |
+
initial_state = AgentState(
|
200 |
+
question=question,
|
201 |
+
current_step="analyze",
|
202 |
+
tool_output="",
|
203 |
+
final_answer="",
|
204 |
+
history=[],
|
205 |
+
needs_more_info=False,
|
206 |
+
search_query=""
|
207 |
+
)
|
208 |
|
209 |
# Run the workflow
|
210 |
final_state = self.workflow.invoke(initial_state)
|
211 |
+
return final_state.final_answer
|
212 |
|
213 |
except Exception as e:
|
214 |
print(f"Error in agent processing: {e}")
|
|
|
280 |
|
281 |
try:
|
282 |
# Initialize the state for this question
|
283 |
+
initial_state = AgentState(
|
284 |
+
question=question_text,
|
285 |
+
current_step="analyze",
|
286 |
+
tool_output="",
|
287 |
+
final_answer="",
|
288 |
+
history=[],
|
289 |
+
needs_more_info=False,
|
290 |
+
search_query=""
|
291 |
+
)
|
292 |
|
293 |
# Run the workflow for this question
|
294 |
print(f"\nProcessing question {task_id}: {question_text[:50]}...")
|
|
|
299 |
f"Step: {h['step']}\n" +
|
300 |
f"Input: {h.get('input', h.get('query', ''))}\n" +
|
301 |
f"Output: {h.get('output', h.get('results', h.get('error', '')))}"
|
302 |
+
for h in final_state.history
|
303 |
])
|
304 |
|
305 |
# Add to results
|
306 |
+
submitted_answer = final_state.final_answer
|
307 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
308 |
results_log.append({
|
309 |
"Task ID": task_id,
|
|
|
312 |
"Workflow History": workflow_history
|
313 |
})
|
314 |
|
315 |
+
print(f"Completed question {task_id} with {len(final_state.history)} workflow steps")
|
316 |
|
317 |
except Exception as e:
|
318 |
print(f"Error running agent workflow on task {task_id}: {e}")
|
requirements.txt
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
gradio
|
2 |
requests
|
3 |
-
langgraph
|
4 |
pydantic>=2.0.0
|
5 |
duckduckgo-search>=4.1.1
|
|
|
1 |
gradio
|
2 |
requests
|
3 |
+
langgraph==0.2.62
|
4 |
pydantic>=2.0.0
|
5 |
duckduckgo-search>=4.1.1
|