Skip to content
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

Add stream output for Agent #835

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Add stream output for Agent #835

wants to merge 1 commit into from

Conversation

Undertone0809
Copy link
Owner

@Undertone0809 Undertone0809 commented Aug 3, 2024

Related to #833

Add stream output support for ToolAgent.

  • ToolAgent Class:

    • Add stream parameter to the run method.
    • Implement logic to handle the stream parameter.
    • Modify the _run method to support streaming output.
    • Raise error if stream=True and output_schema is not provided.
  • BaseAgent Class:

    • Add stream parameter to the run method.
    • Implement _run_stream method to handle streaming output.
  • Example:

    • Update example/agent/tool_agent_usage.py to demonstrate the usage of agent.run(..., stream=True).
  • Tests:

    • Add tests in tests/agents/test_tool_agent.py to verify the stream mode output functionality.

For more details, open the Copilot Workspace session.

Summary by CodeRabbit

  • New Features

    • Introduced streaming capabilities for the agent, allowing real-time output during execution.
    • Enhanced the tool agent to process multiple responses dynamically.
  • Bug Fixes

    • Added validation to ensure necessary parameters for streaming operations are provided.
  • Tests

    • Added a new test to validate the tool agent's behavior in stream mode.

Related to #833

Add stream output support for ToolAgent.

* **ToolAgent Class**:
  - Add `stream` parameter to the `run` method.
  - Implement logic to handle the `stream` parameter.
  - Modify the `_run` method to support streaming output.
  - Raise error if `stream=True` and `output_schema` is not provided.

* **BaseAgent Class**:
  - Add `stream` parameter to the `run` method.
  - Implement `_run_stream` method to handle streaming output.

* **Example**:
  - Update `example/agent/tool_agent_usage.py` to demonstrate the usage of `agent.run(..., stream=True)`.

* **Tests**:
  - Add tests in `tests/agents/test_tool_agent.py` to verify the stream mode output functionality.

---

For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/Undertone0809/promptulate/issues/833?shareId=XXXX-XXXX-XXXX-XXXX).
Copy link

coderabbitai bot commented Aug 3, 2024

Walkthrough

The recent changes enhance the functionality of the ToolAgent by introducing a streaming output feature. This allows the agent to yield intermediate responses in real-time during execution, improving user interaction and feedback. The method signatures have been updated to include a stream parameter, enabling more dynamic handling of outputs across various components within the agent system.

Changes

Files Change Summary
example/agent/tool_agent_usage.py Updated agent.run in main to use stream=True, enabling real-time response handling via iteration over outputs.
promptulate/agents/base.py Modified run method to accept stream parameter, invoking _run_stream for real-time output. Added _run_stream for streaming functionality.
promptulate/agents/tool_agent/agent.py Enhanced _run method with stream parameter to allow yielding results when streaming is enabled. Added validation for output_schema.
tests/agents/test_tool_agent.py Introduced test_stream_mode to validate the new streaming functionality of ToolAgent, ensuring responses are correctly processed.

Possibly related issues

  • Add stream output for Agent #833: This feature request aligns with the changes made, as it specifically calls for adding stream output capabilities to the ToolAgent, which is now implemented.

Poem

🐇 In a world of code where agents play,
Streams of wisdom dance and sway.
With each response a new delight,
Real-time magic, shining bright!
Hopping through the lines so keen,
Our tool now flows, a wondrous scene! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Outside diff range, codebase verification and nitpick comments (1)
promptulate/agents/base.py (1)

Line range hint 28-45:
LGTM! But fix the line length issues.

The changes to the run method correctly implement the streaming functionality. However, some lines exceed the maximum line length.

-        stream: bool = False,
+        stream: bool = False,
-            return self._run_stream(instruction, output_schema, examples, *args, **kwargs)
+            return self._run_stream(
+                instruction, output_schema, examples, *args, **kwargs
+            )
Tools
Ruff

44-44: Line too long (90 > 88)

(E501)

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 11b21d8 and a92d2e3.

Files selected for processing (4)
  • example/agent/tool_agent_usage.py (1 hunks)
  • promptulate/agents/base.py (4 hunks)
  • promptulate/agents/tool_agent/agent.py (2 hunks)
  • tests/agents/test_tool_agent.py (1 hunks)
Additional context used
Ruff
promptulate/agents/base.py

44-44: Line too long (90 > 88)

(E501)


91-91: Line too long (90 > 88)

(E501)

promptulate/agents/tool_agent/agent.py

