PraisonAI 2.0.2__cp311-cp311-macosx_15_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of PraisonAI might be problematic. Click here for more details.

Files changed (81) hide show
  1. praisonai/__init__.py +6 -0
  2. praisonai/__main__.py +10 -0
  3. praisonai/agents_generator.py +615 -0
  4. praisonai/api/call.py +292 -0
  5. praisonai/auto.py +238 -0
  6. praisonai/chainlit_ui.py +304 -0
  7. praisonai/cli.py +512 -0
  8. praisonai/deploy.py +138 -0
  9. praisonai/inbuilt_tools/__init__.py +24 -0
  10. praisonai/inbuilt_tools/autogen_tools.py +117 -0
  11. praisonai/inc/__init__.py +2 -0
  12. praisonai/inc/config.py +96 -0
  13. praisonai/inc/models.py +128 -0
  14. praisonai/public/android-chrome-192x192.png +0 -0
  15. praisonai/public/android-chrome-512x512.png +0 -0
  16. praisonai/public/apple-touch-icon.png +0 -0
  17. praisonai/public/fantasy.svg +3 -0
  18. praisonai/public/favicon-16x16.png +0 -0
  19. praisonai/public/favicon-32x32.png +0 -0
  20. praisonai/public/favicon.ico +0 -0
  21. praisonai/public/game.svg +3 -0
  22. praisonai/public/logo_dark.png +0 -0
  23. praisonai/public/logo_light.png +0 -0
  24. praisonai/public/movie.svg +3 -0
  25. praisonai/public/thriller.svg +3 -0
  26. praisonai/setup/__init__.py +1 -0
  27. praisonai/setup/build.py +21 -0
  28. praisonai/setup/config.yaml +60 -0
  29. praisonai/setup/post_install.py +23 -0
  30. praisonai/setup/setup_conda_env.py +25 -0
  31. praisonai/setup/setup_conda_env.sh +72 -0
  32. praisonai/setup.py +16 -0
  33. praisonai/test.py +105 -0
  34. praisonai/train.py +276 -0
  35. praisonai/ui/README.md +21 -0
  36. praisonai/ui/chat.py +387 -0
  37. praisonai/ui/code.py +440 -0
  38. praisonai/ui/components/aicoder.py +269 -0
  39. praisonai/ui/config/.chainlit/config.toml +120 -0
  40. praisonai/ui/config/.chainlit/translations/bn.json +231 -0
  41. praisonai/ui/config/.chainlit/translations/en-US.json +229 -0
  42. praisonai/ui/config/.chainlit/translations/gu.json +231 -0
  43. praisonai/ui/config/.chainlit/translations/he-IL.json +231 -0
  44. praisonai/ui/config/.chainlit/translations/hi.json +231 -0
  45. praisonai/ui/config/.chainlit/translations/kn.json +231 -0
  46. praisonai/ui/config/.chainlit/translations/ml.json +231 -0
  47. praisonai/ui/config/.chainlit/translations/mr.json +231 -0
  48. praisonai/ui/config/.chainlit/translations/ta.json +231 -0
  49. praisonai/ui/config/.chainlit/translations/te.json +231 -0
  50. praisonai/ui/config/.chainlit/translations/zh-CN.json +229 -0
  51. praisonai/ui/config/chainlit.md +1 -0
  52. praisonai/ui/config/translations/bn.json +231 -0
  53. praisonai/ui/config/translations/en-US.json +229 -0
  54. praisonai/ui/config/translations/gu.json +231 -0
  55. praisonai/ui/config/translations/he-IL.json +231 -0
  56. praisonai/ui/config/translations/hi.json +231 -0
  57. praisonai/ui/config/translations/kn.json +231 -0
  58. praisonai/ui/config/translations/ml.json +231 -0
  59. praisonai/ui/config/translations/mr.json +231 -0
  60. praisonai/ui/config/translations/ta.json +231 -0
  61. praisonai/ui/config/translations/te.json +231 -0
  62. praisonai/ui/config/translations/zh-CN.json +229 -0
  63. praisonai/ui/context.py +283 -0
  64. praisonai/ui/db.py +291 -0
  65. praisonai/ui/public/fantasy.svg +3 -0
  66. praisonai/ui/public/game.svg +3 -0
  67. praisonai/ui/public/logo_dark.png +0 -0
  68. praisonai/ui/public/logo_light.png +0 -0
  69. praisonai/ui/public/movie.svg +3 -0
  70. praisonai/ui/public/praison.css +3 -0
  71. praisonai/ui/public/thriller.svg +3 -0
  72. praisonai/ui/realtime.py +421 -0
  73. praisonai/ui/realtimeclient/__init__.py +653 -0
  74. praisonai/ui/realtimeclient/realtimedocs.txt +1484 -0
  75. praisonai/ui/realtimeclient/tools.py +236 -0
  76. praisonai/ui/sql_alchemy.py +706 -0
  77. praisonai/version.py +1 -0
  78. praisonai-2.0.2.dist-info/LICENSE +20 -0
  79. praisonai-2.0.2.dist-info/METADATA +483 -0
  80. praisonai-2.0.2.dist-info/RECORD +81 -0
  81. praisonai-2.0.2.dist-info/WHEEL +4 -0
