Skip to content

Added streaming support for tool call agent #189

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

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

Conversation

shivsak
Copy link
Contributor

@shivsak shivsak commented Mar 13, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced tool operations with real-time streaming updates and improved feedback.
    • Revised guidelines for research execution to ensure clear, fact-based outcomes.
  • Bug Fixes

    • Refined processing of evaluation data to prevent unexpected errors.
    • Improved logging and error handlers to offer clearer insights during tool execution.

Copy link
Contributor

coderabbitai bot commented Mar 13, 2025

Walkthrough

This pull request updates two primary components. In the ResearchAgent class, the _evaluate_progress method now iterates over a designated "evaluation" key and the _synthesize_findings method includes a mandatory guideline to report only factual data. In the ToolCallAgent class, a new logging mechanism with a StreamLogHandler is implemented, error logging is enhanced, and an asynchronous execute_stream method is added for streaming JSON responses. A redundant print statement has been removed, and public API declarations remain unchanged.

Changes

File(s) Change Summary
athina/…/research_agent_step.py - Modified _evaluate_progress to iterate over the "evaluation" key in updated statements.
- Updated _synthesize_findings to include factual reporting guidelines.
- Removed extraneous print statement in the execute method.
athina/…/tool_call_agent.py - Introduced StreamLogHandler for improved logging.
- Standardized step result creation via _create_step_result.
- Enhanced error logging for dependencies and input validation in the execute method.
- Added asynchronous execute_stream method to yield JSON responses with status updates and logs.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant Agent as ToolCallAgent
  participant Logger
  
  Client->>Agent: execute_stream(input_data)
  Agent->>Logger: Log initialization & dependency checks
  Agent->>Agent: Initialize LLM and Composio tools
  Agent->>Logger: Log action processing stages
  Agent-->>Client: Yield JSON response (status & logs)
Loading

Possibly related PRs

Suggested reviewers

  • vivek-athina

Poem

I'm a rabbit, hopping by,
Changes made, oh me, oh my!
Logs now leap, facts stay true,
Code refined for a better view.
With streams that flow like a gentle breeze,
I nibble through bugs with rabbit ease.
Happy coding, in forest of keys!

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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
Contributor

@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: 1

🧹 Nitpick comments (1)
athina/steps/tool_call_agent.py (1)

1-2: Remove unused imports for cleanliness.
Static analysis indicates Union and TypedDict are never used. Consider removing them:

- from typing import Any, Dict, Union, Optional, List, AsyncGenerator, Literal, TypedDict
+ from typing import Any, Dict, Optional, List, AsyncGenerator, Literal
🧰 Tools
🪛 Ruff (0.8.2)

2-2: typing.Union imported but unused

Remove unused import

(F401)


2-2: typing.TypedDict imported but unused

Remove unused import

(F401)

🪛 GitHub Actions: Flake8, Pyflakes and Compileall Linter

[warning] 2-1: Imported modules are unused: 'typing.Union', 'typing.TypedDict', 'os'.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bc120e2 and a308846.

