ag2 0.3.2__py3-none-any.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 ag2 might be problematic. Click here for more details.

Files changed (112) hide show
  1. ag2-0.3.2.dist-info/LICENSE +201 -0
  2. ag2-0.3.2.dist-info/METADATA +490 -0
  3. ag2-0.3.2.dist-info/NOTICE.md +19 -0
  4. ag2-0.3.2.dist-info/RECORD +112 -0
  5. ag2-0.3.2.dist-info/WHEEL +5 -0
  6. ag2-0.3.2.dist-info/top_level.txt +1 -0
  7. autogen/__init__.py +17 -0
  8. autogen/_pydantic.py +116 -0
  9. autogen/agentchat/__init__.py +26 -0
  10. autogen/agentchat/agent.py +142 -0
  11. autogen/agentchat/assistant_agent.py +85 -0
  12. autogen/agentchat/chat.py +306 -0
  13. autogen/agentchat/contrib/__init__.py +0 -0
  14. autogen/agentchat/contrib/agent_builder.py +785 -0
  15. autogen/agentchat/contrib/agent_optimizer.py +450 -0
  16. autogen/agentchat/contrib/capabilities/__init__.py +0 -0
  17. autogen/agentchat/contrib/capabilities/agent_capability.py +21 -0
  18. autogen/agentchat/contrib/capabilities/generate_images.py +297 -0
  19. autogen/agentchat/contrib/capabilities/teachability.py +406 -0
  20. autogen/agentchat/contrib/capabilities/text_compressors.py +72 -0
  21. autogen/agentchat/contrib/capabilities/transform_messages.py +92 -0
  22. autogen/agentchat/contrib/capabilities/transforms.py +565 -0
  23. autogen/agentchat/contrib/capabilities/transforms_util.py +120 -0
  24. autogen/agentchat/contrib/capabilities/vision_capability.py +217 -0
  25. autogen/agentchat/contrib/gpt_assistant_agent.py +545 -0
  26. autogen/agentchat/contrib/graph_rag/__init__.py +0 -0
  27. autogen/agentchat/contrib/graph_rag/document.py +24 -0
  28. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +76 -0
  29. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +50 -0
  30. autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +56 -0
  31. autogen/agentchat/contrib/img_utils.py +390 -0
  32. autogen/agentchat/contrib/llamaindex_conversable_agent.py +114 -0
  33. autogen/agentchat/contrib/llava_agent.py +176 -0
  34. autogen/agentchat/contrib/math_user_proxy_agent.py +471 -0
  35. autogen/agentchat/contrib/multimodal_conversable_agent.py +128 -0
  36. autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +325 -0
  37. autogen/agentchat/contrib/retrieve_assistant_agent.py +56 -0
  38. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +701 -0
  39. autogen/agentchat/contrib/society_of_mind_agent.py +203 -0
  40. autogen/agentchat/contrib/text_analyzer_agent.py +76 -0
  41. autogen/agentchat/contrib/vectordb/__init__.py +0 -0
  42. autogen/agentchat/contrib/vectordb/base.py +243 -0
  43. autogen/agentchat/contrib/vectordb/chromadb.py +326 -0
  44. autogen/agentchat/contrib/vectordb/mongodb.py +559 -0
  45. autogen/agentchat/contrib/vectordb/pgvectordb.py +958 -0
  46. autogen/agentchat/contrib/vectordb/qdrant.py +334 -0
  47. autogen/agentchat/contrib/vectordb/utils.py +126 -0
  48. autogen/agentchat/contrib/web_surfer.py +305 -0
  49. autogen/agentchat/conversable_agent.py +2904 -0
  50. autogen/agentchat/groupchat.py +1666 -0
  51. autogen/agentchat/user_proxy_agent.py +109 -0
  52. autogen/agentchat/utils.py +207 -0
  53. autogen/browser_utils.py +291 -0
  54. autogen/cache/__init__.py +10 -0
  55. autogen/cache/abstract_cache_base.py +78 -0
  56. autogen/cache/cache.py +182 -0
  57. autogen/cache/cache_factory.py +85 -0
  58. autogen/cache/cosmos_db_cache.py +150 -0
  59. autogen/cache/disk_cache.py +109 -0
  60. autogen/cache/in_memory_cache.py +61 -0
  61. autogen/cache/redis_cache.py +128 -0
  62. autogen/code_utils.py +745 -0
  63. autogen/coding/__init__.py +22 -0
  64. autogen/coding/base.py +113 -0
  65. autogen/coding/docker_commandline_code_executor.py +262 -0
  66. autogen/coding/factory.py +45 -0
  67. autogen/coding/func_with_reqs.py +203 -0
  68. autogen/coding/jupyter/__init__.py +22 -0
  69. autogen/coding/jupyter/base.py +32 -0
  70. autogen/coding/jupyter/docker_jupyter_server.py +164 -0
  71. autogen/coding/jupyter/embedded_ipython_code_executor.py +182 -0
  72. autogen/coding/jupyter/jupyter_client.py +224 -0
  73. autogen/coding/jupyter/jupyter_code_executor.py +161 -0
  74. autogen/coding/jupyter/local_jupyter_server.py +168 -0
  75. autogen/coding/local_commandline_code_executor.py +410 -0
  76. autogen/coding/markdown_code_extractor.py +44 -0
  77. autogen/coding/utils.py +57 -0
  78. autogen/exception_utils.py +46 -0
  79. autogen/extensions/__init__.py +0 -0
  80. autogen/formatting_utils.py +76 -0
  81. autogen/function_utils.py +362 -0
  82. autogen/graph_utils.py +148 -0
  83. autogen/io/__init__.py +15 -0
  84. autogen/io/base.py +105 -0
  85. autogen/io/console.py +43 -0
  86. autogen/io/websockets.py +213 -0
  87. autogen/logger/__init__.py +11 -0
  88. autogen/logger/base_logger.py +140 -0
  89. autogen/logger/file_logger.py +287 -0
  90. autogen/logger/logger_factory.py +29 -0
  91. autogen/logger/logger_utils.py +42 -0
  92. autogen/logger/sqlite_logger.py +459 -0
  93. autogen/math_utils.py +356 -0
  94. autogen/oai/__init__.py +33 -0
  95. autogen/oai/anthropic.py +428 -0
  96. autogen/oai/bedrock.py +600 -0
  97. autogen/oai/cerebras.py +264 -0
  98. autogen/oai/client.py +1148 -0
  99. autogen/oai/client_utils.py +167 -0
  100. autogen/oai/cohere.py +453 -0
  101. autogen/oai/completion.py +1216 -0
  102. autogen/oai/gemini.py +469 -0
  103. autogen/oai/groq.py +281 -0
  104. autogen/oai/mistral.py +279 -0
  105. autogen/oai/ollama.py +576 -0
  106. autogen/oai/openai_utils.py +810 -0
  107. autogen/oai/together.py +343 -0
  108. autogen/retrieve_utils.py +487 -0
  109. autogen/runtime_logging.py +163 -0
  110. autogen/token_count_utils.py +257 -0
  111. autogen/types.py +20 -0
  112. autogen/version.py +7 -0
