Skip to content

Conversation

@SzekiHou
Copy link
Collaborator

No description provided.

ahgpt and others added 30 commits December 16, 2025 19:59
# Conflicts:
#	aworld/utils/run_util.py
@gemini-code-assist
Copy link

Summary of Changes

Hello @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

  • Background Task Management: Introduced a new concept for managing background tasks across handlers, context, and environment components, enabling asynchronous and non-blocking operations within the agent framework.
  • Memory Integration for Pending Tasks: The LLMAgent now actively checks for and loads 'pending' memory items, which are specifically designed to temporarily store results from background tasks until the main agent is ready to process them.
  • Dedicated Background Task Handler: A new handler, BackgroundTaskHandler, has been added to efficiently process completion messages from background tasks, facilitating the 'hot-merging' of results directly into the main task context or triggering subsequent agent actions.
  • Fluent Sandbox Builder Pattern: Implemented a fluent API for constructing Sandbox instances, which allows for more readable and flexible configuration of environments, including the definition of agents and their execution modes.
  • Enhanced Sandbox Configuration: The Sandbox and BaseSandbox classes have been extended with new properties such as agents, streaming, env_content_name, and env_content, along with dynamic reinitialization capabilities to adapt to configuration changes.
  • MCP Server Environment Content Injection: The McpServers class now automatically injects context-specific environment content (e.g., task_id, session_id, agent_id) into tool call parameters, streamlining tool development and reducing boilerplate.
  • Real-time Tool Result Streaming: Integrated a new WebSocket-based communication channel (env_channel) to enable real-time streaming of tool results, particularly for background tasks, providing immediate feedback and dynamic task management.

🧠 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 Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a 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 UnboundLocalError and 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.sleep which 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.

Comment on lines 782 to 785
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()}")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Comment on lines +348 to +351
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}")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Comment on lines 552 to 556
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)]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Comment on lines 101 to 107
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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The variable pre_finished is assigned a value but is never used. This appears to be dead code and should be removed to improve clarity.

Comment on lines +107 to +108
if False:
yield message

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This if False: block contains code that will never be executed. This is dead code and should be removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants