fdaudens HF Staff commited on
Commit
ab1ba02
·
verified ·
1 Parent(s): e9063dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -74
app.py CHANGED
@@ -23,6 +23,9 @@ from llama_index.core.memory import ChatMemoryBuffer
23
  from llama_index.readers.web import RssReader, SimpleWebPageReader
24
  from llama_index.core import SummaryIndex
25
 
 
 
 
26
  import subprocess
27
  subprocess.run(["playwright", "install"])
28
 
@@ -296,15 +299,14 @@ web_agent = AgentWorkflow.from_tools_or_functions(
296
  )
297
  ctx = Context(web_agent)
298
 
299
- # Async helper to run agent queries
300
  def run_query_sync(query: str):
301
  """Helper to run async agent.run in sync context."""
302
  return asyncio.get_event_loop().run_until_complete(
303
  web_agent.run(query, ctx=ctx)
304
  )
305
 
306
- stream_queue = asyncio.Queue()
307
-
308
  async def run_query(query: str):
309
  trace_id = f"agent-run-{uuid.uuid4().hex}"
310
  try:
@@ -313,90 +315,51 @@ async def run_query(query: str):
313
  session_id="web-agent-session",
314
  user_id=ANON_USER_ID,
315
  ):
316
- # Clear the queue before starting
317
- while not stream_queue.empty():
318
- try:
319
- stream_queue.get_nowait()
320
- except:
321
- pass
322
-
323
- # Add initial messages to the queue
324
- await stream_queue.put("🤔 Thinking about your question...\n\n")
325
-
326
- # The key is to patch each individual tool function to capture its usage
327
- original_functions = {}
328
 
329
- # Store original functions and patch each tool
330
- for tool in tools:
331
- tool_name = tool.metadata.name
332
- original_fn = tool.fn
333
- original_functions[tool_name] = original_fn
334
-
335
- # Create a wrapper function that will log the tool usage
336
- def create_wrapper(orig_fn, tool_name):
337
- async def wrapper(*args, **kwargs):
338
- # Log tool usage
339
- await stream_queue.put(f"🔧 Using tool: {tool_name}...\n")
340
-
341
- # Call original function
342
- if asyncio.iscoroutinefunction(orig_fn):
343
- result = await orig_fn(*args, **kwargs)
344
- else:
345
- result = orig_fn(*args, **kwargs)
346
-
347
- # Log result
348
- await stream_queue.put(f"📊 Got result from {tool_name}\n")
349
- return result
350
 
351
- return wrapper
352
-
353
- # Replace the function with our wrapped version
354
- tool.fn = create_wrapper(original_fn, tool_name)
355
-
356
- # Start the agent run
357
- await stream_queue.put("🧠 Planning approach...\n\n")
358
- task = asyncio.create_task(web_agent.run(query, ctx=ctx))
359
-
360
- # Stream updates while waiting for completion
361
- while not task.done():
362
- try:
363
- # Check if there's anything in the queue to yield
364
- if not stream_queue.empty():
365
- chunk = await stream_queue.get()
366
- yield chunk
367
  else:
368
- # Wait a bit and check again
369
- await asyncio.sleep(0.1)
370
- except Exception as e:
371
- yield f"\n⚠️ Error during streaming: {str(e)}\n"
372
 
373
- # Get the final result
374
- try:
375
- result = await task
376
- final_response = result.response if isinstance(result.response, str) else str(result.response)
377
-
378
- # Yield the final answer
379
- yield f"\n\n✅ Final answer: {final_response}"
380
- except Exception as e:
381
- yield f"\n\n❌ Error getting final result: {str(e)}"
382
-
383
- # Restore original functions
384
- for tool in tools:
385
- tool_name = tool.metadata.name
386
- if tool_name in original_functions:
387
- tool.fn = original_functions[tool_name]
388
  except Exception as e:
389
- yield f"❌ Error: {str(e)}"
390
  finally:
391
  instrumentor.flush()
392
 
393
- # Gradio interface function
394
  async def gradio_query(user_input, chat_history=None):
395
  history = chat_history or []
396
  history.append({"role": "user", "content": user_input})
397
 
398
  # Add initial assistant message
399
- history.append({"role": "assistant", "content": "Thinking..."})
400
  yield history, history
401
 
402
  # Get streaming response
 
23
  from llama_index.readers.web import RssReader, SimpleWebPageReader
24
  from llama_index.core import SummaryIndex
25
 
26
+ # Import the event types for streaming
27
+ from llama_index.core.agent.workflow import AgentStream, ToolCall, ToolCallResult
28
+
29
  import subprocess
30
  subprocess.run(["playwright", "install"])
31
 
 
299
  )
300
  ctx = Context(web_agent)
301
 
302
+ # Async helper to run agent queries (kept for compatibility)
303
  def run_query_sync(query: str):
304
  """Helper to run async agent.run in sync context."""
305
  return asyncio.get_event_loop().run_until_complete(
306
  web_agent.run(query, ctx=ctx)
307
  )
308
 
309
+ # Updated run_query function to use stream_events
 
310
  async def run_query(query: str):
311
  trace_id = f"agent-run-{uuid.uuid4().hex}"
312
  try:
 
315
  session_id="web-agent-session",
316
  user_id=ANON_USER_ID,
317
  ):
318
+ # Start the handler
319
+ handler = web_agent.run(query, ctx=ctx)
 
 
 
 
 
 
 
 
 
 
320
 
321
+ # Stream content
322
+ full_response = ""
323
+ async for event in handler.stream_events():
324
+ if isinstance(event, AgentStream):
325
+ # This is the text being generated
326
+ if event.delta:
327
+ yield event.delta
328
+ elif isinstance(event, ToolCall):
329
+ # A tool is being called
330
+ tool_name = event.data.get("name", "unknown tool")
331
+ yield f"\n\n🔧 Using tool: {tool_name}...\n"
332
+ elif isinstance(event, ToolCallResult):
333
+ # Result from a tool call
334
+ # Try to find the tool name in the event data
335
+ tool_name = "the tool"
336
+ if hasattr(event, "parent_id") and event.parent_id:
337
+ # This might help identify the parent tool call
338
+ tool_name = f"tool {event.parent_id}"
 
 
 
339
 
340
+ # Get the result from the event data
341
+ result = event.data.get("result", "")
342
+
343
+ # Truncate long results for display
344
+ if isinstance(result, str) and len(result) > 200:
345
+ result_preview = result[:200] + "... (truncated)"
 
 
 
 
 
 
 
 
 
 
346
  else:
347
+ result_preview = str(result)
348
+
349
+ yield f"\n📊 Got result from {tool_name}\n"
 
350
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  except Exception as e:
352
+ yield f"\n\n❌ Error: {str(e)}"
353
  finally:
354
  instrumentor.flush()
355
 
356
+ # Updated gradio_query function
357
  async def gradio_query(user_input, chat_history=None):
358
  history = chat_history or []
359
  history.append({"role": "user", "content": user_input})
360
 
361
  # Add initial assistant message
362
+ history.append({"role": "assistant", "content": "Processing..."})
363
  yield history, history
364
 
365
  # Get streaming response