📒 Files selected for processing (2)
  • athina/steps/research_agent_step.py (3 hunks)
  • athina/steps/tool_call_agent.py (12 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
athina/steps/tool_call_agent.py

2-2: typing.Union imported but unused

Remove unused import

(F401)


2-2: typing.TypedDict imported but unused

Remove unused import

(F401)


73-73: Local variable execution_time is assigned to but never used

Remove assignment to unused variable execution_time

(F841)

🪛 GitHub Actions: MyPy static type checker
athina/steps/tool_call_agent.py

[error] 64-64: Signature of "_create_step_result" incompatible with supertype "Step" [override]


[error] 64-64: This violates the Liskov substitution principle


[error] 64-64: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides


[error] 161-161: Signature of "answer" incompatible with supertype "QuestionAnswerer" [override]


[error] 161-161: This violates the Liskov substitution principle


[error] 161-161: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides


[error] 188-188: Signature of "_create_step_result" incompatible with supertype "Step" [override]


[error] 188-188: This violates the Liskov substitution principle


[error] 188-188: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides


[error] 310-310: Library stubs not installed for "requests" [import-untyped]

🪛 GitHub Actions: Flake8, Pyflakes and Compileall Linter
athina/steps/tool_call_agent.py

[warning] 2-1: Imported modules are unused: 'typing.Union', 'typing.TypedDict', 'os'.


[warning] 73-9: Local variable 'execution_time' is assigned to but never used.

athina/steps/research_agent_step.py

[error] 331-331: F541 f-string is missing placeholders


[error] 407-407: F541 f-string is missing placeholders


[error] 448-448: F541 f-string is missing placeholders


[error] 659-659: F541 f-string is missing placeholders


[error] 969-969: F541 f-string is missing placeholders

🔇 Additional comments (19)
athina/steps/research_agent_step.py (3)

5-5: No concerns regarding added import types.
This import addition appears to be used later in the code for asynchronous operations, and it aligns with the function signatures referencing AsyncGenerator.


449-449: Safer iteration using .get().
Using updated_statements.get("evaluation", []) helps avoid KeyError if "evaluation" is absent.


512-512: Factual integrity guideline is clear.
This explicit requirement to avoid inventing information aligns with the broader project goals.

athina/steps/tool_call_agent.py (16)

4-4: No issues with JSON import.
This import is legitimately used later for serialization.


15-17: Logger setup looks good.
Defining a module-level logger early is a standard best practice.

🧰 Tools
🪛 GitHub Actions: Flake8, Pyflakes and Compileall Linter

[warning] 73-9: Local variable 'execution_time' is assigned to but never used.


19-32: StreamLogHandler implementation is straightforward.
This class correctly accumulates log messages for retrieval, which is helpful for streaming logs.

🧰 Tools
🪛 GitHub Actions: Flake8, Pyflakes and Compileall Linter

[warning] 73-9: Local variable 'execution_time' is assigned to but never used.


52-52: New attribute for log handler is appropriate.
Storing the stream_log_handler at the class level ensures easy access throughout.

🧰 Tools
🪛 GitHub Actions: Flake8, Pyflakes and Compileall Linter

[warning] 73-9: Local variable 'execution_time' is assigned to but never used.


54-56: Pydantic Config update is fine.
Allowing arbitrary types is often necessary when dealing with complex objects like log handlers.

🧰 Tools
🪛 GitHub Actions: Flake8, Pyflakes and Compileall Linter

[warning] 73-9: Local variable 'execution_time' is assigned to but never used.


57-62: Logging initialization in init method makes sense.
Ensures the log handler is attached once per agent instance.

🧰 Tools
🪛 GitHub Actions: Flake8, Pyflakes and Compileall Linter

[warning] 73-9: Local variable 'execution_time' is assigned to but never used.


82-94: Robust import error handling.
Importing composio_llamaindex inside this block ensures graceful failures when the dependency is missing.


122-132: Clear “no actions” error path.
Returning an error early prevents malformed agent executions.


135-145: Prompt validation is solid.
This block properly halts execution if no prompt is provided.


149-150: Environment loading is acceptable.
Loading environment variables here is consistent with typical usage.


154-157: Entity-specific toolset initialization.
Allowing a custom entity_id further tailors the toolset usage; the logging is clear.


180-184: Verbose logging for actions.
Notifying how many actions/tools are retrieved helps with debugging the agent’s tool usage.


188-189: Graceful failure when no valid tools are found.
Immediate error response ensures no futile attempts to run the agent without tools.

🧰 Tools
🪛 GitHub Actions: MyPy static type checker

[error] 188-188: Signature of "_create_step_result" incompatible with supertype "Step" [override]


[error] 188-188: This violates the Liskov substitution principle


[error] 188-188: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides


244-253: Successful result encapsulation.
Returning a standardized payload fosters consistency across step results.


261-264: Comprehensive error response.
Capturing stack traces in metadata is helpful for debugging.


276-585: Asynchronous streaming method is well-structured.
This large addition implements detailed log streaming and status updates. The incremental yields effectively inform callers about the agent’s progress.

🧰 Tools
🪛 GitHub Actions: MyPy static type checker

[error] 310-310: Library stubs not installed for "requests" [import-untyped]

Comment on lines +64 to +71
def _create_step_result(
self,
status: Literal["success", "error"],
data: Any,
start_time: float,
metadata: Optional[Dict[str, Any]] = None,
) -> StepResult:
"""Create a standardized step result object."""
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Address signature incompatibility & unused variable.
MyPy flags this override as incompatible with the parent Step class. Verify the parent’s required signature or rename this method if it's not meant to override. Also, consider using or removing execution_time at line 73:

 def _create_step_result(
     self,
     status: Literal["success", "error"],
     data: Any,
     start_time: float,
     metadata: Optional[Dict[str, Any]] = None,
 ) -> StepResult:
     end_time = time.perf_counter()
-    execution_time = end_time - start_time
+    # Remove or utilize execution_time if required by the design
     
     return {
       "status": status,
       "data": str(data),
       "metadata": metadata or {},
     }
📝 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
def _create_step_result(
self,
status: Literal["success", "error"],
data: Any,
start_time: float,
metadata: Optional[Dict[str, Any]] = None,
) -> StepResult:
"""Create a standardized step result object."""
def _create_step_result(
self,
status: Literal["success", "error"],
data: Any,
start_time: float,
metadata: Optional[Dict[str, Any]] = None,
) -> StepResult:
"""Create a standardized step result object."""
end_time = time.perf_counter()
# Remove or utilize execution_time if required by the design
return {
"status": status,
"data": str(data),
"metadata": metadata or {},
}
🧰 Tools
🪛 GitHub Actions: MyPy static type checker

[error] 64-64: Signature of "_create_step_result" incompatible with supertype "Step" [override]


[error] 64-64: This violates the Liskov substitution principle


[error] 64-64: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides

🪛 GitHub Actions: Flake8, Pyflakes and Compileall Linter

[warning] 73-9: Local variable 'execution_time' is assigned to but never used.

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