ESkuratov commited on
Commit
2139c78
·
1 Parent(s): 9bd34a5

update app agent

Browse files
Files changed (2) hide show
  1. agent.py +7 -35
  2. app.py +3 -32
agent.py CHANGED
@@ -163,6 +163,10 @@ def _route(state):
163
  return "tool"
164
 
165
  def rewoo_graph():
 
 
 
 
166
  graph = StateGraph(ReWOO)
167
  graph.add_node("plan", get_plan)
168
  graph.add_node("tool", tool_execution)
@@ -174,7 +178,7 @@ def rewoo_graph():
174
 
175
  compiled_graph = graph.compile()
176
 
177
- # Create a wrapper that initializes missing state fields and handles recursion
178
  def wrapped_invoke(state_dict):
179
  # Ensure all required fields are initialized
180
  if "messages" not in state_dict:
@@ -188,40 +192,8 @@ def rewoo_graph():
188
  if "current_step" not in state_dict:
189
  state_dict["current_step"] = 0
190
 
191
- # Add max steps protection
192
- max_steps = 10 # Set reasonable limit to prevent infinite loops
193
-
194
- # Store original invoke function
195
- original_invoke = compiled_graph.invoke
196
-
197
- def safe_invoke(state):
198
- # Check if we've reached max steps
199
- if state.get("current_step", 0) >= max_steps:
200
- print(f"Reached maximum steps limit of {max_steps}")
201
- # Force the graph to solve with what it has
202
- if "steps" in state and "results" in state:
203
- result = solve(state)
204
- return {**state, **result}
205
- return {**state, "result": f"Processing exceeded {max_steps} steps. Task may be too complex."}
206
-
207
- # Update step counter
208
- state["current_step"] = state.get("current_step", 0) + 1
209
-
210
- # Call the original invoke with protection
211
- try:
212
- return original_invoke(state)
213
- except RuntimeError as e:
214
- if "maximum recursion depth exceeded" in str(e):
215
- print("Recursion limit encountered, forcing solution")
216
- # Force a solution
217
- if "steps" in state and "results" in state:
218
- result = solve(state)
219
- return {**state, **result}
220
- return {**state, "result": "Encountered recursion error. Here's my best attempt with what I've processed so far."}
221
- raise # Re-raise if it's not a recursion error
222
-
223
- return safe_invoke(state_dict)
224
 
225
- # Replace the invoke method with our safer wrapper
226
  compiled_graph.invoke = wrapped_invoke
227
  return compiled_graph
 
163
  return "tool"
164
 
165
  def rewoo_graph():
166
+ prompt_template = ChatPromptTemplate.from_messages([("user", prompt)])
167
+ global planner # Define planner at the global scope so get_plan can use it
168
+ planner = prompt_template | model
169
+
170
  graph = StateGraph(ReWOO)
171
  graph.add_node("plan", get_plan)
172
  graph.add_node("tool", tool_execution)
 
178
 
179
  compiled_graph = graph.compile()
180
 
181
+ # Create a wrapper that initializes missing state fields
182
  def wrapped_invoke(state_dict):
183
  # Ensure all required fields are initialized
184
  if "messages" not in state_dict:
 
192
  if "current_step" not in state_dict:
193
  state_dict["current_step"] = 0
194
 
195
+ return compiled_graph.invoke(state_dict)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
+ # Replace the invoke method with our wrapper
198
  compiled_graph.invoke = wrapped_invoke
199
  return compiled_graph
app.py CHANGED
@@ -20,44 +20,15 @@ class BasicAgent:
20
  def __call__(self, question: str) -> str:
21
  print(f"Agent received question (first 50 chars): {question[:50]}...")
22
  try:
23
- # Set timeout to prevent hanging on complex questions
24
- import signal
25
-
26
- def handler(signum, frame):
27
- raise TimeoutError("Processing took too long")
28
-
29
- # Set 30-second timeout (adjust as needed)
30
- signal.signal(signal.SIGALRM, handler)
31
- signal.alarm(30)
32
-
33
  result = self.graph.invoke({"task": question, "messages": [HumanMessage(content=question)]})
34
-
35
- # Cancel the alarm
36
- signal.alarm(0)
37
-
38
  answer = result.get('result', "No answer generated.")
39
-
40
- # Ensure we have a valid answer
41
- if not answer or answer == "No answer generated.":
42
- answer = "I wasn't able to generate a complete answer, but here's what I found: " + str(result.get('results', {}))
43
-
44
  return answer
45
-
46
  except RecursionError as e:
47
  print(f"Recursion error encountered: {e}")
48
- return "I'm sorry, but this question seems too complex for my current processing capabilities. Let me try to answer directly: " + model.invoke(question).content
49
-
50
- except TimeoutError as e:
51
- print(f"Timeout error: {e}")
52
- return "This question took too long to process. Let me answer directly: " + model.invoke(question).content
53
-
54
  except Exception as e:
55
- print(f"Error in agent processing: {type(e).__name__}: {e}")
56
- # Fall back to direct LLM call
57
- try:
58
- return "I encountered an error in my reasoning process. Let me answer directly: " + model.invoke(question).content
59
- except:
60
- return f"I experienced an error while processing this question and couldn't generate a fallback answer. Error: {str(e)}"
61
 
62
 
63
  def run_and_submit_all( profile: gr.OAuthProfile | None):
 
20
  def __call__(self, question: str) -> str:
21
  print(f"Agent received question (first 50 chars): {question[:50]}...")
22
  try:
 
 
 
 
 
 
 
 
 
 
23
  result = self.graph.invoke({"task": question, "messages": [HumanMessage(content=question)]})
 
 
 
 
24
  answer = result.get('result', "No answer generated.")
 
 
 
 
 
25
  return answer
 
26
  except RecursionError as e:
27
  print(f"Recursion error encountered: {e}")
28
+ return "I encountered a recursion error while processing this question. The task might be too complex for my current configuration."
 
 
 
 
 
29
  except Exception as e:
30
+ print(f"Error in agent processing: {e}")
31
+ return f"I encountered an error while processing this question: {str(e)}"
 
 
 
 
32
 
33
 
34
  def run_and_submit_all( profile: gr.OAuthProfile | None):