praisonai/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ # Disable OpenTelemetry SDK
2
+ import os
3
+ os.environ["OTEL_SDK_DISABLED"] = "true"
4
+ os.environ["EC_TELEMETRY"] = "false"
5
+ from .cli import PraisonAI
6
+ from .version import __version__
praisonai/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ # __main__.py
2
+
3
+ from .cli import PraisonAI
4
+
5
+ def main():
6
+ praison_ai = PraisonAI()
7
+ praison_ai.main()
8
+
9
+ if __name__ == "__main__":
10
+ main()
@@ -0,0 +1,615 @@
1
+ # praisonai/agents_generator.py
2
+
3
+ import sys
4
+ from .version import __version__
5
+ import yaml, os
6
+ from rich import print
7
+ from dotenv import load_dotenv
8
+ from .auto import AutoGenerator
9
+ from .inbuilt_tools import *
10
+ from .inc import PraisonAIModel
11
+ import inspect
12
+ from pathlib import Path
13
+ import importlib
14
+ import importlib.util
15
+ import os
16
+ import logging
17
+
18
+ # Framework-specific imports with availability checks
19
+ CREWAI_AVAILABLE = False
20
+ AUTOGEN_AVAILABLE = False
21
+ PRAISONAI_TOOLS_AVAILABLE = False
22
+ AGENTOPS_AVAILABLE = False
23
+ PRAISONAI_AVAILABLE = False
24
+
25
+ try:
26
+ from praisonaiagents import Agent as PraisonAgent, Task as PraisonTask, PraisonAIAgents
27
+ PRAISONAI_AVAILABLE = True
28
+ except ImportError:
29
+ pass
30
+
31
+ try:
32
+ from crewai import Agent, Task, Crew
33
+ from crewai.telemetry import Telemetry
34
+ CREWAI_AVAILABLE = True
35
+ except ImportError:
36
+ pass
37
+
38
+ try:
39
+ import autogen
40
+ AUTOGEN_AVAILABLE = True
41
+ except ImportError:
42
+ pass
43
+
44
+ try:
45
+ import agentops
46
+ AGENTOPS_AVAILABLE = True
47
+ AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY")
48
+ if not AGENTOPS_API_KEY:
49
+ AGENTOPS_AVAILABLE = False
50
+ except ImportError:
51
+ pass
52
+
53
+ # Only try to import praisonai_tools if either CrewAI or AutoGen is available
54
+ if CREWAI_AVAILABLE or AUTOGEN_AVAILABLE or PRAISONAI_AVAILABLE:
55
+ try:
56
+ from praisonai_tools import (
57
+ CodeDocsSearchTool, CSVSearchTool, DirectorySearchTool, DOCXSearchTool, DirectoryReadTool,
58
+ FileReadTool, TXTSearchTool, JSONSearchTool, MDXSearchTool, PDFSearchTool, RagTool,
59
+ ScrapeElementFromWebsiteTool, ScrapeWebsiteTool, WebsiteSearchTool, XMLSearchTool,
60
+ YoutubeChannelSearchTool, YoutubeVideoSearchTool, BaseTool
61
+ )
62
+ PRAISONAI_TOOLS_AVAILABLE = True
63
+ except ImportError:
64
+ # If import fails, define BaseTool as a simple base class
65
+ class BaseTool:
66
+ pass
67
+
68
+ os.environ["OTEL_SDK_DISABLED"] = "true"
69
+
70
+ def noop(*args, **kwargs):
71
+ pass
72
+
73
+ def disable_crewai_telemetry():
74
+ if CREWAI_AVAILABLE:
75
+ for attr in dir(Telemetry):
76
+ if callable(getattr(Telemetry, attr)) and not attr.startswith("__"):
77
+ setattr(Telemetry, attr, noop)
78
+
79
+ # Only disable telemetry if CrewAI is available
80
+ if CREWAI_AVAILABLE:
81
+ disable_crewai_telemetry()
82
+
83
+ class AgentsGenerator:
84
+ def __init__(self, agent_file, framework, config_list, log_level=None, agent_callback=None, task_callback=None, agent_yaml=None, tools=None):
85
+ """
86
+ Initialize the AgentsGenerator object.
87
+
88
+ Parameters:
89
+ agent_file (str): The path to the agent file.
90
+ framework (str): The framework to be used for the agents.
91
+ config_list (list): A list of configurations for the agents.
92
+ log_level (int, optional): The logging level to use. Defaults to logging.INFO.
93
+ agent_callback (callable, optional): A callback function to be executed after each agent step.
94
+ task_callback (callable, optional): A callback function to be executed after each tool run.
95
+ agent_yaml (str, optional): The content of the YAML file. Defaults to None.
96
+ tools (dict, optional): A dictionary containing the tools to be used for the agents. Defaults to None.
97
+
98
+ Attributes:
99
+ agent_file (str): The path to the agent file.
100
+ framework (str): The framework to be used for the agents.
101
+ config_list (list): A list of configurations for the agents.
102
+ log_level (int): The logging level to use.
103
+ agent_callback (callable, optional): A callback function to be executed after each agent step.
104
+ task_callback (callable, optional): A callback function to be executed after each tool run.
105
+ tools (dict): A dictionary containing the tools to be used for the agents.
106
+ """
107
+ self.agent_file = agent_file
108
+ self.framework = framework
109
+ self.config_list = config_list
110
+ self.log_level = log_level
111
+ self.agent_callback = agent_callback
112
+ self.task_callback = task_callback
113
+ self.agent_yaml = agent_yaml
114
+ self.tools = tools or [] # Store tool class names as a list
115
+ self.log_level = log_level or logging.getLogger().getEffectiveLevel()
116
+ if self.log_level == logging.NOTSET:
117
+ self.log_level = os.environ.get('LOGLEVEL', 'INFO').upper()
118
+
119
+ logging.basicConfig(level=self.log_level, format='%(asctime)s - %(levelname)s - %(message)s')
120
+ self.logger = logging.getLogger(__name__)
121
+ self.logger.setLevel(self.log_level)
122
+
123
+ # Validate framework availability
124
+ if framework == "crewai" and not CREWAI_AVAILABLE:
125
+ 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]'")
128
+ elif framework == "praisonai" and not PRAISONAI_AVAILABLE:
129
+ raise ImportError("PraisonAI is not installed. Please install it with 'pip install praisonaiagents'")
130
+
131
+ def is_function_or_decorated(self, obj):
132
+ """
133
+ Checks if the given object is a function or has a __call__ method.
134
+
135
+ Parameters:
136
+ obj (object): The object to be checked.
137
+
138
+ Returns:
139
+ bool: True if the object is a function or has a __call__ method, False otherwise.
140
+ """
141
+ return inspect.isfunction(obj) or hasattr(obj, '__call__')
142
+
143
+ def load_tools_from_module(self, module_path):
144
+ """
145
+ Loads tools from a specified module path.
146
+
147
+ Parameters:
148
+ module_path (str): The path to the module containing the tools.
149
+
150
+ Returns:
151
+ dict: A dictionary containing the names of the tools as keys and the corresponding functions or objects as values.
152
+
153
+ Raises:
154
+ FileNotFoundError: If the specified module path does not exist.
155
+ """
156
+ spec = importlib.util.spec_from_file_location("tools_module", module_path)
157
+ module = importlib.util.module_from_spec(spec)
158
+ spec.loader.exec_module(module)
159
+ return {name: obj for name, obj in inspect.getmembers(module, self.is_function_or_decorated)}
160
+
161
+ def load_tools_from_module_class(self, module_path):
162
+ """
163
+ Loads tools from a specified module path containing classes that inherit from BaseTool
164
+ or are part of langchain_community.tools package.
165
+ """
166
+ spec = importlib.util.spec_from_file_location("tools_module", module_path)
167
+ module = importlib.util.module_from_spec(spec)
168
+ try:
169
+ spec.loader.exec_module(module)
170
+ return {name: obj() for name, obj in inspect.getmembers(module,
171
+ lambda x: inspect.isclass(x) and (
172
+ x.__module__.startswith('langchain_community.tools') or
173
+ (PRAISONAI_TOOLS_AVAILABLE and issubclass(x, BaseTool))
174
+ ) and x is not BaseTool)}
175
+ except ImportError as e:
176
+ self.logger.warning(f"Error loading tools from {module_path}: {e}")
177
+ return {}
178
+
179
+ def load_tools_from_package(self, package_path):
180
+ """
181
+ Loads tools from a specified package path containing modules with functions or classes.
182
+
183
+ Parameters:
184
+ package_path (str): The path to the package containing the tools.
185
+
186
+ Returns:
187
+ dict: A dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.
188
+
189
+ Raises:
190
+ FileNotFoundError: If the specified package path does not exist.
191
+
192
+ This function iterates through all the .py files in the specified package path, excluding those that start with "__". For each file, it imports the corresponding module and checks if it contains any functions or classes that can be loaded as tools. The function then returns a dictionary containing the names of the tools as keys and the corresponding initialized instances of the classes as values.
193
+ """
194
+ tools_dict = {}
195
+ for module_file in os.listdir(package_path):
196
+ if module_file.endswith('.py') and not module_file.startswith('__'):
197
+ module_name = f"{package_path.name}.{module_file[:-3]}" # Remove .py for import
198
+ module = importlib.import_module(module_name)
199
+ for name, obj in inspect.getmembers(module, self.is_function_or_decorated):
200
+ tools_dict[name] = obj
201
+ return tools_dict
202
+
203
+ def generate_crew_and_kickoff(self):
204
+ """
205
+ Generates a crew of agents and initiates tasks based on the provided configuration.
206
+
207
+ Parameters:
208
+ agent_file (str): The path to the agent file.
209
+ framework (str): The framework to be used for the agents.
210
+ config_list (list): A list of configurations for the agents.
211
+
212
+ Returns:
213
+ str: The output of the tasks performed by the crew of agents.
214
+
215
+ Raises:
216
+ FileNotFoundError: If the specified agent file does not exist.
217
+
218
+ This function first loads the agent configuration from the specified file. It then initializes the tools required for the agents based on the specified framework. If the specified framework is "autogen", it loads the LLM configuration dynamically and creates an AssistantAgent for each role in the configuration. It then adds tools to the agents if specified in the configuration. Finally, it prepares tasks for the agents based on the configuration and initiates the tasks using the crew of agents. If the specified framework is not "autogen", it creates a crew of agents and initiates tasks based on the configuration.
219
+ """
220
+ if self.agent_yaml:
221
+ config = yaml.safe_load(self.agent_yaml)
222
+ else:
223
+ if self.agent_file == '/app/api:app' or self.agent_file == 'api:app':
224
+ self.agent_file = 'agents.yaml'
225
+ try:
226
+ with open(self.agent_file, 'r') as f:
227
+ config = yaml.safe_load(f)
228
+ except FileNotFoundError:
229
+ print(f"File not found: {self.agent_file}")
230
+ return
231
+
232
+ topic = config['topic']
233
+ tools_dict = {}
234
+
235
+ # Only try to use praisonai_tools if it's available and needed
236
+ if PRAISONAI_TOOLS_AVAILABLE and (CREWAI_AVAILABLE or AUTOGEN_AVAILABLE or PRAISONAI_AVAILABLE):
237
+ tools_dict = {
238
+ 'CodeDocsSearchTool': CodeDocsSearchTool(),
239
+ 'CSVSearchTool': CSVSearchTool(),
240
+ 'DirectorySearchTool': DirectorySearchTool(),
241
+ 'DOCXSearchTool': DOCXSearchTool(),
242
+ 'DirectoryReadTool': DirectoryReadTool(),
243
+ 'FileReadTool': FileReadTool(),
244
+ 'TXTSearchTool': TXTSearchTool(),
245
+ 'JSONSearchTool': JSONSearchTool(),
246
+ 'MDXSearchTool': MDXSearchTool(),
247
+ 'PDFSearchTool': PDFSearchTool(),
248
+ 'RagTool': RagTool(),
249
+ 'ScrapeElementFromWebsiteTool': ScrapeElementFromWebsiteTool(),
250
+ 'ScrapeWebsiteTool': ScrapeWebsiteTool(),
251
+ 'WebsiteSearchTool': WebsiteSearchTool(),
252
+ 'XMLSearchTool': XMLSearchTool(),
253
+ 'YoutubeChannelSearchTool': YoutubeChannelSearchTool(),
254
+ 'YoutubeVideoSearchTool': YoutubeVideoSearchTool(),
255
+ }
256
+
257
+ # Add tools from class names
258
+ for tool_class in self.tools:
259
+ if isinstance(tool_class, type) and issubclass(tool_class, BaseTool):
260
+ tool_name = tool_class.__name__
261
+ tools_dict[tool_name] = tool_class()
262
+ self.logger.debug(f"Added tool: {tool_name}")
263
+
264
+ root_directory = os.getcwd()
265
+ tools_py_path = os.path.join(root_directory, 'tools.py')
266
+ tools_dir_path = Path(root_directory) / 'tools'
267
+
268
+ if os.path.isfile(tools_py_path):
269
+ tools_dict.update(self.load_tools_from_module_class(tools_py_path))
270
+ self.logger.debug("tools.py exists in the root directory. Loading tools.py and skipping tools folder.")
271
+ elif tools_dir_path.is_dir():
272
+ tools_dict.update(self.load_tools_from_module_class(tools_dir_path))
273
+ self.logger.debug("tools folder exists in the root directory")
274
+
275
+ framework = self.framework or config.get('framework')
276
+
277
+ if framework == "autogen":
278
+ if not AUTOGEN_AVAILABLE:
279
+ raise ImportError("AutoGen is not installed. Please install it with 'pip install praisonai[autogen]'")
280
+ if AGENTOPS_AVAILABLE:
281
+ agentops.init(os.environ.get("AGENTOPS_API_KEY"), default_tags=["autogen"])
282
+ return self._run_autogen(config, topic, tools_dict)
283
+ elif framework == "praisonai":
284
+ if not PRAISONAI_AVAILABLE:
285
+ raise ImportError("PraisonAI is not installed. Please install it with 'pip install praisonaiagents'")
286
+ if AGENTOPS_AVAILABLE:
287
+ agentops.init(os.environ.get("AGENTOPS_API_KEY"), default_tags=["praisonai"])
288
+ return self._run_praisonai(config, topic, tools_dict)
289
+ else: # framework=crewai
290
+ if not CREWAI_AVAILABLE:
291
+ raise ImportError("CrewAI is not installed. Please install it with 'pip install praisonai[crewai]'")
292
+ if AGENTOPS_AVAILABLE:
293
+ agentops.init(os.environ.get("AGENTOPS_API_KEY"), default_tags=["crewai"])
294
+ return self._run_crewai(config, topic, tools_dict)
295
+
296
+ def _run_autogen(self, config, topic, tools_dict):
297
+ """
298
+ Run agents using the AutoGen framework.
299
+
300
+ Args:
301
+ config (dict): Configuration dictionary
302
+ topic (str): The topic to process
303
+ tools_dict (dict): Dictionary of available tools
304
+
305
+ Returns:
306
+ str: Result of the agent interactions
307
+ """
308
+ llm_config = {"config_list": self.config_list}
309
+
310
+ # Set up user proxy agent
311
+ user_proxy = autogen.UserProxyAgent(
312
+ name="User",
313
+ human_input_mode="NEVER",
314
+ is_termination_msg=lambda x: (x.get("content") or "").rstrip().rstrip(".").lower().endswith("terminate") or "TERMINATE" in (x.get("content") or ""),
315
+ code_execution_config={
316
+ "work_dir": "coding",
317
+ "use_docker": False,
318
+ }
319
+ )
320
+
321
+ agents = {}
322
+ tasks = []
323
+
324
+ # Create agents and tasks from config
325
+ for role, details in config['roles'].items():
326
+ agent_name = details['role'].format(topic=topic).replace("{topic}", topic)
327
+ agent_goal = details['goal'].format(topic=topic)
328
+
329
+ # Create AutoGen assistant agent
330
+ agents[role] = autogen.AssistantAgent(
331
+ name=agent_name,
332
+ llm_config=llm_config,
333
+ system_message=details['backstory'].format(topic=topic) +
334
+ ". Must Reply \"TERMINATE\" in the end when everything is done.",
335
+ )
336
+
337
+ # Add tools to agent if specified
338
+ for tool in details.get('tools', []):
339
+ if tool in tools_dict:
340
+ try:
341
+ tool_class = globals()[f'autogen_{type(tools_dict[tool]).__name__}']
342
+ self.logger.debug(f"Found {tool_class.__name__} for {tool}")
343
+ tool_class(agents[role], user_proxy)
344
+ except KeyError:
345
+ self.logger.warning(f"Warning: autogen_{type(tools_dict[tool]).__name__} function not found. Skipping this tool.")
346
+ continue
347
+
348
+ # Prepare tasks
349
+ for task_name, task_details in details.get('tasks', {}).items():
350
+ description_filled = task_details['description'].format(topic=topic)
351
+ expected_output_filled = task_details['expected_output'].format(topic=topic)
352
+
353
+ chat_task = {
354
+ "recipient": agents[role],
355
+ "message": description_filled,
356
+ "summary_method": "last_msg",
357
+ }
358
+ tasks.append(chat_task)
359
+
360
+ # Execute tasks
361
+ response = user_proxy.initiate_chats(tasks)
362
+ result = "### Output ###\n" + response[-1].summary if hasattr(response[-1], 'summary') else ""
363
+
364
+ if AGENTOPS_AVAILABLE:
365
+ agentops.end_session("Success")
366
+
367
+ return result
368
+
369
+ def _run_crewai(self, config, topic, tools_dict):
370
+ """
371
+ Run agents using the CrewAI framework.
372
+
373
+ Args:
374
+ config (dict): Configuration dictionary
375
+ topic (str): The topic to process
376
+ tools_dict (dict): Dictionary of available tools
377
+
378
+ Returns:
379
+ str: Result of the agent interactions
380
+ """
381
+ agents = {}
382
+ tasks = []
383
+ tasks_dict = {}
384
+
385
+ # Create agents from config
386
+ for role, details in config['roles'].items():
387
+ role_filled = details['role'].format(topic=topic)
388
+ goal_filled = details['goal'].format(topic=topic)
389
+ backstory_filled = details['backstory'].format(topic=topic)
390
+
391
+ # Get agent tools
392
+ agent_tools = [tools_dict[tool] for tool in details.get('tools', [])
393
+ if tool in tools_dict]
394
+
395
+ # Configure LLM
396
+ llm_model = details.get('llm')
397
+ if llm_model:
398
+ llm = PraisonAIModel(
399
+ model=llm_model.get("model", os.environ.get("MODEL_NAME", "openai/gpt-4o")),
400
+ ).get_model()
401
+ else:
402
+ llm = PraisonAIModel().get_model()
403
+
404
+ # Configure function calling LLM
405
+ function_calling_llm_model = details.get('function_calling_llm')
406
+ if function_calling_llm_model:
407
+ function_calling_llm = PraisonAIModel(
408
+ model=function_calling_llm_model.get("model", os.environ.get("MODEL_NAME", "openai/gpt-4o")),
409
+ ).get_model()
410
+ else:
411
+ function_calling_llm = PraisonAIModel().get_model()
412
+
413
+ # Create CrewAI agent
414
+ agent = Agent(
415
+ role=role_filled,
416
+ goal=goal_filled,
417
+ backstory=backstory_filled,
418
+ tools=agent_tools,
419
+ allow_delegation=details.get('allow_delegation', False),
420
+ llm=llm,
421
+ function_calling_llm=function_calling_llm,
422
+ max_iter=details.get('max_iter', 15),
423
+ max_rpm=details.get('max_rpm'),
424
+ max_execution_time=details.get('max_execution_time'),
425
+ verbose=details.get('verbose', True),
426
+ cache=details.get('cache', True),
427
+ system_template=details.get('system_template'),
428
+ prompt_template=details.get('prompt_template'),
429
+ response_template=details.get('response_template'),
430
+ )
431
+
432
+ # Set agent callback if provided
433
+ if self.agent_callback:
434
+ agent.step_callback = self.agent_callback
435
+
436
+ agents[role] = agent
437
+
438
+ # Create tasks for the agent
439
+ for task_name, task_details in details.get('tasks', {}).items():
440
+ description_filled = task_details['description'].format(topic=topic)
441
+ expected_output_filled = task_details['expected_output'].format(topic=topic)
442
+
443
+ task = Task(
444
+ description=description_filled,
445
+ expected_output=expected_output_filled,
446
+ agent=agent,
447
+ tools=task_details.get('tools', []),
448
+ async_execution=task_details.get('async_execution', False),
449
+ context=[],
450
+ config=task_details.get('config', {}),
451
+ output_json=task_details.get('output_json'),
452
+ output_pydantic=task_details.get('output_pydantic'),
453
+ output_file=task_details.get('output_file', ""),
454
+ callback=task_details.get('callback'),
455
+ human_input=task_details.get('human_input', False),
456
+ create_directory=task_details.get('create_directory', False)
457
+ )
458
+
459
+ # Set task callback if provided
460
+ if self.task_callback:
461
+ task.callback = self.task_callback
462
+
463
+ tasks.append(task)
464
+ tasks_dict[task_name] = task
465
+
466
+ # Set up task contexts
467
+ for role, details in config['roles'].items():
468
+ for task_name, task_details in details.get('tasks', {}).items():
469
+ task = tasks_dict[task_name]
470
+ context_tasks = [tasks_dict[ctx] for ctx in task_details.get('context', [])
471
+ if ctx in tasks_dict]
472
+ task.context = context_tasks
473
+
474
+ # Create and run the crew
475
+ crew = Crew(
476
+ agents=list(agents.values()),
477
+ tasks=tasks,
478
+ verbose=2
479
+ )
480
+
481
+ self.logger.debug("Final Crew Configuration:")
482
+ self.logger.debug(f"Agents: {crew.agents}")
483
+ self.logger.debug(f"Tasks: {crew.tasks}")
484
+
485
+ response = crew.kickoff()
486
+ result = f"### Task Output ###\n{response}"
487
+
488
+ if AGENTOPS_AVAILABLE:
489
+ agentops.end_session("Success")
490
+
491
+ return result
492
+
493
+ def _run_praisonai(self, config, topic, tools_dict):
494
+ """
495
+ Run agents using the PraisonAI framework.
496
+ """
497
+ agents = {}
498
+ tasks = []
499
+ tasks_dict = {}
500
+
501
+ # Create agents from config
502
+ for role, details in config['roles'].items():
503
+ role_filled = details['role'].format(topic=topic)
504
+ goal_filled = details['goal'].format(topic=topic)
505
+ backstory_filled = details['backstory'].format(topic=topic)
506
+
507
+ # Get agent tools
508
+ agent_tools = [tools_dict[tool] for tool in details.get('tools', [])
509
+ if tool in tools_dict]
510
+
511
+ # Configure LLM
512
+ llm_model = details.get('llm')
513
+ if llm_model:
514
+ llm = llm_model.get("model", os.environ.get("MODEL_NAME", "gpt-4o"))
515
+ else:
516
+ llm = os.environ.get("MODEL_NAME", "gpt-4o")
517
+
518
+ # Configure function calling LLM
519
+ function_calling_llm_model = details.get('function_calling_llm')
520
+ if function_calling_llm_model:
521
+ function_calling_llm = function_calling_llm_model.get("model", os.environ.get("MODEL_NAME", "openai/gpt-4o"))
522
+ else:
523
+ function_calling_llm = os.environ.get("MODEL_NAME", "gpt-4o")
524
+
525
+ # Create PraisonAI agent
526
+ agent = PraisonAgent(
527
+ name=role_filled,
528
+ role=role_filled,
529
+ goal=goal_filled,
530
+ backstory=backstory_filled,
531
+ tools=agent_tools,
532
+ allow_delegation=details.get('allow_delegation', False),
533
+ llm=llm,
534
+ function_calling_llm=function_calling_llm,
535
+ max_iter=details.get('max_iter', 15),
536
+ max_rpm=details.get('max_rpm'),
537
+ max_execution_time=details.get('max_execution_time'),
538
+ verbose=details.get('verbose', True),
539
+ cache=details.get('cache', True),
540
+ system_template=details.get('system_template'),
541
+ prompt_template=details.get('prompt_template'),
542
+ response_template=details.get('response_template'),
543
+ )
544
+
545
+ # Set agent callback if provided
546
+ if self.agent_callback:
547
+ agent.step_callback = self.agent_callback
548
+
549
+ agents[role] = agent
550
+
551
+ # Create tasks for the agent
552
+ for task_name, task_details in details.get('tasks', {}).items():
553
+ description_filled = task_details['description'].format(topic=topic)
554
+ expected_output_filled = task_details['expected_output'].format(topic=topic)
555
+
556
+ # Create task using PraisonAI Task class
557
+ task = PraisonTask(
558
+ description=description_filled,
559
+ expected_output=expected_output_filled,
560
+ agent=agent,
561
+ tools=task_details.get('tools', []),
562
+ async_execution=task_details.get('async_execution', False),
563
+ context=[],
564
+ config=task_details.get('config', {}),
565
+ output_json=task_details.get('output_json'),
566
+ output_pydantic=task_details.get('output_pydantic'),
567
+ output_file=task_details.get('output_file', ""),
568
+ callback=task_details.get('callback'),
569
+ create_directory=task_details.get('create_directory', False)
570
+ )
571
+
572
+ # Set task callback if provided
573
+ if self.task_callback:
574
+ task.callback = self.task_callback
575
+
576
+ tasks.append(task)
577
+ tasks_dict[task_name] = task
578
+
579
+ # Set up task contexts
580
+ for role, details in config['roles'].items():
581
+ for task_name, task_details in details.get('tasks', {}).items():
582
+ task = tasks_dict[task_name]
583
+ context_tasks = [tasks_dict[ctx] for ctx in task_details.get('context', [])
584
+ if ctx in tasks_dict]
585
+ task.context = context_tasks
586
+
587
+ # Create and run the PraisonAI agents
588
+ if config.get('process') == 'hierarchical':
589
+ agents = PraisonAIAgents(
590
+ agents=list(agents.values()),
591
+ tasks=tasks,
592
+ verbose=True,
593
+ process="hierarchical",
594
+ manager_llm=config.get('manager_llm', 'gpt-4o'),
595
+ )
596
+ else:
597
+ agents = PraisonAIAgents(
598
+ agents=list(agents.values()),
599
+ tasks=tasks,
600
+ verbose=2
601
+ )
602
+
603
+ self.logger.debug("Final Configuration:")
604
+ self.logger.debug(f"Agents: {agents.agents}")
605
+ self.logger.debug(f"Tasks: {agents.tasks}")
606
+
607
+ response = agents.start()
608
+ # result = f"### Task Output ###\n{response}"
609
+ self.logger.debug(f"Result: {response}")
610
+ result = ""
611
+
612
+ if AGENTOPS_AVAILABLE:
613
+ agentops.end_session("Success")
614
+
615
+ return result