Skip to content

Commit a4158b7

Browse files
Merge pull request #936 from MervinPraison/claude/issue-935-20250715_170032
feat: Add AutoGen v0.4 support with backward compatibility
2 parents b35d15f + 8d2e261 commit a4158b7

File tree

3 files changed

+176
-9
lines changed

3 files changed

+176
-9
lines changed

src/praisonai/praisonai/agents_generator.py

Lines changed: 147 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
# Framework-specific imports with availability checks
1919
CREWAI_AVAILABLE = False
2020
AUTOGEN_AVAILABLE = False
21+
AUTOGEN_V4_AVAILABLE = False
2122
PRAISONAI_TOOLS_AVAILABLE = False
2223
AGENTOPS_AVAILABLE = False
2324
PRAISONAI_AVAILABLE = False
@@ -41,6 +42,17 @@
4142
except ImportError:
4243
pass
4344

45+
try:
46+
from autogen_agentchat.agents import AssistantAgent as AutoGenV4AssistantAgent
47+
from autogen_ext.models.openai import OpenAIChatCompletionClient
48+
from autogen_agentchat.teams import RoundRobinGroupChat
49+
from autogen_agentchat.conditions import TextMentionTermination, MaxMessageTermination
50+
from autogen_agentchat.messages import TextMessage
51+
from autogen_core import CancellationToken
52+
AUTOGEN_V4_AVAILABLE = True
53+
except ImportError:
54+
pass
55+
4456
try:
4557
import agentops
4658
AGENTOPS_AVAILABLE = True
@@ -123,8 +135,8 @@ def __init__(self, agent_file, framework, config_list, log_level=None, agent_cal
123135
# Validate framework availability
124136
if framework == "crewai" and not CREWAI_AVAILABLE:
125137
raise ImportError("CrewAI is not installed. Please install it with 'pip install praisonai[crewai]'")
126-
elif framework == "autogen" and not AUTOGEN_AVAILABLE:
127-
raise ImportError("AutoGen is not installed. Please install it with 'pip install praisonai[autogen]'")
138+
elif framework == "autogen" and not (AUTOGEN_AVAILABLE or AUTOGEN_V4_AVAILABLE):
139+
raise ImportError("AutoGen is not installed. Please install it with 'pip install praisonai[autogen]' for v0.2 or 'pip install praisonai[autogen-v4]' for v0.4")
128140
elif framework == "praisonai" and not PRAISONAI_AVAILABLE:
129141
raise ImportError("PraisonAI is not installed. Please install it with 'pip install praisonaiagents'")
130142

@@ -316,11 +328,35 @@ def generate_crew_and_kickoff(self):
316328
framework = self.framework or config.get('framework')
317329

318330
if framework == "autogen":
319-
if not AUTOGEN_AVAILABLE:
320-
raise ImportError("AutoGen is not installed. Please install it with 'pip install praisonai[autogen]'")
331+
if not (AUTOGEN_AVAILABLE or AUTOGEN_V4_AVAILABLE):
332+
raise ImportError("AutoGen is not installed. Please install it with 'pip install praisonai[autogen]' for v0.2 or 'pip install praisonai[autogen-v4]' for v0.4")
333+
334+
# Choose autogen version based on availability and environment preference
335+
# AUTOGEN_VERSION can be set to "v0.2" or "v0.4" to force a specific version
336+
autogen_version = os.environ.get("AUTOGEN_VERSION", "auto").lower()
337+
338+
use_v4 = False
339+
if autogen_version == "v0.4" and AUTOGEN_V4_AVAILABLE:
340+
use_v4 = True
341+
elif autogen_version == "v0.2" and AUTOGEN_AVAILABLE:
342+
use_v4 = False
343+
elif autogen_version == "auto":
344+
# Default preference: use v0.4 if available, fallback to v0.2
345+
use_v4 = AUTOGEN_V4_AVAILABLE
346+
else:
347+
# Fallback to whatever is available
348+
use_v4 = AUTOGEN_V4_AVAILABLE and not AUTOGEN_AVAILABLE
349+
321350
if AGENTOPS_AVAILABLE:
322-
agentops.init(os.environ.get("AGENTOPS_API_KEY"), default_tags=["autogen"])
323-
return self._run_autogen(config, topic, tools_dict)
351+
version_tag = "autogen-v4" if use_v4 else "autogen-v2"
352+
agentops.init(os.environ.get("AGENTOPS_API_KEY"), default_tags=[version_tag])
353+
354+
if use_v4:
355+
self.logger.info("Using AutoGen v0.4")
356+
return self._run_autogen_v4(config, topic, tools_dict)
357+
else:
358+
self.logger.info("Using AutoGen v0.2")
359+
return self._run_autogen(config, topic, tools_dict)
324360
elif framework == "praisonai":
325361
if not PRAISONAI_AVAILABLE:
326362
raise ImportError("PraisonAI is not installed. Please install it with 'pip install praisonaiagents'")
@@ -407,6 +443,111 @@ def _run_autogen(self, config, topic, tools_dict):
407443

408444
return result
409445

446+
def _run_autogen_v4(self, config, topic, tools_dict):
447+
"""
448+
Run agents using the AutoGen v0.4 framework with async, event-driven architecture.
449+
450+
Args:
451+
config (dict): Configuration dictionary
452+
topic (str): The topic to process
453+
tools_dict (dict): Dictionary of available tools
454+
455+
Returns:
456+
str: Result of the agent interactions
457+
"""
458+
import asyncio
459+
460+
async def run_autogen_v4_async():
461+
# Create model client for v0.4
462+
model_config = self.config_list[0] if self.config_list else {}
463+
model_client = OpenAIChatCompletionClient(
464+
model=model_config.get('model', 'gpt-4o'),
465+
api_key=model_config.get('api_key', os.environ.get("OPENAI_API_KEY")),
466+
base_url=model_config.get('base_url', "https://api.openai.com/v1")
467+
)
468+
469+
agents = []
470+
combined_tasks = []
471+
472+
# Create agents from config
473+
for role, details in config['roles'].items():
474+
agent_name = details['role'].format(topic=topic).replace("{topic}", topic)
475+
backstory = details['backstory'].format(topic=topic)
476+
477+
# Convert tools for v0.4 - simplified tool passing
478+
agent_tools = []
479+
for tool_name in details.get('tools', []):
480+
if tool_name in tools_dict:
481+
tool_instance = tools_dict[tool_name]
482+
# For v0.4, we can pass the tool's run method directly if it's callable
483+
if hasattr(tool_instance, 'run') and callable(tool_instance.run):
484+
agent_tools.append(tool_instance.run)
485+
486+
# Create v0.4 AssistantAgent
487+
assistant = AutoGenV4AssistantAgent(
488+
name=agent_name,
489+
system_message=backstory + ". Must reply with 'TERMINATE' when the task is complete.",
490+
model_client=model_client,
491+
tools=agent_tools,
492+
reflect_on_tool_use=True
493+
)
494+
495+
agents.append(assistant)
496+
497+
# Collect all task descriptions for sequential execution
498+
for task_name, task_details in details.get('tasks', {}).items():
499+
description_filled = task_details['description'].format(topic=topic)
500+
combined_tasks.append(description_filled)
501+
502+
if not agents:
503+
return "No agents created from configuration"
504+
505+
# Create termination conditions
506+
text_termination = TextMentionTermination("TERMINATE")
507+
max_messages_termination = MaxMessageTermination(max_messages=20)
508+
termination_condition = text_termination | max_messages_termination
509+
510+
# Create RoundRobinGroupChat for parallel/sequential execution
511+
group_chat = RoundRobinGroupChat(
512+
agents,
513+
termination_condition=termination_condition,
514+
max_turns=len(agents) * 3 # Allow multiple rounds
515+
)
516+
517+
# Combine all tasks into a single task description
518+
task_description = f"Topic: {topic}\n\nTasks to complete:\n" + "\n".join(
519+
f"{i+1}. {task}" for i, task in enumerate(combined_tasks)
520+
)
521+
522+
# Run the group chat
523+
try:
524+
result = await group_chat.run(task=task_description)
525+
526+
# Extract the final message content
527+
if result.messages:
528+
final_message = result.messages[-1]
529+
if hasattr(final_message, 'content'):
530+
return f"### AutoGen v0.4 Output ###\n{final_message.content}"
531+
else:
532+
return f"### AutoGen v0.4 Output ###\n{str(final_message)}"
533+
else:
534+
return "### AutoGen v0.4 Output ###\nNo messages generated"
535+
536+
except Exception as e:
537+
self.logger.error(f"Error in AutoGen v0.4 execution: {str(e)}")
538+
return f"### AutoGen v0.4 Error ###\n{str(e)}"
539+
540+
finally:
541+
# Close the model client
542+
await model_client.close()
543+
544+
# Run the async function
545+
try:
546+
return asyncio.run(run_autogen_v4_async())
547+
except Exception as e:
548+
self.logger.error(f"Error running AutoGen v0.4: {str(e)}")
549+
return f"### AutoGen v0.4 Error ###\n{str(e)}"
550+
410551
def _run_crewai(self, config, topic, tools_dict):
411552
"""
412553
Run agents using the CrewAI framework.

src/praisonai/praisonai/auto.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,13 @@
3232
except ImportError:
3333
pass
3434

35+
try:
36+
from autogen_agentchat.agents import AssistantAgent
37+
from autogen_ext.models.openai import OpenAIChatCompletionClient
38+
AUTOGEN_V4_AVAILABLE = True
39+
except ImportError:
40+
AUTOGEN_V4_AVAILABLE = False
41+
3542
try:
3643
from praisonai_tools import (
3744
CodeDocsSearchTool, CSVSearchTool, DirectorySearchTool, DOCXSearchTool,
@@ -73,10 +80,11 @@ def __init__(self, topic="Movie Story writing about AI", agent_file="test.yaml",
7380
CrewAI is not installed. Please install with:
7481
pip install "praisonai[crewai]"
7582
""")
76-
elif framework == "autogen" and not AUTOGEN_AVAILABLE:
83+
elif framework == "autogen" and not (AUTOGEN_AVAILABLE or AUTOGEN_V4_AVAILABLE):
7784
raise ImportError("""
7885
AutoGen is not installed. Please install with:
79-
pip install "praisonai[autogen]"
86+
pip install "praisonai[autogen]" for v0.2
87+
pip install "praisonai[autogen-v4]" for v0.4
8088
""")
8189
elif framework == "praisonai" and not PRAISONAI_AVAILABLE:
8290
raise ImportError("""
@@ -86,7 +94,14 @@ def __init__(self, topic="Movie Story writing about AI", agent_file="test.yaml",
8694

8795
# Only show tools message if using a framework and tools are needed
8896
if (framework in ["crewai", "autogen"]) and not PRAISONAI_TOOLS_AVAILABLE:
89-
logging.warning(f"""
97+
if framework == "autogen":
98+
logging.warning("""
99+
Tools are not available for autogen. To use tools, install:
100+
pip install "praisonai[autogen]" for v0.2
101+
pip install "praisonai[autogen-v4]" for v0.4
102+
""")
103+
else:
104+
logging.warning(f"""
90105
Tools are not available for {framework}. To use tools, install:
91106
pip install "praisonai[{framework}]"
92107
""")

src/praisonai/pyproject.toml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,13 @@ call = [
9292
train = []
9393
crewai = ["crewai>=0.32.0", "praisonai-tools>=0.0.22"]
9494
autogen = ["pyautogen==0.2.29", "praisonai-tools>=0.0.22", "crewai"]
95+
autogen-v4 = [
96+
"autogen-agentchat>=0.4.0",
97+
"autogen-ext[openai]>=0.4.0",
98+
"autogen-core>=0.4.0",
99+
"praisonai-tools>=0.0.22",
100+
"crewai"
101+
]
95102

96103
[tool.poetry]
97104
name = "PraisonAI"
@@ -119,6 +126,9 @@ instructor = ">=1.3.3"
119126
PyYAML = ">=6.0"
120127
mcp = ">=1.6.0"
121128
pyautogen = {version = "==0.2.29", optional = true}
129+
autogen-agentchat = {version = ">=0.4.0", optional = true}
130+
autogen-ext = {version = ">=0.4.0", optional = true}
131+
autogen-core = {version = ">=0.4.0", optional = true}
122132
crewai = {version = ">=0.32.0", optional = true}
123133
praisonai-tools = {version = ">=0.0.22", optional = true}
124134
chainlit = {version = "==2.5.5", optional = true}
@@ -277,6 +287,7 @@ call = [
277287
]
278288
crewai = ["crewai", "praisonai-tools"]
279289
autogen = ["pyautogen", "praisonai-tools", "crewai"]
290+
autogen-v4 = ["autogen-agentchat", "autogen-ext", "autogen-core", "praisonai-tools", "crewai"]
280291

281292
[tool.poetry-dynamic-versioning]
282293
enable = true

0 commit comments

Comments
 (0)