-
-
Notifications
You must be signed in to change notification settings - Fork 755
Migrate from pyautogen to ag2 Library #1012
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?
Migrate from pyautogen to ag2 Library #1012
Conversation
…rror - Fix LLM._log_llm_config to properly check if tools is a list/tuple before iterating - Fix Agent.__init__ to wrap single callable tools in a list automatically - Resolves "'function' object is not iterable" error when using LLMGuardrail - Maintains full backward compatibility Fixes MervinPraison#876 Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
…s-batch-upload feat: Add 10 Grok4 Intelligent Agent Examples
- Created _check_all_tasks_completed() helper method to eliminate code duplication - Both async and sync workflow methods now use the same completion check logic - No functional changes, pure refactoring for better maintainability Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
- Extract numeric values from tool results for better clarity - Add explicit prompting for final answers after tool execution - Handle empty initial responses from Ollama with retry logic - Fix duplicate strip calls in response handling This improves Ollama's ability to: 1. Understand numeric values from tool results 2. Generate proper final answers instead of returning None 3. Avoid getting stuck in infinite loops Fixes the issue where Ollama was unable to properly chain tool calls for sequential operations like getting a stock price and multiplying it. Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
…871-20250714_005124 feat: Add Gemini structured output support
…875-20250714_005802 fix: Support GuardrailResult return type in guardrail functions (MervinPraison#875)
…878-20250714_005448 fix: prevent duplicate callback invocations in LLM response generation
…873-20250714_005616 fix: use LLM abstraction instead of hardcoded OpenAI in hierarchical process
- Remove explicitly prohibited hardcoded regex patterns - Move import re to top of file (PEP 8 compliance) - Extract duplicated message-building logic into helper method - Define prompt constants at class level for maintainability - Simplify tool result formatting without numeric extraction - Maintain backward compatibility and existing functionality Fixes code quality issues identified by automated review tools while ensuring compliance with explicit PR requirements. Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
- Renamed MultiModelAgent class to RouterAgent throughout codebase - Updated multi_model_agent.py -> router_agent.py - Updated all imports, exports, and references in: - src/praisonai-agents/praisonaiagents/agent/__init__.py - examples/python/agents/multi-provider-agent.py - examples/python/agents/MULTI_PROVIDER_README.md - src/praisonai-agents/test_multi_provider.py - RouterAgent better reflects the primary purpose of intelligent model routing - Maintains all existing functionality and backward compatibility Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
- Replace deprecated asyncio.get_event_loop() with asyncio.get_running_loop() - Fix event loop blocking issues in API and MCP server implementations - Improve async handling consistency across the codebase 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
… in llm.py - Remove redundant conditional expressions that were causing unnecessary repetition - Add intelligent final answer detection after tool execution - Prevent unnecessary tool execution loops when LLM provides substantive response 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
- Add callback_executed tracking in llm.py to prevent duplicate callbacks - Fix validation timing in agent.py for output_json/output_pydantic flows - Ensure guardrail validation runs even for JSON outputs - Improve interaction display logic to avoid redundant callbacks 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> Co-Authored-By: Mervin Praison <noreply@mervinpraison.com>
…-20250714_063758 fix: Improve Ollama sequential tool calling handling
…866-20250713_204435 feat: Add multi-provider/multi-model support with intelligent routing
…son#896) - Add agent_name, agent_role, agent_tools, task_name, task_description, task_id to callbacks - Update display_interaction() and adisplay_interaction() to accept new parameters - Enhance LLM.get_response() to accept and pass task context - Modify Agent.chat() to accept task parameters - Update task execution in agents.py to pass task information - Maintain backward compatibility with existing callbacks - Add test scripts to verify functionality Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com> 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
…874-20250714_005622 fix: prevent infinite loop in parallel task execution
- Remove Trafilatura from core praisonaiagents package - Create custom tool implementation in examples/python/tools/ - Update example to demonstrate custom tool usage with agents - Remove dependencies from pyproject.toml - Remove from tools __init__.py and README.md - Keep all functionality as standalone custom tool This change follows the request to not integrate into core package but provide as custom tool example instead. Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
Refactor tools parameter initialization to better handle falsy values while maintaining single function support. Changed from explicit None check to using ''tools or []'' pattern, which properly handles all falsy values (None, False, 0, "", etc.) without breaking existing functionality. This resolves backward compatibility regression where falsy values other than None were not handled correctly in the tools parameter. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
…7-20250718-1454 Fix: Add telemetry cleanup to execute() and aexecute() methods to prevent hanging
…9-20250718-1529 Fix: Add comprehensive telemetry cleanup to prevent agent termination hang
- Added comprehensive telemetry cleanup calls in agent.py at all return points - Ensures proper cleanup after guardrail validation failures - Prevents hanging during agent termination by forcing telemetry shutdown - Added test files to validate telemetry cleanup functionality - Addresses hanging issues in async agent execution flows 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Mervin Praison <mervin@praison.ai>
- Modified Agent.start() method to automatically consume the generator by default - Added return_generator=True parameter for backwards compatibility - Made MCP import optional to prevent import errors - Updated examples to demonstrate new behavior - Fixes issue where basic-agents.py would stop without producing output 🤖 Generated with [Claude Code](https://claude.ai/code) Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
…-1003-20250718-1604 Fix: Agent.start() now auto-consumes generator for better UX
- Replace 13 scattered _cleanup_telemetry() calls with single try...finally block - Ensure cleanup happens on ALL exit paths regardless of success/failure - Standardize test tolerances to 2 threads across all test files - Improve test error messages to show specific thread details - Maintain backward compatibility and all existing functionality - Reduce code duplication by 95% in chat method 🤖 Generated with Claude Code Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
…02-20250718-1556 PR MervinPraison#1002: Changes from Claude
…claude/pr-1002-20250718-1556 Revert "PR MervinPraison#1002: Changes from Claude"
…-20250718-1439 Fix: Correct indentation in chat method try-finally block
…andling - Simplified logging of parameters in debug mode for better clarity. - Enhanced error handling during LLM calls and reflections to ensure robust rollback mechanisms. - Improved structure for handling knowledge search and prompt normalization. - Reduced code duplication by integrating common functionalities into streamlined processes.
- Added timeout-based flush operation in MinimalTelemetry.shutdown() - Replaced blocking PostHog flush with threaded timeout approach - Prevents indefinite blocking during program termination - Maintains backward compatibility and data integrity - Fixes issue where PostHog queue.join() would hang on exit Resolves MervinPraison#1009 Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
- Add thread safety with shutdown locks to prevent concurrent shutdown calls - Fix double thread pool shutdown issue that could cause undefined behavior - Implement memory leak prevention with bounded metrics storage (max 1000 entries) - Replace unsafe daemon threads with ThreadPoolExecutor for better control - Increase flush timeout from 2s to 5s for improved reliability - Add comprehensive error handling with proper logging levels - Split shutdown logic into maintainable helper methods - Maintain full backward compatibility with existing API These changes address critical thread safety issues while preserving all existing functionality and ensuring reliable telemetry shutdown behavior. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
…-1009-20250718-1740 fix: prevent telemetry shutdown from hanging indefinitely
WalkthroughThe changes update the project configuration and integration test documentation to rename the dependency "pyautogen" to "ag2" while keeping the version and functionality unchanged. All references to "pyautogen" in dependency declarations and installation instructions are replaced with "ag2". No code or functional logic is modified. Changes
Possibly related PRs
Poem
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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.
Summary of Changes
Hello @AG2AI-Admin, 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 is a straightforward migration aimed at transitioning the codebase from the deprecated pyautogen library to its recommended successor, ag2. The primary goal is to ensure ongoing compatibility and leverage improvements in the ag2 ecosystem, as there are no syntax differences between the two libraries. The changes involve updating package dependencies and relevant documentation.
Highlights
- Dependency Migration: I've updated the
pyproject.tomlfile to replace thepyautogendependency withag2across various sections, including the mainautogendependency group and optional dependencies. This ensures the project now uses the newag2library. - Documentation Update: I've modified the
README.mdin the integration tests directory to reflect the newag2library. This includes updating installation instructions and troubleshooting tips, guiding users topip install ag2instead ofpyautogen.
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.
Footnotes
-
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. ↩
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 PR migrates the project from the deprecated pyautogen library to ag2. Suggestions have been made to improve the maintainability of the pyproject.toml by consolidating dependency definitions and to enhance the clarity of the testing documentation by providing more complete installation instructions.
| train = [] | ||
| crewai = ["crewai>=0.32.0", "praisonai-tools>=0.0.22"] | ||
| autogen = ["pyautogen==0.2.29", "praisonai-tools>=0.0.22", "crewai"] | ||
| autogen = ["ag2==0.2.29", "praisonai-tools>=0.0.22", "crewai"] |
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.
Consider consolidating dependency definitions. Optional dependencies (extras) are defined here in [project.optional-dependencies] and also in [tool.poetry.extras] (e.g., line 289). The [tool.poetry.extras] section is a legacy way of defining extras in Poetry and maintaining both can lead to inconsistencies. To improve maintainability, remove the [tool.poetry.extras] section entirely and rely only on [project.optional-dependencies].
| PyYAML = ">=6.0" | ||
| mcp = ">=1.6.0" | ||
| pyautogen = {version = "==0.2.29", optional = true} | ||
| ag2 = {version = "==0.2.29", optional = true} |
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.
For consistency and adherence to modern packaging standards (PEP 621), define all dependencies under the [project] table. This would mean moving dependencies from [tool.poetry.dependencies] to [project.dependencies] to centralize dependency management and make the pyproject.toml easier to understand and maintain.
| ### Required for AutoGen Tests: | ||
| ```bash | ||
| pip install pyautogen | ||
| pip install ag2 |
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.
| ImportError: No module named 'autogen' | ||
| ``` | ||
| **Solution:** Install the framework: `pip install pyautogen` | ||
| **Solution:** Install the framework: `pip install ag2` |
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 solution is incomplete. While pip install ag2 might resolve the ImportError for the autogen module, the tests require other dependencies as well. Point to the correct installation method for all test dependencies.
| **Solution:** Install the framework: `pip install ag2` | |
| **Solution:** Install the framework dependencies: `pip install .[autogen]` |
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.
Actionable comments posted: 0
🔭 Outside diff range comments (2)
src/praisonai/pyproject.toml (2)
128-133: Potential duplication with an existingpyautogenentry
ag2is added as an optional dependency, but ifpyautogenstill exists in this same table (or in any generated lock file) poetry will consider them two distinct packages and may install both.If
pyautogenis still present, drop it entirely:- pyautogen = {version = "==0.2.29", optional = true}
94-101: Purgepyautogenfrom lock files and regenerate dependenciesThe search still shows
pyautogenlocked in both Poetry and pip-compile outputs, which will pull in the old package alongsideag2:
- src/praisonai/uv.lock
• name = "pyautogen" (lines 4079, 4206, 4498)
• sdist / wheel entries for pyautogen-0.2.29 (lines 4513–4515)- src/praisonai/poetry.lock
• name = "pyautogen" (line 6485)
• wheel / tar.gz entries for pyautogen-0.5.3 (lines 6493–6494)
• extras autogen still includespyautogen(line 9720)Please regenerate your lock files to pick up the updated
ag2extras and drop all references topyautogen:
- Run
poetry lock(orpoetry lock --no-update)- Re-run your pip-compile or uv-tooling step to rebuild
uv.lockAfter that, double-check CI configs, Dockerfiles, docs, etc., for any hard-coded
pyautogenmentions.
🧹 Nitpick comments (2)
src/praisonai/pyproject.toml (1)
289-290: Keep extras list alphabetically sorted for readabilityPure nit: while touching this line you could sort the extras alphabetically to keep long lists tidy.
-autogen = ["ag2", "praisonai-tools", "crewai"] +autogen = ["ag2", "crewai", "praisonai-tools"]src/praisonai/tests/integration/README.md (1)
254-255: Stay consistent in troubleshooting sectionGood catch replacing the package name, but consider adding a note that
ag2provides theautogenmodule (if that’s the case) to avoid confusion for new contributors.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/praisonai/pyproject.toml(3 hunks)src/praisonai/tests/integration/README.md(2 hunks)
🧰 Additional context used
🧠 Learnings (2)
src/praisonai/pyproject.toml (3)
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-07-18T14:39:55.954Z
Learning: Applies to src/praisonai-agents/praisonaiagents/agent/**/*.py : Use the `Agent` class from `praisonaiagents/agent/` for creating agents, with parameters such as `name`, `role`, `goal`, `backstory`, `llm`, `self_reflect`, `min_reflect`, `max_reflect`, `tools`, `guardrail`, and `max_guardrail_retries`.
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-07-18T14:39:55.954Z
Learning: Applies to src/praisonai-agents/praisonaiagents/mcp/**/*.py : MCP integration code in `praisonaiagents/mcp/` should implement server-side tool protocol, SSE support, and dynamic tool registration.
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-07-18T14:39:55.954Z
Learning: Applies to src/praisonai-agents/praisonaiagents/**/*.py : Gracefully degrade functionality for optional dependencies (e.g., memory, knowledge, LLM providers) if they are not installed.
src/praisonai/tests/integration/README.md (5)
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-07-18T14:39:55.954Z
Learning: Applies to src/praisonai-agents/tests/**/*.py : All test files should be placed in the `tests/` directory and demonstrate specific usage patterns, serving as both test and documentation.
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-07-18T14:39:55.954Z
Learning: Applies to src/praisonai-agents/praisonaiagents/llm/**/*.py : LLM integration code in `praisonaiagents/llm/` should use the unified LiteLLM wrapper and support multiple providers (OpenAI, Anthropic, Gemini, DeepSeek, Ollama).
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-ts/.windsurfrules:0-0
Timestamp: 2025-07-18T14:40:53.720Z
Learning: Applies to src/praisonai-ts/src/tools/README.md : The 'src/tools/README.md' file should provide documentation for tool developers
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-07-18T14:39:55.954Z
Learning: Applies to src/praisonai-agents/praisonaiagents/agent/**/*.py : Use the `Agent` class from `praisonaiagents/agent/` for creating agents, with parameters such as `name`, `role`, `goal`, `backstory`, `llm`, `self_reflect`, `min_reflect`, `max_reflect`, `tools`, `guardrail`, and `max_guardrail_retries`.
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-07-18T14:39:55.954Z
Learning: Applies to src/praisonai-agents/praisonaiagents/**/*.py : Gracefully degrade functionality for optional dependencies (e.g., memory, knowledge, LLM providers) if they are not installed.
🔇 Additional comments (1)
src/praisonai/tests/integration/README.md (1)
148-149: Verify import path after package renameThe install instruction now points to
ag2, but the surrounding docs – and likely the tests – still refer to the module nameautogen.
Confirm thatimport autogenstill works after installingag2; if not, update test code and docs accordingly.
|
@claude review these changes, will this impact other areas ? |
|
Claude encountered an error —— View job I'll analyze this and get back to you. |
2 similar comments
|
Claude encountered an error —— View job I'll analyze this and get back to you. |
|
Claude encountered an error —— View job I'll analyze this and get back to you. |
|
@@ -91,7 +91,7 @@ call = [ |
|
@claude review these changes again , make those changes in the above branch, based on the proposal if no changes exists in the provided branch. Also create a new branch instead if no original source branch exists |
|
Claude encountered an error —— View job I'll analyze this and get back to you. |
Hey there! This is AG2 👋
First of all, thank you for using pyautogen! We've seen you're using pyautogen, and we're here to help you migrate to ag2.
This pull request is designed to help update this codebase by smoothly transitioning from the
pyautogenlibrary to the newag2library.Why the change?
pyautogenis being deprecated, andag2is now the recommended successor for ongoing development.The good news is, there is no syntax difference between pyautogen and ag2 – this migration primarily involves updating library imports and usage.
This update will ensure the project stays compatible with the latest tools and can benefit from all the improvements in the ag2 ecosystem.
Could you please take a moment to review and merge this at your earliest convenience? Your collaboration is much appreciated! Thank you!
Summary by CodeRabbit