ag2 0.4.1__py3-none-any.whl → 0.5.0__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.0.dist-info}/METADATA +5 -146
  2. ag2-0.5.0.dist-info/RECORD +6 -0
  3. ag2-0.5.0.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.0.dist-info}/LICENSE +0 -0
  159. {ag2-0.4.1.dist-info → ag2-0.5.0.dist-info}/NOTICE.md +0 -0
  160. {ag2-0.4.1.dist-info → ag2-0.5.0.dist-info}/WHEEL +0 -0
@@ -1,450 +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 copy
8
- import json
9
- from typing import Dict, List, Literal, Optional, Union
10
-
11
- import autogen
12
- from autogen.code_utils import execute_code
13
-
14
- ADD_FUNC = {
15
- "type": "function",
16
- "function": {
17
- "name": "add_function",
18
- "description": "Add a function in the context of the conversation. Necessary Python packages must be declared. The name of the function MUST be the same with the function name in the code you generated.",
19
- "parameters": {
20
- "type": "object",
21
- "properties": {
22
- "name": {"type": "string", "description": "The name of the function in the code implementation."},
23
- "description": {"type": "string", "description": "A short description of the function."},
24
- "arguments": {
25
- "type": "string",
26
- "description": 'JSON schema of arguments encoded as a string. Please note that the JSON schema only supports specific types including string, integer, object, array, boolean. (do not have float type) For example: { "url": { "type": "string", "description": "The URL", }}. Please avoid the error \'array schema missing items\' when using array type.',
27
- },
28
- "packages": {
29
- "type": "string",
30
- "description": "A list of package names imported by the function, and that need to be installed with pip prior to invoking the function. This solves ModuleNotFoundError. It should be string, not list.",
31
- },
32
- "code": {
33
- "type": "string",
34
- "description": "The implementation in Python. Do not include the function declaration.",
35
- },
36
- },
37
- "required": ["name", "description", "arguments", "packages", "code"],
38
- },
39
- },
40
- }
41
-
42
- REVISE_FUNC = {
43
- "type": "function",
44
- "function": {
45
- "name": "revise_function",
46
- "description": "Revise a function in the context of the conversation. Necessary Python packages must be declared. The name of the function MUST be the same with the function name in the code you generated.",
47
- "parameters": {
48
- "type": "object",
49
- "properties": {
50
- "name": {"type": "string", "description": "The name of the function in the code implementation."},
51
- "description": {"type": "string", "description": "A short description of the function."},
52
- "arguments": {
53
- "type": "string",
54
- "description": 'JSON schema of arguments encoded as a string. Please note that the JSON schema only supports specific types including string, integer, object, array, boolean. (do not have float type) For example: { "url": { "type": "string", "description": "The URL", }}. Please avoid the error \'array schema missing items\' when using array type.',
55
- },
56
- "packages": {
57
- "type": "string",
58
- "description": "A list of package names imported by the function, and that need to be installed with pip prior to invoking the function. This solves ModuleNotFoundError. It should be string, not list.",
59
- },
60
- "code": {
61
- "type": "string",
62
- "description": "The implementation in Python. Do not include the function declaration.",
63
- },
64
- },
65
- "required": ["name", "description", "arguments", "packages", "code"],
66
- },
67
- },
68
- }
69
-
70
- REMOVE_FUNC = {
71
- "type": "function",
72
- "function": {
73
- "name": "remove_function",
74
- "description": "Remove one function in the context of the conversation. Once remove one function, the assistant will not use this function in future conversation.",
75
- "parameters": {
76
- "type": "object",
77
- "properties": {
78
- "name": {"type": "string", "description": "The name of the function in the code implementation."}
79
- },
80
- "required": ["name"],
81
- },
82
- },
83
- }
84
-
85
- OPT_PROMPT = """You are a function optimizer. Your task is to maintain a list of functions for the assistant according to the existing function list and conversation history that happens between the assistant and the user.
86
- You can perform one of the following four actions to manipulate the function list using the functions you have:
87
- 1. Revise one existing function (using revise_function).
88
- 2. Remove one existing function (using remove_function).
89
- 3. Add one new function (using add_function).
90
- 4. Directly return "TERMINATE" to me if no more actions are needed for the current function list.
91
-
92
- Below are the principles that you need to follow for taking these four actions.
93
- (1) Revise one existing function:
94
- 1. Pay more attention to the failed tasks and corresponding error information, and optimize the function used in these tasks according to the conversation history if needed.
95
- 2. A failed function call can occur due to incorrect input arguments (missing arguments) or an incorrect function code implementation. You should focus more on the function code implementation and make it easy to get success function call.
96
- 3. Do not revise the function that you think works well and plays a critical role in solving the problems according to the conversation history. Only making revisions if needed.
97
- 4. Sometimes, a NameError may occur. To fix this error, you can either revise the name of the function in the code implementation or revise the name of the function call to make these two names consistent.
98
- (2) Remove one existing function:
99
- 1. Only remove the function that you think is not needed anymore in future tasks.
100
- (3) Add one new function:
101
- 1. The added function should be general enough to be used in future tasks. For instance, if you encounter a problem that this function can solve, or one step of it, you can use the generated function directly instead of starting from scratch
102
- 2. The added new function should solve a higher-level question that encompasses the original query and extend the code's functionality to make it more versatile and widely applicable.
103
- 3. Replace specific strings or variable names with general variables to enhance the tool's applicability to various queries. All names used inside the function should be passed in as arguments.
104
- Below is an example of a function that potentially deserves to be adde in solving MATH problems, which can be used to solve a higher-level question:
105
- {{
106
- \"name\": \"evaluate_expression\",
107
- \"description\": \"Evaluate arithmetic or mathematical expressions provided as strings.\",
108
- \"arguments\": {{
109
- \"expression\": {{
110
- \"type\": \"string\",
111
- \"description\": \"The mathematical expression to evaluate.\"
112
- }}
113
- }},
114
- \"packages\": \"sympy\",
115
- \"code\": \"from sympy import sympify, SympifyError\\n\\ndef evaluate_expression(expression):\\n try:\\n result = sympify(expression)\\n if result.is_number:\\n result = float(result)\\n else:\\n result = str(result)\\n return result\\n except SympifyError as e:\\n return str(e)\"
116
- }}
117
- (4) Directly return "TERMINATE":
118
- If you think there is no need to perform any other actions for the current function list since the current list is optimal more actions will harm the performance in future tasks. Please directly reply to me with "TERMINATE".
119
-
120
- One function signature includes the following five elements:
121
- 1. Function name
122
- 2. Function description
123
- 3. JSON schema of arguments encoded as a string
124
- 4. A list of package names imported by the function packages
125
- 5. The code implementation
126
-
127
- Below are the signatures of the current functions:
128
- List A: {best_functions}.
129
- The following list are the function signatures that you have after taking {actions_num} actions to manipulate List A:
130
- List B: {incumbent_functions}.
131
-
132
- {accumulated_experience}
133
-
134
- Here are {best_conversations_num} conversation histories of solving {best_conversations_num} tasks using List A.
135
- History:
136
- {best_conversations_history}
137
-
138
- {statistic_informations}
139
-
140
- According to the information I provide, please take one of four actions to manipulate list B using the functions you know.
141
- Instead of returning TERMINATE directly or taking no action, you should try your best to optimize the function list. Only take no action if you really think the current list is optimal, as more actions will harm performance in future tasks.
142
- Even adding a general function that can substitute the assistant’s repeated suggestions of Python code with the same functionality could also be helpful.
143
- """
144
-
145
-
146
- def execute_func(name, packages, code, **args):
147
- """
148
- The wrapper for generated functions.
149
- """
150
- pip_install = (
151
- f"""print("Installing package: {packages}")\nsubprocess.run(["pip", "-qq", "install", "{packages}"])"""
152
- if packages
153
- else ""
154
- )
155
- str = f"""
156
- import subprocess
157
- {pip_install}
158
- print("Result of {name} function execution:")
159
- {code}
160
- args={args}
161
- result={name}(**args)
162
- if result is not None: print(result)
163
- """
164
- print(f"execute_code:\n{str}")
165
- result = execute_code(str, use_docker="shaokun529/evoagent:v1")
166
- if result[0] != 0:
167
- raise Exception("Error in executing function:" + result[1])
168
- print(f"Result: {result[1]}")
169
- return result[1]
170
-
171
-
172
- class AgentOptimizer:
173
- """
174
- Base class for optimizing AutoGen agents. Specifically, it is used to optimize the functions used in the agent.
175
- More information could be found in the following paper: https://arxiv.org/abs/2402.11359.
176
- """
177
-
178
- def __init__(
179
- self,
180
- max_actions_per_step: int,
181
- llm_config: dict,
182
- optimizer_model: Optional[str] = "gpt-4-1106-preview",
183
- ):
184
- """
185
- (These APIs are experimental and may change in the future.)
186
- Args:
187
- max_actions_per_step (int): the maximum number of actions that the optimizer can take in one step.
188
- llm_config (dict): llm inference configuration.
189
- Please refer to [OpenAIWrapper.create](/docs/reference/oai/client#create) for available options.
190
- When using OpenAI or Azure OpenAI endpoints, please specify a non-empty 'model' either in `llm_config` or in each config of 'config_list' in `llm_config`.
191
- optimizer_model: the model used for the optimizer.
192
- """
193
- self.max_actions_per_step = max_actions_per_step
194
- self._max_trials = 3
195
- self.optimizer_model = optimizer_model
196
-
197
- self._trial_conversations_history = []
198
- self._trial_conversations_performance = []
199
- self._trial_functions = []
200
-
201
- self._best_conversations_history = []
202
- self._best_conversations_performance = []
203
- self._best_functions = []
204
-
205
- self._failure_functions_performance = []
206
- self._best_performance = -1
207
-
208
- assert isinstance(llm_config, dict), "llm_config must be a dict"
209
- llm_config = copy.deepcopy(llm_config)
210
- self.llm_config = llm_config
211
- if self.llm_config in [{}, {"config_list": []}, {"config_list": [{"model": ""}]}]:
212
- raise ValueError(
213
- "When using OpenAI or Azure OpenAI endpoints, specify a non-empty 'model' either in 'llm_config' or in each config of 'config_list'."
214
- )
215
- self.llm_config["config_list"] = autogen.filter_config(
216
- llm_config["config_list"], {"model": [self.optimizer_model]}
217
- )
218
- self._client = autogen.OpenAIWrapper(**self.llm_config)
219
-
220
- def record_one_conversation(self, conversation_history: List[Dict], is_satisfied: bool = None):
221
- """
222
- record one conversation history.
223
- Args:
224
- conversation_history (List[Dict]): the chat messages of the conversation.
225
- is_satisfied (bool): whether the user is satisfied with the solution. If it is none, the user will be asked to input the satisfaction.
226
- """
227
- if is_satisfied is None:
228
- reply = input(
229
- "Please provide whether the user is satisfied with the solution. 1 represents satisfied. 0 represents not satisfied. Press enter to submit. \n"
230
- )
231
- assert reply in [
232
- "0",
233
- "1",
234
- ], "The input is invalid. Please input 1 or 0. 1 represents satisfied. 0 represents not satisfied."
235
- is_satisfied = True if reply == "1" else False
236
- self._trial_conversations_history.append(
237
- {"Conversation {i}".format(i=len(self._trial_conversations_history)): conversation_history}
238
- )
239
- self._trial_conversations_performance.append(
240
- {"Conversation {i}".format(i=len(self._trial_conversations_performance)): 1 if is_satisfied else 0}
241
- )
242
-
243
- def step(self):
244
- """
245
- One step of training. It will return register_for_llm and register_for_executor at each iteration,
246
- which are subsequently utilized to update the assistant and executor agents, respectively.
247
- See example: https://github.com/ag2ai/ag2/blob/main/notebook/agentchat_agentoptimizer.ipynb
248
- """
249
- performance = sum(sum(d.values()) for d in self._trial_conversations_performance) / len(
250
- self._trial_conversations_performance
251
- )
252
-
253
- if performance < self._best_performance:
254
- self._failure_functions_performance.append({"functions": self._trial_functions, "performance": performance})
255
- self._failure_functions_performance = sorted(
256
- self._failure_functions_performance, key=lambda x: x["performance"]
257
- )
258
- else:
259
- self._failure_functions_performance = []
260
- self._best_performance = performance
261
- self._best_functions = copy.deepcopy(self._trial_functions)
262
- self._best_conversations_history = copy.deepcopy(self._trial_conversations_history)
263
- self._best_conversations_performance = copy.deepcopy(self._trial_conversations_performance)
264
- self._trial_conversations_history = []
265
- self._trial_conversations_performance = []
266
-
267
- best_functions = copy.deepcopy(self._best_functions)
268
- incumbent_functions = copy.deepcopy(self._best_functions)
269
- failure_experience_prompt, statistic_prompt = self._construct_intermediate_prompt()
270
-
271
- for action_index in range(self.max_actions_per_step):
272
- prompt = OPT_PROMPT.format(
273
- best_conversations_history=self._best_conversations_history,
274
- best_conversations_num=len(self._best_conversations_history),
275
- actions_num=action_index,
276
- best_functions=best_functions,
277
- incumbent_functions=incumbent_functions,
278
- accumulated_experience=failure_experience_prompt,
279
- statistic_informations=statistic_prompt,
280
- )
281
- messages = [{"role": "user", "content": prompt}]
282
- for _ in range(self._max_trials):
283
- response = self._client.create(
284
- messages=messages, tools=[ADD_FUNC, REVISE_FUNC, REMOVE_FUNC], tool_choice="auto"
285
- )
286
- actions = response.choices[0].message.tool_calls
287
- if self._validate_actions(actions, incumbent_functions):
288
- break
289
- if actions is not None and self._validate_actions(actions, incumbent_functions):
290
- incumbent_functions = self._update_function_call(incumbent_functions, actions)
291
-
292
- remove_functions = list(
293
- set([key for dictionary in self._trial_functions for key in dictionary.keys()])
294
- - set([key for dictionary in incumbent_functions for key in dictionary.keys()])
295
- )
296
-
297
- register_for_llm = []
298
- register_for_exector = {}
299
- for name in remove_functions:
300
- register_for_llm.append({"func_sig": {"name": name}, "is_remove": True})
301
- register_for_exector.update({name: None})
302
- for func in incumbent_functions:
303
- register_for_llm.append(
304
- {
305
- "func_sig": {
306
- "name": func.get("name"),
307
- "description": func.get("description"),
308
- "parameters": {"type": "object", "properties": func.get("arguments")},
309
- },
310
- "is_remove": False,
311
- }
312
- )
313
- register_for_exector.update(
314
- {
315
- func.get("name"): lambda **args: execute_func(
316
- func.get("name"), func.get("packages"), func.get("code"), **args
317
- )
318
- }
319
- )
320
-
321
- self._trial_functions = incumbent_functions
322
- return register_for_llm, register_for_exector
323
-
324
- def reset_optimizer(self):
325
- """
326
- reset the optimizer.
327
- """
328
-
329
- self._trial_conversations_history = []
330
- self._trial_conversations_performance = []
331
- self._trial_functions = []
332
-
333
- self._best_conversations_history = []
334
- self._best_conversations_performance = []
335
- self._best_functions = []
336
-
337
- self._best_performance = -1
338
- self._failure_functions_performance = []
339
-
340
- def _update_function_call(self, incumbent_functions, actions):
341
- """
342
- update function call.
343
- """
344
-
345
- formated_actions = []
346
- for action in actions:
347
- func = json.loads(action.function.arguments.strip('"'))
348
- func["action_name"] = action.function.name
349
-
350
- if func.get("action_name") == "remove_function":
351
- item = {
352
- "action_name": func.get("action_name"),
353
- "name": func.get("name"),
354
- }
355
- else:
356
- item = {
357
- "action_name": func.get("action_name"),
358
- "name": func.get("name"),
359
- "description": func.get("description"),
360
- "arguments": json.loads(func.get("arguments").strip('"')),
361
- "packages": func.get("packages"),
362
- "code": func.get("code"),
363
- }
364
- formated_actions.append(item)
365
- actions = formated_actions
366
-
367
- for action in actions:
368
- name, description, arguments, packages, code, action_name = (
369
- action.get("name"),
370
- action.get("description"),
371
- action.get("arguments"),
372
- action.get("packages"),
373
- action.get("code"),
374
- action.get("action_name"),
375
- )
376
- if action_name == "remove_function":
377
- incumbent_functions = [item for item in incumbent_functions if item["name"] != name]
378
- else:
379
- incumbent_functions = [item for item in incumbent_functions if item["name"] != name]
380
- incumbent_functions.append(
381
- {
382
- "name": name,
383
- "description": description,
384
- "arguments": arguments,
385
- "packages": packages,
386
- "code": code,
387
- }
388
- )
389
-
390
- return incumbent_functions
391
-
392
- def _construct_intermediate_prompt(self):
393
- """
394
- construct intermediate prompts.
395
- """
396
- if len(self._failure_functions_performance) != 0:
397
- failure_experience_prompt = "We also provide more examples for different functions and their corresponding performance (0-100).\n The following function signatures are arranged in are arranged in ascending order based on their performance, where higher performance indicate better quality."
398
- failure_experience_prompt += "\n"
399
- for item in self._failure_functions_performance:
400
- failure_experience_prompt += "Function: \n" + str(item["functions"]) + "\n"
401
- failure_experience_prompt += "Performance: \n" + str(item["performance"]) + "\n"
402
- else:
403
- failure_experience_prompt = "\n"
404
-
405
- if len(self._best_conversations_performance) != 0:
406
- statistic_prompt = "The following table shows the statistical information for solving each task in each conversation and indicates, whether the result is satisfied by the users. 1 represents satisfied. 0 represents not satisfied."
407
- statistic_prompt += "\n"
408
- for item in self._best_conversations_performance:
409
- statistic_prompt += str(item) + "\n"
410
- else:
411
- statistic_prompt = "\n"
412
-
413
- return failure_experience_prompt, statistic_prompt
414
-
415
- def _validate_actions(self, actions, incumbent_functions):
416
- """
417
- validate whether the proposed actions are feasible.
418
- """
419
- if actions is None:
420
- return True
421
- else:
422
- # val json format
423
- for action in actions:
424
- function_args = action.function.arguments
425
- try:
426
- function_args = json.loads(function_args.strip('"'))
427
- if "arguments" in function_args.keys():
428
- json.loads(function_args.get("arguments").strip('"'))
429
- except Exception as e:
430
- print("JSON is invalid:", e)
431
- return False
432
- # val syntax
433
- for action in actions:
434
- if action.function.name != "remove_function":
435
- function_args = json.loads(action.function.arguments.strip('"'))
436
- code = function_args.get("code")
437
- try:
438
- compile(code, "<string>", "exec")
439
- print("successfully compiled")
440
- except Exception as e:
441
- print("Syntax is invalid:", e)
442
- return False
443
- for action in actions:
444
- action_name = action.function.name
445
- if action_name == "remove_function":
446
- function_args = json.loads(action.function.arguments.strip('"'))
447
- if function_args.get("name") not in [item["name"] for item in incumbent_functions]:
448
- print("The function you want to remove does not exist.")
449
- return False
450
- return True
File without changes
@@ -1,21 +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
- from autogen.agentchat.assistant_agent import ConversableAgent
8
-
9
-
10
- class AgentCapability:
11
- """Base class for composable capabilities that can be added to an agent."""
12
-
13
- def __init__(self):
14
- pass
15
-
16
- def add_to_agent(self, agent: ConversableAgent):
17
- """
18
- Adds a particular capability to the given agent. Must be implemented by the capability subclass.
19
- An implementation will typically call agent.register_hook() one or more times. See teachability.py as an example.
20
- """
21
- raise NotImplementedError