1
- # agents_generator.py
1
+ # praisonai/ agents_generator.py
2
2
3
3
import sys
4
4
from .version import __version__
12
12
import argparse
13
13
from .auto import AutoGenerator
14
14
from crewai_tools import *
15
- from .tools import *
15
+ from .inbuilt_tools import *
16
+ import inspect
17
+ from pathlib import Path
18
+ import importlib
19
+ import importlib .util
16
20
17
21
class AgentsGenerator :
18
22
def __init__ (self , agent_file , framework , config_list ):
19
23
self .agent_file = agent_file
20
24
self .framework = framework
21
25
self .config_list = config_list
26
+
27
+ def is_function_or_decorated (self , obj ):
28
+ return inspect .isfunction (obj ) or hasattr (obj , '__call__' )
29
+
30
+ def load_tools_from_module (self , module_path ):
31
+ spec = importlib .util .spec_from_file_location ("tools_module" , module_path )
32
+ module = importlib .util .module_from_spec (spec )
33
+ spec .loader .exec_module (module )
34
+ return {name : obj for name , obj in inspect .getmembers (module , self .is_function_or_decorated )}
35
+
36
+ def load_tools_from_module_class (self , module_path ):
37
+ spec = importlib .util .spec_from_file_location ("tools_module" , module_path )
38
+ module = importlib .util .module_from_spec (spec )
39
+ spec .loader .exec_module (module )
40
+ return {name : obj () for name , obj in inspect .getmembers (module , lambda x : inspect .isclass (x ) and issubclass (x , BaseTool ) and x is not BaseTool )}
41
+
42
+ def load_tools_from_package (self , package_path ):
43
+ tools_dict = {}
44
+ for module_file in os .listdir (package_path ):
45
+ if module_file .endswith ('.py' ) and not module_file .startswith ('__' ):
46
+ module_name = f"{ package_path .name } .{ module_file [:- 3 ]} " # Remove .py for import
47
+ module = importlib .import_module (module_name )
48
+ for name , obj in inspect .getmembers (module , self .is_function_or_decorated ):
49
+ tools_dict [name ] = obj
50
+ return tools_dict
22
51
23
52
def generate_crew_and_kickoff (self ):
24
53
if self .agent_file == '/app/api:app' or self .agent_file == 'api:app' :
@@ -51,9 +80,20 @@ def generate_crew_and_kickoff(self):
51
80
'WebsiteSearchTool' : WebsiteSearchTool (),
52
81
'XMLSearchTool' : XMLSearchTool (),
53
82
'YoutubeChannelSearchTool' : YoutubeChannelSearchTool (),
54
- 'YoutubeVideoSearchTool' : YoutubeVideoSearchTool ()
83
+ 'YoutubeVideoSearchTool' : YoutubeVideoSearchTool (),
55
84
}
56
- # config['tools'] = [tools_dict[tool] for tool in config.get('tools', []) if tool in tools_dict]
85
+ root_directory = os .getcwd ()
86
+ tools_py_path = os .path .join (root_directory , 'tools.py' )
87
+ tools_dir_path = Path (root_directory ) / 'tools'
88
+
89
+ if os .path .isfile (tools_py_path ):
90
+ tools_dict .update (self .load_tools_from_module_class (tools_py_path ))
91
+ print ("tools.py exists in the root directory. Loading tools.py and skipping tools folder." )
92
+ elif tools_dir_path .is_dir ():
93
+ tools_dict .update (self .load_tools_from_module_class (tools_dir_path ))
94
+ print ("tools folder exists in the root directory" )
95
+ # print(tools_dict)
96
+
57
97
framework = self .framework or config .get ('framework' )
58
98
59
99
agents = {}
@@ -86,7 +126,12 @@ def generate_crew_and_kickoff(self):
86
126
)
87
127
for tool in details .get ('tools' , []):
88
128
if tool in tools_dict :
89
- tool_class = globals ()[f'autogen_{ type (tools_dict [tool ]).__name__ } ' ]
129
+ try :
130
+ tool_class = globals ()[f'autogen_{ type (tools_dict [tool ]).__name__ } ' ]
131
+ print (f"Found { tool_class .__name__ } for { tool } " )
132
+ except KeyError :
133
+ print (f"Warning: autogen_{ type (tools_dict [tool ]).__name__ } function not found. Skipping this tool." )
134
+ continue
90
135
tool_class (agents [role ], user_proxy )
91
136
92
137
# Preparing tasks for initiate_chats
@@ -121,7 +166,7 @@ def generate_crew_and_kickoff(self):
121
166
122
167
task = Task (description = description_filled , expected_output = expected_output_filled , agent = agent )
123
168
tasks .append (task )
124
- # print(agents)
169
+ print (agents . values () )
125
170
crew = Crew (
126
171
agents = list (agents .values ()),
127
172
tasks = tasks ,
@@ -130,92 +175,4 @@ def generate_crew_and_kickoff(self):
130
175
131
176
response = crew .kickoff ()
132
177
result = f"### Task Output ###\n { response } "
133
- return result
134
-
135
-
136
- # # AutoGen Tools example below
137
- # from typing import Any, Optional
138
- # import os
139
- # from autogen import ConversableAgent
140
- # from autogen_tools import autogen_ScrapeWebsiteTool
141
-
142
- # assistant = ConversableAgent(
143
- # name="Assistant",
144
- # system_message="You are a helpful AI assistant. "
145
- # "You can help with website scraping. "
146
- # "Return 'TERMINATE' when the task is done.",
147
- # llm_config={"config_list": [{"model": "gpt-3.5-turbo", "api_key": os.environ["OPENAI_API_KEY"]}]},
148
- # )
149
-
150
- # user_proxy = ConversableAgent(
151
- # name="User",
152
- # llm_config=False,
153
- # is_termination_msg=lambda msg: msg.get("content") is not None and "TERMINATE" in msg["content"],
154
- # human_input_mode="NEVER",
155
- # )
156
-
157
- # autogen_ScrapeWebsiteTool(assistant, user_proxy)
158
-
159
- # chat_result = user_proxy.initiate_chat(assistant, message="Scrape the official Nodejs website.")
160
-
161
- # # CrewAI Tools example below
162
- # import os
163
- # from crewai import Agent, Task, Crew
164
- # # Importing crewAI tools
165
- # from crewai_tools import (
166
- # DirectoryReadTool,
167
- # FileReadTool,
168
- # SerperDevTool,
169
- # WebsiteSearchTool
170
- # )
171
-
172
- # # Set up API keys
173
- # os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
174
- # os.environ["OPENAI_API_KEY"] = "Your Key"
175
-
176
- # # Instantiate tools
177
- # docs_tool = DirectoryReadTool(directory='./blog-posts')
178
- # file_tool = FileReadTool()
179
- # search_tool = SerperDevTool()
180
- # web_rag_tool = WebsiteSearchTool()
181
-
182
- # # Create agents
183
- # researcher = Agent(
184
- # role='Market Research Analyst',
185
- # goal='Provide up-to-date market analysis of the AI industry',
186
- # backstory='An expert analyst with a keen eye for market trends.',
187
- # tools=[search_tool, web_rag_tool],
188
- # verbose=True
189
- # )
190
-
191
- # writer = Agent(
192
- # role='Content Writer',
193
- # goal='Craft engaging blog posts about the AI industry',
194
- # backstory='A skilled writer with a passion for technology.',
195
- # tools=[docs_tool, file_tool],
196
- # verbose=True
197
- # )
198
-
199
- # # Define tasks
200
- # research = Task(
201
- # description='Research the latest trends in the AI industry and provide a summary.',
202
- # expected_output='A summary of the top 3 trending developments in the AI industry with a unique perspective on their significance.',
203
- # agent=researcher
204
- # )
205
-
206
- # write = Task(
207
- # description='Write an engaging blog post about the AI industry, based on the research analyst’s summary. Draw inspiration from the latest blog posts in the directory.',
208
- # expected_output='A 4-paragraph blog post formatted in markdown with engaging, informative, and accessible content, avoiding complex jargon.',
209
- # agent=writer,
210
- # output_file='blog-posts/new_post.md' # The final blog post will be saved here
211
- # )
212
-
213
- # # Assemble a crew
214
- # crew = Crew(
215
- # agents=[researcher, writer],
216
- # tasks=[research, write],
217
- # verbose=2
218
- # )
219
-
220
- # # Execute tasks
221
- # crew.kickoff()
178
+ return result
0 commit comments