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