naman1102 commited on
Commit
1c5f119
·
1 Parent(s): e73cfbd

req_pydantic

Browse files
Files changed (2) hide show
  1. app.py +66 -55
  2. 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 simple state
40
- workflow = StateGraph(dict)
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: Dict[str, Any]) -> str:
57
- if state.get('current_step') == 'calculator':
58
  return 'calculator'
59
- elif state.get('current_step') == 'search':
60
  return 'search'
61
- elif state.get('current_step') == 'final_answer':
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: Dict[str, Any]) -> Dict[str, Any]:
96
  """Analyze the question and determine the next step."""
97
- prompt = f"""Analyze this question and determine what needs to be done: {state['question']}
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['needs_more_info'] = analysis.get('needs_search', False)
112
- state['search_query'] = analysis.get('search_query', '')
113
 
114
  if analysis.get('needs_calculation', False):
115
- state['current_step'] = 'calculator'
116
- state['tool_output'] = str(analysis['calculation'])
117
  elif analysis.get('needs_search', False):
118
- state['current_step'] = 'search'
119
  else:
120
- state['current_step'] = 'final_answer'
121
 
122
  return state
123
 
124
- def _use_calculator(self, state: Dict[str, Any]) -> Dict[str, Any]:
125
  """Use the calculator tool."""
126
  try:
127
- result = self.calculator.invoke({"input": eval(state['tool_output'])})
128
- state['history'].append({
129
  'step': 'calculator',
130
- 'input': state['tool_output'],
131
  'output': str(result['output'].result)
132
  })
133
- state['current_step'] = 'final_answer'
134
  except Exception as e:
135
- state['history'].append({
136
  'step': 'calculator_error',
137
  'error': str(e)
138
  })
139
- state['current_step'] = 'final_answer'
140
  return state
141
 
142
- def _use_search(self, state: Dict[str, Any]) -> Dict[str, Any]:
143
  """Use the search tool."""
144
  try:
145
  result = self.search_tool.invoke({
146
  "input": {
147
- "query": state['search_query'],
148
  "max_results": 3
149
  }
150
  })
151
- state['history'].append({
152
  'step': 'search',
153
- 'query': state['search_query'],
154
  'results': [str(r) for r in result['output'].results]
155
  })
156
- state['needs_more_info'] = False
157
- state['current_step'] = 'final_answer'
158
  except Exception as e:
159
- state['history'].append({
160
  'step': 'search_error',
161
  'error': str(e)
162
  })
163
- state['current_step'] = 'final_answer'
164
  return state
165
 
166
- def _generate_final_answer(self, state: Dict[str, Any]) -> Dict[str, Any]:
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['history']])
170
 
171
- prompt = f"""Based on the following information and history, provide a final answer to the question: {state['question']}
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['final_answer'] = self._call_llm_api(prompt)
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
- 'question': question,
190
- 'current_step': 'analyze',
191
- 'tool_output': '',
192
- 'final_answer': '',
193
- 'history': [],
194
- 'needs_more_info': False,
195
- 'search_query': ''
196
- }
197
 
198
  # Run the workflow
199
  final_state = self.workflow.invoke(initial_state)
200
- return final_state['final_answer']
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
- 'question': question_text,
274
- 'current_step': 'analyze',
275
- 'tool_output': '',
276
- 'final_answer': '',
277
- 'history': [],
278
- 'needs_more_info': False,
279
- 'search_query': ''
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['history']
292
  ])
293
 
294
  # Add to results
295
- submitted_answer = final_state['final_answer']
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['history'])} workflow steps")
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>=0.0.10
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