Skip to content

Add multi-agent API functionality in multi-agents-api.py and `multi…#476

Merged
MervinPraison merged 1 commit intomainfrom
develop
May 14, 2025
Merged

Add multi-agent API functionality in multi-agents-api.py and `multi…#476
MervinPraison merged 1 commit intomainfrom
develop

Conversation

@MervinPraison
Copy link
Copy Markdown
Owner

@MervinPraison MervinPraison commented May 14, 2025

…-agents-group-api.py, increment version to 0.0.80 in pyproject.tomlanduv.lock, and enhance agent launch logic in agents.py` with improved endpoint management and healthcheck capabilities.

Summary by CodeRabbit

  • New Features
    • Introduced web services that allow users to interact with multi-agent systems for AI research and summarization tasks through dedicated API endpoints.
    • Users can access different agent groups via separate URLs for tailored information retrieval and summarization.
  • Enhancements
    • Added the ability to launch agent collections as API endpoints, enabling sequential query processing and easy integration.
  • Chores
    • Updated the project version to 0.0.80.

…-agents-group-api.py`, increment version to 0.0.80 in `pyproject.toml` and `uv.lock`, and enhance agent launch logic in `agents.py` with improved endpoint management and healthcheck capabilities.
@MervinPraison MervinPraison merged commit eb94124 into main May 14, 2025
4 of 6 checks passed
@netlify
Copy link
Copy Markdown

netlify bot commented May 14, 2025

Deploy Preview for praisonai canceled.

Name Link
🔨 Latest commit e50db48
🔍 Latest deploy log https://app.netlify.com/sites/praisonai/deploys/6824837352b246000814866a

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented May 14, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update introduces new scripts for launching multi-agent systems via the praisonaiagents framework, including group and single-agent endpoints. It adds a launch method to the core agent class to expose agents as FastAPI endpoints, manages server state for multiple endpoints, and increments the project version.

Changes

File(s) Change Summary
src/praisonai-agents/multi-agents-api.py, src/praisonai-agents/multi-agents-group-api.py New scripts defining and launching multi-agent systems with different agent groupings and web API endpoints using the praisonaiagents framework. Each script configures agents for research and summarization tasks and launches them as FastAPI services on specified paths and ports.
src/praisonai-agents/praisonaiagents/agents/agents.py Adds a launch method to the PraisonAIAgents class, enabling agents to be served as FastAPI endpoints. Handles sequential query processing, endpoint registration, server state management, and background server startup. Introduces global variables for shared app instances and endpoint tracking.
src/praisonai-agents/pyproject.toml Updates the project version from 0.0.79 to 0.0.80. No other configuration changes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FastAPI Server
    participant Agents Collection
    participant Research Agent
    participant Summarise Agent

    User->>FastAPI Server: POST /agents with query
    FastAPI Server->>Agents Collection: Receive query
    Agents Collection->>Research Agent: Process query (e.g., search AI 2024)
    Research Agent-->>Agents Collection: Research result
    Agents Collection->>Summarise Agent: Summarize research result
    Summarise Agent-->>Agents Collection: Summary points
    Agents Collection-->>FastAPI Server: Chain of agent results
    FastAPI Server-->>User: JSON response with results
Loading

Suggested labels

Review effort 2/5

Poem

🐇
A warren of agents, now ready to serve,
With research and summaries, they never lose nerve!
Endpoints are hopping, on port thirty-thirty,
FastAPI magic—responses come flirty.
With a version hop, and new code to show,
This rabbit says: onward, let the queries flow!

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fed7ac5 and e50db48.

