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