@@ -0,0 +1,785 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # Portions derived from https://github.com/microsoft/autogen are under the MIT License.
6
+ # SPDX-License-Identifier: MIT
7
+ import hashlib
8
+ import importlib
9
+ import json
10
+ import logging
11
+ import re
12
+ import socket
13
+ import subprocess as sp
14
+ import time
15
+ from typing import Dict, List, Optional, Tuple, Union
16
+
17
+ import requests
18
+ from termcolor import colored
19
+
20
+ import autogen
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ def _config_check(config: Dict):
26
+ # check config loading
27
+ assert config.get("coding", None) is not None, 'Missing "coding" in your config.'
28
+ assert config.get("default_llm_config", None) is not None, 'Missing "default_llm_config" in your config.'
29
+ assert config.get("code_execution_config", None) is not None, 'Missing "code_execution_config" in your config.'
30
+
31
+ for agent_config in config["agent_configs"]:
32
+ assert agent_config.get("name", None) is not None, 'Missing agent "name" in your agent_configs.'
33
+ assert (
34
+ agent_config.get("system_message", None) is not None
35
+ ), 'Missing agent "system_message" in your agent_configs.'
36
+ assert agent_config.get("description", None) is not None, 'Missing agent "description" in your agent_configs.'
37
+
38
+
39
+ def _retrieve_json(text):
40
+ match = re.findall(autogen.code_utils.CODE_BLOCK_PATTERN, text, flags=re.DOTALL)
41
+ if not match:
42
+ return text
43
+ code_blocks = []
44
+ for _, code in match:
45
+ code_blocks.append(code)
46
+ return code_blocks[0]
47
+
48
+
49
+ class AgentBuilder:
50
+ """
51
+ AgentBuilder can help user build an automatic task solving process powered by multi-agent system.
52
+ Specifically, our building pipeline includes initialize and build.
53
+ """
54
+
55
+ online_server_name = "online"
56
+
57
+ DEFAULT_PROXY_AUTO_REPLY = 'There is no code from the last 1 message for me to execute. Group chat manager should let other participants to continue the conversation. If the group chat manager want to end the conversation, you should let other participant reply me only with "TERMINATE"'
58
+
59
+ GROUP_CHAT_DESCRIPTION = """ # Group chat instruction
60
+ You are now working in a group chat with different expert and a group chat manager.
61
+ You should refer to the previous message from other participant members or yourself, follow their topic and reply to them.
62
+
63
+ **Your role is**: {name}
64
+ Group chat members: {members}{user_proxy_desc}
65
+
66
+ When the task is complete and the result has been carefully verified, after obtaining agreement from the other members, you can end the conversation by replying only with "TERMINATE".
67
+
68
+ # Your profile
69
+ {sys_msg}
70
+ """
71
+
72
+ DEFAULT_DESCRIPTION = """## Your role
73
+ [Complete this part with expert's name and skill description]
74
+
75
+ ## Task and skill instructions
76
+ - [Complete this part with task description]
77
+ - [Complete this part with skill description]
78
+ - [(Optional) Complete this part with other information]
79
+ """
80
+
81
+ CODING_AND_TASK_SKILL_INSTRUCTION = """## Useful instructions for task-solving
82
+ - Solve the task step by step if you need to.
83
+ - When you find an answer, verify the answer carefully. Include verifiable evidence with possible test case in your response if possible.
84
+ - All your reply should be based on the provided facts.
85
+
86
+ ## How to verify?
87
+ **You have to keep believing that everyone else's answers are wrong until they provide clear enough evidence.**
88
+ - Verifying with step-by-step backward reasoning.
89
+ - Write test cases according to the general task.
90
+
91
+ ## How to use code?
92
+ - Suggest python code (in a python coding block) or shell script (in a sh coding block) for the Computer_terminal to execute.
93
+ - If missing python packages, you can install the package by suggesting a `pip install` code in the ```sh ... ``` block.
94
+ - When using code, you must indicate the script type in the coding block.
95
+ - Do not the coding block which requires users to modify.
96
+ - Do not suggest a coding block if it's not intended to be executed by the Computer_terminal.
97
+ - The Computer_terminal cannot modify your code.
98
+ - **Use 'print' function for the output when relevant**.
99
+ - Check the execution result returned by the Computer_terminal.
100
+ - Do not ask Computer_terminal to copy and paste the result.
101
+ - If the result indicates there is an error, fix the error and output the code again. """
102
+
103
+ CODING_PROMPT = """Does the following task need programming (i.e., access external API or tool by coding) to solve,
104
+ or coding may help the following task become easier?
105
+
106
+ TASK: {task}
107
+
108
+ Answer only YES or NO.
109
+ """
110
+
111
+ AGENT_NAME_PROMPT = """# Your task
112
+ Suggest no more than {max_agents} experts with their name according to the following user requirement.
113
+
114
+ ## User requirement
115
+ {task}
116
+
117
+ # Task requirement
118
+ - Expert's name should follow the format: [skill]_Expert.
119
+ - Only reply the names of the experts, separated by ",".
120
+ For example: Python_Expert, Math_Expert, ... """
121
+
122
+ AGENT_SYS_MSG_PROMPT = """# Your goal
123
+ - According to the task and expert name, write a high-quality description for the expert by filling the given template.
124
+ - Ensure that your description are clear and unambiguous, and include all necessary information.
125
+
126
+ # Task
127
+ {task}
128
+
129
+ # Expert name
130
+ {position}
131
+
132
+ # Template
133
+ {default_sys_msg}
134
+ """
135
+
136
+ AGENT_DESCRIPTION_PROMPT = """# Your goal
137
+ Summarize the following expert's description in a sentence.
138
+
139
+ # Expert name
140
+ {position}
141
+
142
+ # Expert's description
143
+ {sys_msg}
144
+ """
145
+
146
+ AGENT_SEARCHING_PROMPT = """# Your goal
147
+ Considering the following task, what experts should be involved to the task?
148
+
149
+ # TASK
150
+ {task}
151
+
152
+ # EXPERT LIST
153
+ {agent_list}
154
+
155
+ # Requirement
156
+ - You should consider if the experts' name and profile match the task.
157
+ - Considering the effort, you should select less then {max_agents} experts; less is better.
158
+ - Separate expert names by commas and use "_" instead of space. For example, Product_manager,Programmer
159
+ - Only return the list of expert names.
160
+ """
161
+
162
+ AGENT_SELECTION_PROMPT = """# Your goal
163
+ Match roles in the role set to each expert in expert set.
164
+
165
+ # Skill set
166
+ {skills}
167
+
168
+ # Expert pool (formatting with name: description)
169
+ {expert_pool}
170
+
171
+ # Answer format
172
+ ```json
173
+ {{
174
+ "skill_1 description": "expert_name: expert_description", // if there exists an expert that suitable for skill_1
175
+ "skill_2 description": "None", // if there is no experts that suitable for skill_2
176
+ ...
177
+ }}
178
+ ```
179
+ """
180
+
181
+ def __init__(
182
+ self,
183
+ config_file_or_env: Optional[str] = "OAI_CONFIG_LIST",
184
+ config_file_location: Optional[str] = "",
185
+ builder_model: Optional[Union[str, list]] = [],
186
+ agent_model: Optional[Union[str, list]] = [],
187
+ builder_model_tags: Optional[list] = [],
188
+ agent_model_tags: Optional[list] = [],
189
+ max_agents: Optional[int] = 5,
190
+ ):
191
+ """
192
+ (These APIs are experimental and may change in the future.)
193
+ Args:
194
+ config_file_or_env: path or environment of the OpenAI api configs.
195
+ builder_model: specify a model as the backbone of build manager.
196
+ agent_model: specify a model as the backbone of participant agents.
197
+ endpoint_building_timeout: timeout for building up an endpoint server.
198
+ max_agents: max agents for each task.
199
+ """
200
+ builder_model = builder_model if isinstance(builder_model, list) else [builder_model]
201
+ builder_filter_dict = {}
202
+ if len(builder_model) != 0:
203
+ builder_filter_dict.update({"model": builder_model})
204
+ if len(builder_model_tags) != 0:
205
+ builder_filter_dict.update({"tags": builder_model_tags})
206
+ builder_config_list = autogen.config_list_from_json(config_file_or_env, filter_dict=builder_filter_dict)
207
+ if len(builder_config_list) == 0:
208
+ raise RuntimeError(
209
+ f"Fail to initialize build manager: {builder_model}{builder_model_tags} does not exist in {config_file_or_env}. "
210
+ f'If you want to change this model, please specify the "builder_model" in the constructor.'
211
+ )
212
+ self.builder_model = autogen.OpenAIWrapper(config_list=builder_config_list)
213
+
214
+ self.agent_model = agent_model if isinstance(agent_model, list) else [agent_model]
215
+ self.agent_model_tags = agent_model_tags
216
+ self.config_file_or_env = config_file_or_env
217
+ self.config_file_location = config_file_location
218
+
219
+ self.building_task: str = None
220
+ self.agent_configs: List[Dict] = []
221
+ self.open_ports: List[str] = []
222
+ self.agent_procs: Dict[str, Tuple[sp.Popen, str]] = {}
223
+ self.agent_procs_assign: Dict[str, Tuple[autogen.ConversableAgent, str]] = {}
224
+ self.cached_configs: Dict = {}
225
+
226
+ self.max_agents = max_agents
227
+
228
+ def set_builder_model(self, model: str):
229
+ self.builder_model = model
230
+
231
+ def set_agent_model(self, model: str):
232
+ self.agent_model = model
233
+
234
+ def _create_agent(
235
+ self,
236
+ agent_config: Dict,
237
+ member_name: List[str],
238
+ llm_config: dict,
239
+ use_oai_assistant: Optional[bool] = False,
240
+ ) -> autogen.AssistantAgent:
241
+ """
242
+ Create a group chat participant agent.
243
+
244
+ If the agent rely on an open-source model, this function will automatically set up an endpoint for that agent.
245
+ The API address of that endpoint will be "localhost:{free port}".
246
+
247
+ Args:
248
+ agent_config: agent's config. It should include the following information:
249
+ 1. model_name: backbone model of an agent, e.g., gpt-4-1106-preview, meta/Llama-2-70b-chat
250
+ 2. agent_name: use to identify an agent in the group chat.
251
+ 3. system_message: including persona, task solving instruction, etc.
252
+ 4. description: brief description of an agent that help group chat manager to pick the speaker.
253
+ llm_config: specific configs for LLM (e.g., config_list, seed, temperature, ...).
254
+ use_oai_assistant: use OpenAI assistant api instead of self-constructed agent.
255
+ world_size: the max size of parallel tensors (in most of the cases, this is identical to the amount of GPUs).
256
+
257
+ Returns:
258
+ agent: a set-up agent.
259
+ """
260
+ model_name_or_hf_repo = agent_config.get("model", [])
261
+ model_name_or_hf_repo = (
262
+ model_name_or_hf_repo if isinstance(model_name_or_hf_repo, list) else [model_name_or_hf_repo]
263
+ )
264
+ model_tags = agent_config.get("tags", [])
265
+ agent_name = agent_config["name"]
266
+ system_message = agent_config["system_message"]
267
+ description = agent_config["description"]
268
+
269
+ # Path to the customize **ConversableAgent** class.
270
+ model_path = agent_config.get("model_path", None)
271
+ filter_dict = {}
272
+ if len(model_name_or_hf_repo) > 0:
273
+ filter_dict.update({"model": model_name_or_hf_repo})
274
+ if len(model_tags) > 0:
275
+ filter_dict.update({"tags": model_tags})
276
+ config_list = autogen.config_list_from_json(
277
+ self.config_file_or_env, file_location=self.config_file_location, filter_dict=filter_dict
278
+ )
279
+ if len(config_list) == 0:
280
+ raise RuntimeError(
281
+ f"Fail to initialize agent {agent_name}: {model_name_or_hf_repo}{model_tags} does not exist in {self.config_file_or_env}.\n"
282
+ f'If you would like to change this model, please specify the "agent_model" in the constructor.\n'
283
+ f"If you load configs from json, make sure the model in agent_configs is in the {self.config_file_or_env}."
284
+ )
285
+ server_id = self.online_server_name
286
+ current_config = llm_config.copy()
287
+ current_config.update({"config_list": config_list})
288
+ if use_oai_assistant:
289
+ from autogen.agentchat.contrib.gpt_assistant_agent import GPTAssistantAgent
290
+
291
+ agent = GPTAssistantAgent(
292
+ name=agent_name,
293
+ llm_config={**current_config, "assistant_id": None},
294
+ instructions=system_message,
295
+ overwrite_instructions=False,
296
+ )
297
+ else:
298
+ user_proxy_desc = ""
299
+ if self.cached_configs["coding"] is True:
300
+ user_proxy_desc = (
301
+ "\nThe group also include a Computer_terminal to help you run the python and shell code."
302
+ )
303
+
304
+ model_class = autogen.AssistantAgent
305
+ if model_path:
306
+ module_path, model_class_name = model_path.replace("/", ".").rsplit(".", 1)
307
+ module = importlib.import_module(module_path)
308
+ model_class = getattr(module, model_class_name)
309
+ if not issubclass(model_class, autogen.ConversableAgent):
310
+ logger.error(f"{model_class} is not a ConversableAgent. Use AssistantAgent as default")
311
+ model_class = autogen.AssistantAgent
312
+
313
+ additional_config = {
314
+ k: v
315
+ for k, v in agent_config.items()
316
+ if k not in ["model", "name", "system_message", "description", "model_path", "tags"]
317
+ }
318
+ agent = model_class(
319
+ name=agent_name, llm_config=current_config.copy(), description=description, **additional_config
320
+ )
321
+ if system_message == "":
322
+ system_message = agent.system_message
323
+ else:
324
+ system_message = f"{system_message}\n\n{self.CODING_AND_TASK_SKILL_INSTRUCTION}"
325
+
326
+ enhanced_sys_msg = self.GROUP_CHAT_DESCRIPTION.format(
327
+ name=agent_name, members=member_name, user_proxy_desc=user_proxy_desc, sys_msg=system_message
328
+ )
329
+ agent.update_system_message(enhanced_sys_msg)
330
+ self.agent_procs_assign[agent_name] = (agent, server_id)
331
+ return agent
332
+
333
+ def clear_agent(self, agent_name: str, recycle_endpoint: Optional[bool] = True):
334
+ """
335
+ Clear a specific agent by name.
336
+
337
+ Args:
338
+ agent_name: the name of agent.
339
+ recycle_endpoint: trigger for recycle the endpoint server. If true, the endpoint will be recycled
340
+ when there is no agent depending on.
341
+ """
342
+ _, server_id = self.agent_procs_assign[agent_name]
343
+ del self.agent_procs_assign[agent_name]
344
+ if recycle_endpoint:
345
+ if server_id == self.online_server_name:
346
+ return
347
+ else:
348
+ for _, iter_sid in self.agent_procs_assign.values():
349
+ if server_id == iter_sid:
350
+ return
351
+ self.agent_procs[server_id][0].terminate()
352
+ self.open_ports.append(server_id.split("_")[-1])
353
+ print(colored(f"Agent {agent_name} has been cleared.", "yellow"), flush=True)
354
+
355
+ def clear_all_agents(self, recycle_endpoint: Optional[bool] = True):
356
+ """
357
+ Clear all cached agents.
358
+ """
359
+ for agent_name in [agent_name for agent_name in self.agent_procs_assign.keys()]:
360
+ self.clear_agent(agent_name, recycle_endpoint)
361
+ print(colored("All agents have been cleared.", "yellow"), flush=True)
362
+
363
+ def build(
364
+ self,
365
+ building_task: str,
366
+ default_llm_config: Dict,
367
+ coding: Optional[bool] = None,
368
+ code_execution_config: Optional[Dict] = None,
369
+ use_oai_assistant: Optional[bool] = False,
370
+ user_proxy: Optional[autogen.ConversableAgent] = None,
371
+ max_agents: Optional[int] = None,
372
+ **kwargs,
373
+ ) -> Tuple[List[autogen.ConversableAgent], Dict]:
374
+ """
375
+ Auto build agents based on the building task.
376
+
377
+ Args:
378
+ building_task: instruction that helps build manager (gpt-4) to decide what agent should be built.
379
+ coding: use to identify if the user proxy (a code interpreter) should be added.
380
+ code_execution_config: specific configs for user proxy (e.g., last_n_messages, work_dir, ...).
381
+ default_llm_config: specific configs for LLM (e.g., config_list, seed, temperature, ...).
382
+ use_oai_assistant: use OpenAI assistant api instead of self-constructed agent.
383
+ user_proxy: user proxy's class that can be used to replace the default user proxy.
384
+
385
+ Returns:
386
+ agent_list: a list of agents.
387
+ cached_configs: cached configs.
388
+ """
389
+ if code_execution_config is None:
390
+ code_execution_config = {
391
+ "last_n_messages": 1,
392
+ "work_dir": "groupchat",
393
+ "use_docker": False,
394
+ "timeout": 10,
395
+ }
396
+
397
+ if max_agents is None:
398
+ max_agents = self.max_agents
399
+
400
+ agent_configs = []
401
+ self.building_task = building_task
402
+
403
+ print(colored("==> Generating agents...", "green"), flush=True)
404
+ resp_agent_name = (
405
+ self.builder_model.create(
406
+ messages=[
407
+ {
408
+ "role": "user",
409
+ "content": self.AGENT_NAME_PROMPT.format(task=building_task, max_agents=max_agents),
410
+ }
411
+ ]
412
+ )
413
+ .choices[0]
414
+ .message.content
415
+ )
416
+ agent_name_list = [agent_name.strip().replace(" ", "_") for agent_name in resp_agent_name.split(",")]
417
+ print(f"{agent_name_list} are generated.", flush=True)
418
+
419
+ print(colored("==> Generating system message...", "green"), flush=True)
420
+ agent_sys_msg_list = []
421
+ for name in agent_name_list:
422
+ print(f"Preparing system message for {name}", flush=True)
423
+ resp_agent_sys_msg = (
424
+ self.builder_model.create(
425
+ messages=[
426
+ {
427
+ "role": "user",
428
+ "content": self.AGENT_SYS_MSG_PROMPT.format(
429
+ task=building_task,
430
+ position=name,
431
+ default_sys_msg=self.DEFAULT_DESCRIPTION,
432
+ ),
433
+ }
434
+ ]
435
+ )
436
+ .choices[0]
437
+ .message.content
438
+ )
439
+ agent_sys_msg_list.append(resp_agent_sys_msg)
440
+
441
+ print(colored("==> Generating description...", "green"), flush=True)
442
+ agent_description_list = []
443
+ for name, sys_msg in list(zip(agent_name_list, agent_sys_msg_list)):
444
+ print(f"Preparing description for {name}", flush=True)
445
+ resp_agent_description = (
446
+ self.builder_model.create(
447
+ messages=[
448
+ {
449
+ "role": "user",
450
+ "content": self.AGENT_DESCRIPTION_PROMPT.format(position=name, sys_msg=sys_msg),
451
+ }
452
+ ]
453
+ )
454
+ .choices[0]
455
+ .message.content
456
+ )
457
+ agent_description_list.append(resp_agent_description)
458
+
459
+ for name, sys_msg, description in list(zip(agent_name_list, agent_sys_msg_list, agent_description_list)):
460
+ agent_configs.append(
461
+ {
462
+ "name": name,
463
+ "model": self.agent_model,
464
+ "tags": self.agent_model_tags,
465
+ "system_message": sys_msg,
466
+ "description": description,
467
+ }
468
+ )
469
+
470
+ if coding is None:
471
+ resp = (
472
+ self.builder_model.create(
473
+ messages=[{"role": "user", "content": self.CODING_PROMPT.format(task=building_task)}]
474
+ )
475
+ .choices[0]
476
+ .message.content
477
+ )
478
+ coding = True if resp == "YES" else False
479
+
480
+ self.cached_configs.update(
481
+ {
482
+ "building_task": building_task,
483
+ "agent_configs": agent_configs,
484
+ "coding": coding,
485
+ "default_llm_config": default_llm_config,
486
+ "code_execution_config": code_execution_config,
487
+ }
488
+ )
489
+ _config_check(self.cached_configs)
490
+ return self._build_agents(use_oai_assistant, user_proxy=user_proxy, **kwargs)
491
+
492
+ def build_from_library(
493
+ self,
494
+ building_task: str,
495
+ library_path_or_json: str,
496
+ default_llm_config: Dict,
497
+ top_k: int = 3,
498
+ coding: Optional[bool] = None,
499
+ code_execution_config: Optional[Dict] = None,
500
+ use_oai_assistant: Optional[bool] = False,
501
+ embedding_model: Optional[str] = "all-mpnet-base-v2",
502
+ user_proxy: Optional[autogen.ConversableAgent] = None,
503
+ **kwargs,
504
+ ) -> Tuple[List[autogen.ConversableAgent], Dict]:
505
+ """
506
+ Build agents from a library.
507
+ The library is a list of agent configs, which contains the name and system_message for each agent.
508
+ We use a build manager to decide what agent in that library should be involved to the task.
509
+
510
+ Args:
511
+ building_task: instruction that helps build manager (gpt-4) to decide what agent should be built.
512
+ library_path_or_json: path or JSON string config of agent library.
513
+ default_llm_config: specific configs for LLM (e.g., config_list, seed, temperature, ...).
514
+ coding: use to identify if the user proxy (a code interpreter) should be added.
515
+ code_execution_config: specific configs for user proxy (e.g., last_n_messages, work_dir, ...).
516
+ use_oai_assistant: use OpenAI assistant api instead of self-constructed agent.
517
+ embedding_model: a Sentence-Transformers model use for embedding similarity to select agents from library.
518
+ As reference, chromadb use "all-mpnet-base-v2" as default.
519
+ user_proxy: user proxy's class that can be used to replace the default user proxy.
520
+
521
+ Returns:
522
+ agent_list: a list of agents.
523
+ cached_configs: cached configs.
524
+ """
525
+ import sqlite3
526
+
527
+ # Some system will have an unexcepted sqlite3 version.
528
+ # Check if the user has installed pysqlite3.
529
+ if int(sqlite3.version.split(".")[0]) < 3:
530
+ try:
531
+ __import__("pysqlite3")
532
+ import sys
533
+
534
+ sys.modules["sqlite3"] = sys.modules.pop("pysqlite3")
535
+ except Exception as e:
536
+ raise e
537
+ import chromadb
538
+ from chromadb.utils import embedding_functions
539
+
540
+ if code_execution_config is None:
541
+ code_execution_config = {
542
+ "last_n_messages": 1,
543
+ "work_dir": "groupchat",
544
+ "use_docker": False,
545
+ "timeout": 120,
546
+ }
547
+
548
+ try:
549
+ agent_library = json.loads(library_path_or_json)
550
+ except json.decoder.JSONDecodeError:
551
+ with open(library_path_or_json, "r") as f:
552
+ agent_library = json.load(f)
553
+ except Exception as e:
554
+ raise e
555
+
556
+ print(colored("==> Looking for suitable agents in the library...", "green"), flush=True)
557
+ skills = building_task.replace(":", " ").split("\n")
558
+ # skills = [line.split("-", 1)[1].strip() if line.startswith("-") else line for line in lines]
559
+ if len(skills) == 0:
560
+ skills = [building_task]
561
+
562
+ chroma_client = chromadb.Client()
563
+ collection = chroma_client.create_collection(
564
+ name="agent_list",
565
+ embedding_function=embedding_functions.SentenceTransformerEmbeddingFunction(model_name=embedding_model),
566
+ )
567
+ collection.add(
568
+ documents=[agent["description"] for agent in agent_library],
569
+ metadatas=[{"source": "agent_profile"} for _ in range(len(agent_library))],
570
+ ids=[f"agent_{i}" for i in range(len(agent_library))],
571
+ )
572
+ agent_desc_list = set()
573
+ for skill in skills:
574
+ recall = set(collection.query(query_texts=[skill], n_results=top_k)["documents"][0])
575
+ agent_desc_list = agent_desc_list.union(recall)
576
+
577
+ agent_config_list = []
578
+ for description in list(agent_desc_list):
579
+ for agent in agent_library:
580
+ if agent["description"] == description:
581
+ agent_config_list.append(agent.copy())
582
+ break
583
+ chroma_client.delete_collection(collection.name)
584
+
585
+ # double recall from the searching result
586
+ expert_pool = [f"{agent['name']}: {agent['description']}" for agent in agent_config_list]
587
+ while True:
588
+ skill_agent_pair_json = (
589
+ self.builder_model.create(
590
+ messages=[
591
+ {
592
+ "role": "user",
593
+ "content": self.AGENT_SELECTION_PROMPT.format(
594
+ skills=building_task, expert_pool=expert_pool, max_agents=self.max_agents
595
+ ),
596
+ }
597
+ ]
598
+ )
599
+ .choices[0]
600
+ .message.content
601
+ )
602
+ try:
603
+ skill_agent_pair_json = _retrieve_json(skill_agent_pair_json)
604
+ skill_agent_pair = json.loads(skill_agent_pair_json)
605
+ break
606
+ except Exception as e:
607
+ print(e, flush=True)
608
+ time.sleep(5)
609
+ continue
610
+
611
+ recalled_agent_config_list = []
612
+ recalled_name_desc = []
613
+ for skill, agent_profile in skill_agent_pair.items():
614
+ # If no suitable agent, generate an agent
615
+ if agent_profile == "None":
616
+ _, agent_config_temp = self.build(
617
+ building_task=skill,
618
+ default_llm_config=default_llm_config.copy(),
619
+ coding=False,
620
+ use_oai_assistant=use_oai_assistant,
621
+ max_agents=1,
622
+ )
623
+ self.clear_agent(agent_config_temp["agent_configs"][0]["name"])
624
+ recalled_agent_config_list.append(agent_config_temp["agent_configs"][0])
625
+ else:
626
+ if agent_profile in recalled_name_desc:
627
+ # prevent identical agents
628
+ continue
629
+ recalled_name_desc.append(agent_profile)
630
+ name = agent_profile.split(":")[0].strip()
631
+ desc = agent_profile.split(":")[1].strip()
632
+ for agent in agent_config_list:
633
+ if name == agent["name"] and desc == agent["description"]:
634
+ recalled_agent_config_list.append(agent.copy())
635
+
636
+ print(f"{[agent['name'] for agent in recalled_agent_config_list]} are selected.", flush=True)
637
+
638
+ if coding is None:
639
+ resp = (
640
+ self.builder_model.create(
641
+ messages=[{"role": "user", "content": self.CODING_PROMPT.format(task=building_task)}]
642
+ )
643
+ .choices[0]
644
+ .message.content
645
+ )
646
+ coding = True if resp == "YES" else False
647
+
648
+ self.cached_configs.update(
649
+ {
650
+ "building_task": building_task,
651
+ "agent_configs": recalled_agent_config_list,
652
+ "coding": coding,
653
+ "default_llm_config": default_llm_config,
654
+ "code_execution_config": code_execution_config,
655
+ }
656
+ )
657
+ _config_check(self.cached_configs)
658
+
659
+ return self._build_agents(use_oai_assistant, user_proxy=user_proxy, **kwargs)
660
+
661
+ def _build_agents(
662
+ self, use_oai_assistant: Optional[bool] = False, user_proxy: Optional[autogen.ConversableAgent] = None, **kwargs
663
+ ) -> Tuple[List[autogen.ConversableAgent], Dict]:
664
+ """
665
+ Build agents with generated configs.
666
+
667
+ Args:
668
+ use_oai_assistant: use OpenAI assistant api instead of self-constructed agent.
669
+ user_proxy: user proxy's class that can be used to replace the default user proxy.
670
+
671
+ Returns:
672
+ agent_list: a list of agents.
673
+ cached_configs: cached configs.
674
+ """
675
+ agent_configs = self.cached_configs["agent_configs"]
676
+ default_llm_config = self.cached_configs["default_llm_config"]
677
+ coding = self.cached_configs["coding"]
678
+ code_execution_config = self.cached_configs["code_execution_config"]
679
+
680
+ print(colored("==> Creating agents...", "green"), flush=True)
681
+ for config in agent_configs:
682
+ print(f"Creating agent {config['name']}...", flush=True)
683
+ self._create_agent(
684
+ agent_config=config.copy(),
685
+ member_name=[agent["name"] for agent in agent_configs],
686
+ llm_config=default_llm_config,
687
+ use_oai_assistant=use_oai_assistant,
688
+ **kwargs,
689
+ )
690
+ agent_list = [agent_config[0] for agent_config in self.agent_procs_assign.values()]
691
+
692
+ if coding is True:
693
+ print("Adding user console proxy...", flush=True)
694
+ if user_proxy is None:
695
+ user_proxy = autogen.UserProxyAgent(
696
+ name="Computer_terminal",
697
+ is_termination_msg=lambda x: x == "TERMINATE" or x == "TERMINATE.",
698
+ code_execution_config=code_execution_config,
699
+ human_input_mode="NEVER",
700
+ default_auto_reply=self.DEFAULT_PROXY_AUTO_REPLY,
701
+ )
702
+ agent_list = agent_list + [user_proxy]
703
+
704
+ return agent_list, self.cached_configs.copy()
705
+
706
+ def save(self, filepath: Optional[str] = None) -> str:
707
+ """
708
+ Save building configs. If the filepath is not specific, this function will create a filename by encrypt the
709
+ building_task string by md5 with "save_config_" prefix, and save config to the local path.
710
+
711
+ Args:
712
+ filepath: save path.
713
+
714
+ Return:
715
+ filepath: path save.
716
+ """
717
+ if filepath is None:
718
+ filepath = f'./save_config_{hashlib.md5(self.building_task.encode("utf-8")).hexdigest()}.json'
719
+ with open(filepath, "w") as save_file:
720
+ json.dump(self.cached_configs, save_file, indent=4)
721
+ print(colored(f"Building config saved to {filepath}", "green"), flush=True)
722
+
723
+ return filepath
724
+
725
+ def load(
726
+ self,
727
+ filepath: Optional[str] = None,
728
+ config_json: Optional[str] = None,
729
+ use_oai_assistant: Optional[bool] = False,
730
+ **kwargs,
731
+ ) -> Tuple[List[autogen.ConversableAgent], Dict]:
732
+ """
733
+ Load building configs and call the build function to complete building without calling online LLMs' api.
734
+
735
+ Args:
736
+ filepath: filepath or JSON string for the save config.
737
+ config_json: JSON string for the save config.
738
+ use_oai_assistant: use OpenAI assistant api instead of self-constructed agent.
739
+
740
+ Returns:
741
+ agent_list: a list of agents.
742
+ cached_configs: cached configs.
743
+ """
744
+ # load json string.
745
+ if config_json is not None:
746
+ print(colored("Loading config from JSON...", "green"), flush=True)
747
+ cached_configs = json.loads(config_json)
748
+
749
+ # load from path.
750
+ if filepath is not None:
751
+ print(colored(f"Loading config from {filepath}", "green"), flush=True)
752
+ with open(filepath) as f:
753
+ cached_configs = json.load(f)
754
+
755
+ _config_check(cached_configs)
756
+
757
+ agent_configs = cached_configs["agent_configs"]
758
+ default_llm_config = cached_configs["default_llm_config"]
759
+ coding = cached_configs["coding"]
760
+
761
+ if kwargs.get("code_execution_config", None) is not None:
762
+ # for test
763
+ self.cached_configs.update(
764
+ {
765
+ "building_task": cached_configs["building_task"],
766
+ "agent_configs": agent_configs,
767
+ "coding": coding,
768
+ "default_llm_config": default_llm_config,
769
+ "code_execution_config": kwargs["code_execution_config"],
770
+ }
771
+ )
772
+ del kwargs["code_execution_config"]
773
+ return self._build_agents(use_oai_assistant, **kwargs)
774
+ else:
775
+ code_execution_config = cached_configs["code_execution_config"]
776
+ self.cached_configs.update(
777
+ {
778
+ "building_task": cached_configs["building_task"],
779
+ "agent_configs": agent_configs,
780
+ "coding": coding,
781
+ "default_llm_config": default_llm_config,
782
+ "code_execution_config": code_execution_config,
783
+ }
784
+ )
785
+ return self._build_agents(use_oai_assistant, **kwargs)