-
Notifications
You must be signed in to change notification settings - Fork 113
[Handler, Context, Env]background_task #697
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
# Conflicts: # aworld/utils/run_util.py
…into feat/background_task
…into feat/background_task
Summary of ChangesHello @SzekiHou, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the agent framework by introducing a robust background task execution mechanism. It refactors core components to support non-blocking operations and integrates a new handler for seamless result merging. The update also improves sandbox configurability through a fluent builder pattern and enables real-time tool result streaming via WebSockets, creating a more dynamic and responsive environment for agents. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces a significant new feature for handling background tasks, which is a great addition for long-running operations. The changes span across agents, context, memory, and handlers, and include a new env_channel for communication. The introduction of the SandboxBuilder is also a nice API improvement.
My review focuses on a few key areas:
- Encapsulation and Design: In a couple of places, internal attributes of classes are accessed directly. I've suggested refactoring these to use public methods to improve encapsulation.
- Robustness: I found a potential
UnboundLocalErrorand suggested a fix. - Efficiency: I've pointed out an inefficient list removal pattern and suggested a more performant alternative.
- Asynchronous Programming Patterns: There's a polling loop using
asyncio.sleepwhich is generally an anti-pattern. I've raised this as a high-severity issue and suggested exploring a more event-driven approach, which seems to be partially implemented already with the new background task handlers. - Code Clarity: I've identified a couple of instances of dead code that should be removed.
Overall, this is a substantial and well-thought-out feature. Addressing these points will help improve the robustness and maintainability of the new implementation.
aworld/agents/llm_agent.py
Outdated
| try: | ||
| messages = await self.async_messages_transform(image_urls=images, observation=observation, message=message) | ||
| except Exception as e: | ||
| logger.error(f"Failed to transform llm messages: {e}. {traceback.format_exc()}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If an exception occurs in this try block, the messages variable will not be assigned. The code then proceeds to self._process_messages(messages=messages, ...) on line 788, which will raise an UnboundLocalError. You should initialize messages to a sensible default (e.g., None or []) before this try block to prevent this issue.
| while message.context.has_pending_background_tasks(agent_id=agent_name, parent_task_id=message.context.task_id): | ||
| await asyncio.sleep(1) | ||
| i += 1 | ||
| logger.info(f"{agent_name} is waiting pending background_tasks#{i}") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This while loop uses asyncio.sleep(1) to poll for the completion of background tasks. This is an anti-pattern in asynchronous programming as it blocks the handler and is inefficient. The new BackgroundTaskHandler seems designed to handle completions in an event-driven way. It would be better to leverage that mechanism. For instance, the agent could enter a "waiting" state and be re-activated by an event when the background tasks are done, rather than actively polling in a loop.
aworld/agents/llm_agent.py
Outdated
| if hasattr(memory, 'memory_store') and hasattr(memory.memory_store, 'pending_memory_items'): | ||
| filters = self._build_memory_filters(self.context) | ||
| # Filter out pending items for current task | ||
| pending_items = [item for item in memory.memory_store.pending_memory_items | ||
| if memory.memory_store._filter_memory_item(item, filters)] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The code directly accesses internal attributes of the memory store (memory.memory_store.pending_memory_items) and calls a protected method (_filter_memory_item). This breaks encapsulation and makes the code brittle to changes in the memory store's implementation. It would be better to add a public method to the InMemoryMemoryStore class (e.g., has_pending_items(filters) -> bool) to encapsulate this logic. This would make the agent code cleaner and less coupled to the memory store's internal implementation.
aworld/memory/main.py
Outdated
| def load_pending_memory(self, filters: dict = None): | ||
| filtered_pending_items = [item for item in self.pending_memory_items if self._filter_memory_item(item, filters)] | ||
| if filtered_pending_items: | ||
| for item in filtered_pending_items: | ||
| item.created_at = datetime.now().isoformat() | ||
| self.memory_items.append(item) | ||
| self.pending_memory_items.remove(item) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current implementation of load_pending_memory modifies self.pending_memory_items by calling .remove(item) inside a loop. For a list, remove() has a time complexity of O(n), making the overall operation potentially O(n^2) in the worst case if many items are moved. A more efficient approach would be to build a new list of remaining items, avoiding repeated searches for removal.
| def load_pending_memory(self, filters: dict = None): | |
| filtered_pending_items = [item for item in self.pending_memory_items if self._filter_memory_item(item, filters)] | |
| if filtered_pending_items: | |
| for item in filtered_pending_items: | |
| item.created_at = datetime.now().isoformat() | |
| self.memory_items.append(item) | |
| self.pending_memory_items.remove(item) | |
| def load_pending_memory(self, filters: dict = None): | |
| items_to_move = [] | |
| remaining_items = [] | |
| for item in self.pending_memory_items: | |
| if self._filter_memory_item(item, filters): | |
| item.created_at = datetime.now().isoformat() | |
| items_to_move.append(item) | |
| else: | |
| remaining_items.append(item) | |
| if items_to_move: | |
| self.memory_items.extend(items_to_move) | |
| self.pending_memory_items = remaining_items |
| for pre_k, _ in predecessor.items(): | ||
| if pre_k == agent_name: | ||
| all_input[agent_name] = action.policy_info | ||
| pre_finished = agent.finished |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| if False: | ||
| yield message |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No description provided.