122-122: Line too long (93 > 88)

(E501)

Additional comments not posted (5)
example/agent/tool_agent_usage.py (1)

13-14: LGTM! Verify the usage of agent.run with stream=True.

The changes correctly implement the streaming functionality. Ensure that the agent.run method supports streaming as expected.

Verification successful

LGTM! The agent.run method supports streaming with stream=True.

The implementation correctly handles the stream parameter and calls the _run_stream method when streaming is enabled.

  • promptulate/agents/base.py:
    • run method: Calls _run_stream when stream=True.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `agent.run` with `stream=True`.

# Test: Search for the implementation of `agent.run`.
rg --type python -A 5 $'def run'

Length of output: 64


Script:

#!/bin/bash
# Description: Verify the usage of `agent.run` with `stream=True`.

# Test: Search for the implementation of `agent.run`.
rg -A 5 'def run'

Length of output: 4917


Script:

#!/bin/bash
# Description: Verify the usage of `agent.run` with `stream=True` in `promptulate/agents/base.py`.

# Test: Search for the complete implementation of the `run` method in `promptulate/agents/base.py`.
rg -A 50 'def run' promptulate/agents/base.py

Length of output: 1616

tests/agents/test_tool_agent.py (1)

58-64: LGTM! The test for streaming mode is well-implemented.

The test_stream_mode function correctly validates the streaming functionality of the ToolAgent.

promptulate/agents/tool_agent/agent.py (3)

129-129: Update: Document new parameter.

The method documentation has been updated to include the new stream parameter.


134-135: Validation: Ensure output_schema is provided for streaming.

The code correctly raises a ValueError if stream=True and output_schema is not provided in kwargs.


181-183: Enhancement: Yield results for streaming.

The code correctly yields tool_result when stream is enabled, allowing for real-time output.

@@ -119,17 +119,21 @@ def current_date(self) -> str:
return f"Current date: {time.strftime('%Y-%m-%d %H:%M:%S')}"

def _run(
self, instruction: str, return_raw_data: bool = False, **kwargs
self, instruction: str, return_raw_data: bool = False, stream: bool = False, **kwargs
Copy link

Choose a reason for hiding this comment

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

Refactor: Break down long line.

The line exceeds the maximum line length of 88 characters. Refactor it to improve readability.

-    self, instruction: str, return_raw_data: bool = False, stream: bool = False, **kwargs
+    self, instruction: str, return_raw_data: bool = False, 
+    stream: bool = False, **kwargs
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
self, instruction: str, return_raw_data: bool = False, stream: bool = False, **kwargs
self, instruction: str, return_raw_data: bool = False,
stream: bool = False, **kwargs
Tools
Ruff

122-122: Line too long (93 > 88)

(E501)

Comment on lines +67 to +97
def _run_stream(
self,
instruction: str,
output_schema: Optional[type(BaseModel)] = None,
examples: Optional[List[BaseModel]] = None,
*args,
**kwargs,
) -> Generator[Any, None, None]:
"""Run the tool including specified function and hooks with streaming output"""
Hook.call_hook(
HookTable.ON_AGENT_START,
self,
instruction,
output_schema,
*args,
agent_type=self._agent_type,
**kwargs,
)

for result in self._run(instruction, *args, **kwargs):
# TODO: need to optimize
# if output_schema:
# formatter = OutputFormatter(output_schema, examples)
# prompt = (
# f"{formatter.get_formatted_instructions()}\n##User input:\n{result}"
# )
# json_response: str = self.get_llm()(prompt)
# yield formatter.formatting_result(json_response)
# else:
yield result

Copy link

Choose a reason for hiding this comment

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

LGTM! Address the TODO comment.

The _run_stream method correctly handles streaming output. However, there is a TODO comment indicating a need for optimization.

Do you want me to help optimize this method or open a GitHub issue to track this task?

Tools
Ruff

91-91: Line too long (90 > 88)

(E501)

# if output_schema:
# formatter = OutputFormatter(output_schema, examples)
# prompt = (
# f"{formatter.get_formatted_instructions()}\n##User input:\n{result}"
Copy link

Choose a reason for hiding this comment

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

Fix the line length issue.

The line exceeds the maximum line length.

-            #         f"{formatter.get_formatted_instructions()}\n##User input:\n{result}"
+            #         f"{formatter.get_formatted_instructions()}\n##User input:\n{result}"

Committable suggestion was skipped due to low confidence.

Tools
Ruff

91-91: Line too long (90 > 88)

(E501)

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.

1 participant