⛔ Files ignored due to path filters (1)
  • src/praisonai-agents/uv.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • src/praisonai-agents/multi-agents-api.py (1 hunks)
  • src/praisonai-agents/multi-agents-group-api.py (1 hunks)
  • src/praisonai-agents/praisonaiagents/agents/agents.py (2 hunks)
  • src/praisonai-agents/pyproject.toml (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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>, please review it.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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
Copy Markdown
Contributor

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

Hello @MervinPraison, 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!

Summary of Changes

This pull request introduces multi-agent API functionality, enhancing the praisonaiagents library. It adds new API endpoints for launching and interacting with groups of agents. Specifically, it creates multi-agents-api.py and multi-agents-group-api.py to define agent configurations and launch them as API services. The agents.py file is modified to include improved endpoint management and health check capabilities. The version number is also incremented from 0.0.79 to 0.0.80 in pyproject.toml and uv.lock.

Highlights

  • Multi-Agent API Creation: Introduces multi-agents-api.py and multi-agents-group-api.py to define and launch groups of agents as API endpoints.
  • Enhanced Agent Launch Logic: Modifies agents.py to include improved endpoint management, health check capabilities, and better handling of FastAPI dependencies.
  • Version Increment: Increments the library version from 0.0.79 to 0.0.80 in pyproject.toml and uv.lock.

Changelog

Click here to see the changelog
  • src/praisonai-agents/multi-agents-api.py
    • Creates a new file to define and launch a research agent and a summarization agent as a single API endpoint.
    • Defines a research agent with internet search tool and a summarization agent.
    • Launches the agents on port 3030 at the /agents path.
  • src/praisonai-agents/multi-agents-group-api.py
    • Creates a new file to define and launch multiple groups of agents as separate API endpoints.
    • Defines a research agent and a summarization agent, then creates two agent groups.
    • Launches the first group on port 3030 at the /agents path and the second group at the /agents2 path.
  • src/praisonai-agents/praisonaiagents/agents/agents.py
    • Adds global variables to manage shared servers, registered endpoints, and shared FastAPI apps to handle multiple agent groups.
    • Introduces a launch method to launch agents as a single API endpoint, processing queries sequentially through all agents.
    • Includes error handling, dependency checks (FastAPI, uvicorn), and dynamic endpoint registration.
    • Adds health check endpoint at /health.
    • Adds root endpoint with welcome message at /.
    • Handles both direct JSON and form data for queries.
    • Starts the server in a separate thread to avoid blocking the main thread.
    • Detects if it's the last launch call in the script and blocks the main thread to keep the server alive.
  • src/praisonai-agents/pyproject.toml
    • Increments the version number from 0.0.79 to 0.0.80.
  • src/praisonai-agents/uv.lock
    • Updates the version number from 0.0.79 to 0.0.80 to match the pyproject.toml file.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

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 issue 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 is currently in preview and 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 to provide feedback.

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.


Agents in code, a digital dance,
Each with a task, a focused trance.
APIs hum, a network's grace,
Solving problems at a rapid pace.

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
Copy Markdown
Contributor

@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

The pull request introduces multi-agent API functionality, enhances agent launch logic, and increments the project version. The new launch method in agents.py is comprehensive, but there are areas where improvements can be made to enhance maintainability and error handling. The addition of new API files is a good step towards providing more accessibility to the agents.

Summary of Findings

  • Global Variable Naming: The global variables for managing shared servers could benefit from more descriptive names and explicit type hinting using typing.Dict.
  • Exception Handling: The except block in the handle_query function is too broad and should catch specific exceptions for better error handling.
  • Path Conflict Resolution: The path conflict resolution strategy is basic. Consider suggesting available paths or providing a configuration option for specifying a different path.
  • Agent Error Handling: The error handling within the agent processing loop could be improved to allow for halting or retrying agents instead of always continuing with the original input.
  • Launch Detection Logic: The logic for detecting the last launch() call is complex and potentially unreliable. A more explicit method for signaling completion should be considered.

Merge Readiness

The pull request introduces valuable functionality but requires attention to error handling, naming conventions, and conflict resolution. Addressing these points will improve the code's robustness and maintainability. I am unable to directly approve this pull request, and recommend that others review and approve this code before merging. At a minimum, the HIGH severity comments should be addressed before merging.

Comment on lines +21 to +23
_agents_server_started = {} # Dict of port -> started boolean
_agents_registered_endpoints = {} # Dict of port -> Dict of path -> endpoint_id
_agents_shared_apps = {} # Dict of port -> FastAPI app
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Consider using a more descriptive name for these global variables to improve readability and avoid potential naming conflicts. Also, consider using typing.Dict for type hinting to be more explicit about the types involved.1

Style Guide References

Suggested change
_agents_server_started = {} # Dict of port -> started boolean
_agents_registered_endpoints = {} # Dict of port -> Dict of path -> endpoint_id
_agents_shared_apps = {} # Dict of port -> FastAPI app
agent_servers_started: typing.Dict[int, bool] = {}
agent_registered_endpoints: typing.Dict[int, typing.Dict[str, str]] = {}
agent_shared_apps: typing.Dict[int, FastAPI] = {}

Footnotes

  1. Use descriptive names for variables to improve readability and maintainability. Use typing.Dict for explicit type hinting.

Comment on lines +963 to +972

# Check if path is already registered for this port
if path in _agents_registered_endpoints[port]:
logging.warning(f"Path '{path}' is already registered on port {port}. Please use a different path.")
print(f"⚠️ Warning: Path '{path}' is already registered on port {port}.")
# Use a modified path to avoid conflicts
original_path = path
instance_id = str(uuid.uuid4())[:6]
path = f"{path}_{instance_id}"
logging.warning(f"Using '{path}' instead of '{original_path}'")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The logic for handling path conflicts could be improved. Instead of simply appending a UUID, consider implementing a more user-friendly approach, such as suggesting available paths or providing a configuration option to specify a different path.1

# Suggest available paths or provide a configuration option
logging.warning(f"Path '{path}' is already registered on port {port}. Please use a different path or configure a unique path.")
print(f"⚠️ Warning: Path '{path}' is already registered on port {port}. Please use a different path or configure a unique path.")
return  # Stop further execution to avoid conflicts

Style Guide References

Footnotes

  1. Implement user-friendly conflict resolution strategies.

Comment on lines +988 to +994
query = request_data["query"]
except:
# Fallback to form data or query params
form_data = await request.form()
if "query" in form_data:
query = form_data["query"]
else:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The except block is too broad. It should catch specific exceptions like json.JSONDecodeError and KeyError to handle different error scenarios more precisely. This will help in debugging and prevent masking unexpected errors.1

except json.JSONDecodeError:
    logging.error("Invalid JSON format in request", exc_info=True)
    raise HTTPException(status_code=400, detail="Invalid JSON format in request")
except KeyError:
    logging.error("Missing 'query' field in request", exc_info=True)
    raise HTTPException(status_code=400, detail="Missing 'query' field in request")

Style Guide References

Footnotes

  1. Catch specific exceptions to handle different error scenarios more precisely.

Comment on lines +1021 to +1027
current_input = response
except Exception as e:
logging.error(f"Error with agent {agent.name}: {str(e)}", exc_info=True)
results.append({
"agent": agent.name,
"error": str(e)
})
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Instead of continuing with the original input when an agent encounters an error, consider adding a mechanism to halt the sequence or retry the agent with a modified input. This could prevent cascading errors and improve the overall reliability of the multi-agent system.1

except Exception as e:
    logging.error(f"Error with agent {agent.name}: {str(e)}", exc_info=True)
    results.append({
        "agent": agent.name,
        "error": str(e)
    })
    # Option to halt or retry instead of continuing
    break  # Example: Halt on error

Style Guide References

Footnotes

  1. Implement mechanisms to handle agent errors and prevent cascading failures.

Comment on lines +1077 to +1110

# If this is called from a Python script (not interactive), try to detect if it's the last launch call
if len(stack) > 1 and stack[1].filename.endswith('.py'):
caller_frame = stack[1]
caller_line = caller_frame.lineno

try:
# Read the file to check if there are more launch calls after this one
with open(caller_frame.filename, 'r') as f:
lines = f.readlines()

# Check if there are more launch() calls after the current line
has_more_launches = False
for line in lines[caller_line:]:
if '.launch(' in line and not line.strip().startswith('#'):
has_more_launches = True
break

# If this is the last launch call, block the main thread
if not has_more_launches:
try:
print("\nAll agents registered. Press Ctrl+C to stop the servers.")
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\nServers stopped")
except Exception as e:
# If something goes wrong with detection, block anyway to be safe
logging.error(f"Error in launch detection: {e}")
try:
print("\nKeeping servers alive. Press Ctrl+C to stop.")
while True:
time.sleep(1)
except KeyboardInterrupt:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The logic for detecting the last launch() call is complex and might not be reliable in all scenarios. Consider providing a more explicit way for the user to signal that all agents have been registered, such as a dedicated function call or a configuration option. This would make the code more robust and easier to understand.1

# Provide a dedicated function or configuration option
print("\nAll agents registered. Press Ctrl+C to stop the servers.")
while True:
    time.sleep(1)

Style Guide References

Footnotes

  1. Provide explicit mechanisms for signaling the completion of agent registration.

@coderabbitai coderabbitai bot mentioned this pull request May 14, 2025
shaneholloman pushed a commit to shaneholloman/praisonai that referenced this pull request Feb 4, 2026
Add multi-agent API functionality in `multi-agents-api.py` and `multi…
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