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,16 +0,0 @@
1
- # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
- #
3
- # SPDX-License-Identifier: Apache-2.0
4
- def sum_of_primes_below(threshold):
5
- """
6
- Calculates the sum of all prime numbers below a given threshold.
7
-
8
- Args:
9
- threshold (int): The maximum number (exclusive) up to which primes are summed.
10
-
11
- Returns:
12
- int: The sum of all prime numbers below the threshold.
13
- """
14
- from sympy import primerange
15
-
16
- return sum(primerange(2, threshold))
@@ -1,10 +0,0 @@
1
- markdownify
2
- arxiv
3
- pymupdf
4
- wikipedia-api
5
- easyocr
6
- python-pptx
7
- openai-whisper
8
- pandas
9
- scipy
10
- sentence-transformers
@@ -1,34 +0,0 @@
1
- docid document_content
2
- 1 math complex_numbers_product Calculates the product of a list of complex numbers.
3
- 2 math calculate_matrix_power Calculate the power of a given matrix.
4
- 3 math calculate_day_of_the_week Calculates the day of the week after a given number of days starting from a specified day.
5
- 4 math modular_inverse_sum Calculates the sum of modular inverses of the given expressions modulo the specified modulus.
6
- 5 math sum_of_digit_factorials Calculates the sum of the factorial of each digit in a number, often used in problems involving curious numbers like 145.
7
- 6 math sum_of_primes_below Calculates the sum of all prime numbers below a given threshold.
8
- 7 math evaluate_expression Evaluates a mathematical expression with support for floor function notation and power notation.
9
- 8 math compute_currency_conversion Compute the currency conversion of the given amount using the provided exchange rate.
10
- 9 math find_continuity_point Find the value 'a' that ensures the continuity of a piecewise function at a given point.
11
- 10 math simplify_mixed_numbers Simplifies the sum of two mixed numbers and returns the result as a string in the format 'a b/c'.
12
- 11 math fraction_to_mixed_numbers Simplifies a fraction to its lowest terms and returns it as a mixed number.
13
- 12 math calculate_fraction_sum Calculates the sum of two fractions and returns the result as a mixed number.
14
- 13 math count_distinct_permutations Counts the number of distinct permutations of a sequence where items may be indistinguishable.
15
- 14 math calculate_circle_area_from_diameter Calculate the area of a circle given its diameter.
16
- 15 math calculate_reflected_point Calculates the reflection point of a given point about the line y=x.
17
- 16 data_analysis explore_csv Reads a CSV file and prints the column names, shape, data types, and the first few lines of data.
18
- 17 data_analysis calculate_correlation Calculate the correlation between two columns in a CSV file.
19
- 18 data_analysis detect_outlier_zscore Detect outliers in a CSV file based on a specified column. The outliers are determined by calculating the z-score of the data points in the column.
20
- 19 data_analysis detect_outlier_iqr Detect outliers in a specified column of a CSV file using the IQR method.
21
- 20 data_analysis shapiro_wilk_test Perform the Shapiro-Wilk test on a specified column of a CSV file.
22
- 21 data_analysis calculate_skewness_and_kurtosis Calculate the skewness and kurtosis of a specified column in a CSV file. The kurtosis is calculated using the Fisher definition. The two metrics are computed using scipy.stats functions.
23
- 22 information_retrieval perform_web_search Perform a web search using Bing API.
24
- 23 information_retrieval transcribe_audio_file Transcribes the audio file located at the given file path.
25
- 24 information_retrieval arxiv_search Search for articles on arXiv based on the given query.
26
- 25 information_retrieval arxiv_download Downloads PDF files from ArXiv based on a list of arxiv paper IDs.
27
- 26 information_retrieval scrape_wikipedia_tables Scrapes Wikipedia tables based on a given URL and header keyword.
28
- 27 information_retrieval extract_pdf_text Extracts text from a specified page or the entire PDF file.
29
- 28 information_retrieval extract_pdf_image Extracts images from a PDF file and saves them to the specified output directory.
30
- 29 information_retrieval image_qa Perform question answering on an image using a pre-trained VQA model.
31
- 30 information_retrieval optical_character_recognition Perform optical character recognition (OCR) on the given image.
32
- 31 information_retrieval get_youtube_caption Retrieves the captions for a YouTube video.
33
- 32 information_retrieval youtube_download Downloads a YouTube video and returns the download link.
34
- 33 information_retrieval get_wikipedia_text Retrieves the text content of a Wikipedia page. It does not support tables and other complex formatting.
@@ -1,490 +0,0 @@
1
- # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
- #
3
- # SPDX-License-Identifier: Apache-2.0
4
- import hashlib
5
- import json
6
- import os
7
- from typing import Callable, Dict, List, Literal, Optional, Union
8
-
9
- import autogen
10
- from autogen import UserProxyAgent
11
- from autogen.agentchat.conversable_agent import ConversableAgent
12
-
13
- from .agent_builder import AgentBuilder
14
- from .tool_retriever import ToolBuilder, get_full_tool_description
15
-
16
-
17
- class CaptainAgent(ConversableAgent):
18
- """
19
- (In preview) Captain agent, designed to solve a task with an agent or a group of agents.
20
- """
21
-
22
- DEFAULT_NESTED_CONFIG = {
23
- "autobuild_init_config": {
24
- "config_file_or_env": "OAI_CONFIG_LIST",
25
- "builder_model": "gpt-4o",
26
- "agent_model": "gpt-4o",
27
- },
28
- "autobuild_build_config": {
29
- "default_llm_config": {"temperature": 1, "top_p": 0.95, "max_tokens": 2048},
30
- "code_execution_config": {
31
- "timeout": 300,
32
- "work_dir": "groupchat",
33
- "last_n_messages": 1,
34
- "use_docker": False,
35
- },
36
- "coding": True,
37
- },
38
- "group_chat_config": {"max_round": 10},
39
- "group_chat_llm_config": None,
40
- "max_turns": 5,
41
- }
42
-
43
- AUTOBUILD_TOOL = {
44
- "type": "function",
45
- "function": {
46
- "name": "seek_experts_help",
47
- "description": """Build a group of experts and let them chat with each other in a group chat.""",
48
- "parameters": {
49
- "type": "object",
50
- "properties": {
51
- "group_name": {"type": "string", "description": "[REQUIRED] Name of the group."},
52
- "building_task": {
53
- "type": "string",
54
- "description": """Instructions that help a build manager to build a group of experts.""",
55
- },
56
- "execution_task": {
57
- "type": "string",
58
- "description": """[REQUIRED] The task that needs the experts to solve by conversation.""",
59
- },
60
- },
61
- },
62
- },
63
- }
64
-
65
- AUTOBUILD_SYSTEM_MESSAGE = """# Your role
66
- You are a perfect manager of a group of advanced experts.
67
-
68
- # How to solve the task
69
- When a task is assigned to you:
70
- 1. Analysis of its constraints and conditions for completion.
71
- 2. Respond with a specific plan of how to solve the task.
72
-
73
- After that, you can solve the task in two ways:
74
- - Delegate the resolution of tasks to other experts created by seeking a group of experts for help and derive conclusive insights from their conversation summarization.
75
- - Analysis and solve the task with your coding and language skills.
76
-
77
- # How to seek experts help
78
- The tool "seek_experts_help" can build a group of experts according to the building_task and let them chat with each other in a group chat to solve the execution_task you provided.
79
- - This tool will summarize the essence of the experts' conversation and the derived conclusions.
80
- - You should not modify any task information from meta_user_proxy, including code blocks, but you can provide extra information.
81
- - Within a single response, you are limited to initiating one group of experts.
82
-
83
- ## building_task
84
- This task helps a build manager to build a group of experts for your task.
85
- You should suggest less then three roles (including a checker for verification) with the following format.
86
-
87
- ### Format
88
- - [Detailed description for role 1]
89
- - [Detailed description for role 2]
90
- - [Detailed description for checker]
91
-
92
- ## execution_task
93
- This is the task that needs the experts to solve by conversation.
94
- You should Provide the following information in markdown format.
95
-
96
- ### Format
97
- ## Task description
98
- ...
99
- ## Plan for solving the task
100
- ...
101
- ## Output format
102
- ...
103
- ## Constraints and conditions for completion
104
- ...
105
- ## [Optional] results (including code blocks) and reason from last response
106
- ...
107
-
108
- # After seek_experts_help
109
- You will receive a comprehensive conclusion from the conversation, including the task information, results, reason for the results, conversation contradiction or issues, and additional information.
110
- You **must** conduct a thorough verification for the result and reason's logical compliance by leveraging the step-by-step backward reasoning with the same group of experts (with the same group name) when:
111
- - The conversation has contradictions or issues (need double-check marked as yes), or
112
- - The result is different from the previous results.
113
-
114
- Note that the previous experts will forget everything after you obtain the response from them. You should provide the results (including code blocks) you collected from the previous experts' response and put it in the new execution_task.
115
-
116
- # Some useful instructions
117
- - You only have one tool called "seek_experts_help".
118
- - Provide a answer yourself after "seek_experts_help".
119
- - You should suggest python code in a python coding block (```python...```). If you need to get the value of a variable, you must use the print statement.
120
- - When using code, you must indicate the script type in the code block.
121
- - Do not suggest incomplete code which requires users to modify.
122
- - Be clear about which step uses code, which step uses your language skill, and which step to build a group chat.
123
- - If the code's result indicates there is an error, fix the error and output the whole code again.
124
- - If the error can't be fixed or if the task is not solved even after the code is executed successfully, analyze the problem, revisit your assumption, collect additional info you need, and think of a different approach to try.
125
- - Include verifiable evidence in your response if possible.
126
- - After completing all tasks and verifications, you should conclude the operation and reply "TERMINATE"
127
- """
128
-
129
- DEFAULT_DESCRIPTION = "A helpful AI assistant that can build a group of agents at a proper time to solve a task."
130
-
131
- # This is used to prompt the LLM to summarize the conversation history between CaptainAgent's tool execution history
132
- DEFAULT_SUMMARY_PROMPT = "Read the following conversation history between an expert and a group of agent experts, summarize the conversation history. Your summarization should include the initial task, the experts' plan and the attempt, finally the results of the conversation. If the experts arrived at a conclusion, state it as it is without any modification."
133
-
134
- def __init__(
135
- self,
136
- name: str,
137
- system_message: Optional[str] = None,
138
- llm_config: Optional[Union[Dict, Literal[False]]] = None,
139
- is_termination_msg: Optional[Callable[[Dict], bool]] = None,
140
- max_consecutive_auto_reply: Optional[int] = None,
141
- human_input_mode: Optional[str] = "NEVER",
142
- code_execution_config: Optional[Union[Dict, Literal[False]]] = False,
143
- nested_config: Optional[Dict] = None,
144
- agent_lib: Optional[str] = None,
145
- tool_lib: Optional[str] = None,
146
- agent_config_save_path: Optional[str] = None,
147
- description: Optional[str] = DEFAULT_DESCRIPTION,
148
- **kwargs,
149
- ):
150
- """
151
- Args:
152
- name (str): agent name.
153
- system_message (str): system message for the ChatCompletion inference.
154
- Please override this attribute if you want to reprogram the agent.
155
- llm_config (dict): llm inference configuration.
156
- Please refer to [OpenAIWrapper.create](/docs/reference/oai/client#create) for available options.
157
- is_termination_msg (function): a function that takes a message in the form of a dictionary
158
- and returns a boolean value indicating if this received message is a termination message.
159
- The dict can contain the following keys: "content", "role", "name", "function_call".
160
- max_consecutive_auto_reply (int): the maximum number of consecutive auto replies.
161
- default to None (no limit provided, class attribute MAX_CONSECUTIVE_AUTO_REPLY will be used as the limit in this case).
162
- The limit only plays a role when human_input_mode is not "ALWAYS".
163
- agent_lib (str): the path or a JSON file of the agent library for retrieving the nested chat instantiated by CaptainAgent.
164
- tool_lib (str): the path to the tool library for retrieving the tools used in the nested chat instantiated by CaptainAgent.
165
- nested_config (dict): the configuration for the nested chat instantiated by CaptainAgent.
166
- A full list of keys and their functionalities can be found in [docs](https://ag2ai.github.io/ag2/docs/topics/captainagent/configurations).
167
- agent_config_save_path (str): the path to save the generated or retrieved agent configuration.
168
- **kwargs (dict): Please refer to other kwargs in
169
- [ConversableAgent](https://github.com/ag2ai/ag2/blob/main/autogen/agentchat/conversable_agent.py#L74).
170
- """
171
- super().__init__(
172
- name,
173
- is_termination_msg=is_termination_msg,
174
- max_consecutive_auto_reply=max_consecutive_auto_reply,
175
- human_input_mode=human_input_mode,
176
- code_execution_config=code_execution_config,
177
- llm_config=llm_config,
178
- description=description,
179
- **kwargs,
180
- )
181
-
182
- if system_message is None:
183
- system_message = self.AUTOBUILD_SYSTEM_MESSAGE
184
- nested_config = self._update_config(self.DEFAULT_NESTED_CONFIG, nested_config)
185
- if nested_config["group_chat_llm_config"] is None:
186
- nested_config["group_chat_llm_config"] = llm_config.copy()
187
- if agent_lib:
188
- nested_config["autobuild_build_config"]["library_path_or_json"] = agent_lib
189
- if tool_lib:
190
- if "autobuild_tool_config" not in nested_config:
191
- nested_config["autobuild_tool_config"] = {}
192
- nested_config["autobuild_tool_config"]["tool_root"] = tool_lib
193
-
194
- self.assistant = ConversableAgent(name="CaptainAgent", system_message=system_message, llm_config=llm_config)
195
- self.assistant.update_tool_signature(self.AUTOBUILD_TOOL, is_remove=False)
196
-
197
- self.executor = CaptainUserProxyAgent(
198
- name="Expert_summoner",
199
- nested_config=nested_config,
200
- agent_config_save_path=agent_config_save_path,
201
- is_termination_msg=lambda x: x.get("content", "") and "terminate" in x.get("content", "").lower(),
202
- code_execution_config=code_execution_config,
203
- human_input_mode="NEVER",
204
- )
205
-
206
- self.register_nested_chats(
207
- [
208
- {
209
- "sender": self.executor,
210
- "recipient": self.assistant,
211
- "max_turns": nested_config["max_turns"],
212
- "summary_method": "reflection_with_llm",
213
- "summary_args": {
214
- "summary_prompt": self.DEFAULT_SUMMARY_PROMPT,
215
- },
216
- }
217
- ],
218
- trigger=UserProxyAgent,
219
- position=0,
220
- )
221
-
222
- @staticmethod
223
- def _update_config(default_dict: Dict, update_dict: Optional[Dict]) -> Dict:
224
- """
225
- Recursively updates the default_dict with values from update_dict.
226
- """
227
- if update_dict is None:
228
- return default_dict
229
-
230
- for key, value in update_dict.items():
231
- default_value = default_dict.get(key)
232
- if isinstance(default_value, dict) and isinstance(value, dict):
233
- # Recursively update nested dictionaries
234
- default_dict[key] = CaptainAgent._update_config(default_value, value)
235
- else:
236
- # Update the value or add new key
237
- default_dict[key] = value
238
-
239
- return default_dict
240
-
241
-
242
- class CaptainUserProxyAgent(ConversableAgent):
243
- """(In preview) A proxy agent for the captain agent, that can execute code and provide feedback to the other agents."""
244
-
245
- CONVERSATION_REVIEW_PROMPT = """# Your task
246
- Briefly summarize the conversation history derived from an experts' group chat by following the answer format.
247
- If you found non-trivial errors or issues in the conversation, point it out with a detailed reason, if you think it is worth further verification, mark the "Need double-check" as "Yes"
248
- If you find the conversation ends with TERMINATE and the task is solved, this is normal situation, you can mark the "Need double-check" as "No".
249
-
250
- # Conversation history:
251
- {chat_history}
252
-
253
- # Answer format
254
- ## Task
255
- ...
256
-
257
- ## Results
258
- ...
259
-
260
- ## Reason for the results
261
- ...
262
-
263
- ## Errors or issues in the conversation
264
- ...
265
-
266
- ### Need to double-check?
267
- [Yes or No]
268
-
269
- ## Additional information (file path, code blocks, url, etc.)
270
- ...
271
- """
272
-
273
- AUTOBUILD_TASK_DESC = """You are given: (1) a task and advises from your manager with a specific plan and (2) a general task.
274
- Collect information from the general task, follow the suggestions from manager to solve the task.
275
-
276
- # General Task
277
- {general_task}
278
-
279
- # Task and suggestions from manager
280
- {manager_task} """
281
-
282
- DEFAULT_AUTO_REPLY = "I'm a proxy and I can only execute your tool or end the conversation. If you think the problem is solved, please reply me only with 'TERMINATE'."
283
-
284
- DEFAULT_USER_PROXY_AGENT_DESCRIPTIONS = {
285
- "ALWAYS": "An attentive HUMAN user who can answer questions about the task, and can perform tasks such as running Python code or inputting command line commands at a Linux terminal and reporting back the execution results.",
286
- "TERMINATE": "A user that can run Python code or input command line commands at a Linux terminal and report back the execution results.",
287
- "NEVER": "A computer terminal that can running Python scripts (provided to it quoted in ```python code blocks), or sh shell scripts (provided to it quoted in ```sh code blocks), or the conversation history and result of a group of agents",
288
- }
289
-
290
- def __init__(
291
- self,
292
- name: str,
293
- nested_config: Dict,
294
- agent_config_save_path: str = None,
295
- is_termination_msg: Optional[Callable[[Dict], bool]] = None,
296
- max_consecutive_auto_reply: Optional[int] = None,
297
- human_input_mode: Optional[str] = "NEVER",
298
- code_execution_config: Optional[Union[Dict, Literal[False]]] = None,
299
- default_auto_reply: Optional[Union[str, Dict, None]] = DEFAULT_AUTO_REPLY,
300
- llm_config: Optional[Union[Dict, Literal[False]]] = False,
301
- system_message: Optional[Union[str, List]] = "",
302
- description: Optional[str] = None,
303
- ):
304
- """
305
- Args:
306
- name (str): name of the agent.
307
- nested_config (dict): the configuration for the nested chat instantiated by CaptainAgent.
308
- is_termination_msg (function): a function that takes a message in the form of a dictionary
309
- and returns a boolean value indicating if this received message is a termination message.
310
- The dict can contain the following keys: "content", "role", "name", "function_call".
311
- max_consecutive_auto_reply (int): the maximum number of consecutive auto replies.
312
- default to None (no limit provided, class attribute MAX_CONSECUTIVE_AUTO_REPLY will be used as the limit in this case).
313
- The limit only plays a role when human_input_mode is not "ALWAYS".
314
- human_input_mode (str): whether to ask for human inputs every time a message is received.
315
- Possible values are "ALWAYS", "TERMINATE", "NEVER".
316
- (1) When "ALWAYS", the agent prompts for human input every time a message is received.
317
- Under this mode, the conversation stops when the human input is "exit",
318
- or when is_termination_msg is True and there is no human input.
319
- (2) When "TERMINATE", the agent only prompts for human input only when a termination message is received or
320
- the number of auto reply reaches the max_consecutive_auto_reply.
321
- (3) When "NEVER", the agent will never prompt for human input. Under this mode, the conversation stops
322
- when the number of auto reply reaches the max_consecutive_auto_reply or when is_termination_msg is True.
323
- code_execution_config (dict or False): config for the code execution.
324
- To disable code execution, set to False. Otherwise, set to a dictionary with the following keys:
325
- - work_dir (Optional, str): The working directory for the code execution.
326
- If None, a default working directory will be used.
327
- The default working directory is the "extensions" directory under
328
- "path_to_autogen".
329
- - use_docker (Optional, list, str or bool): The docker image to use for code execution.
330
- Default is True, which means the code will be executed in a docker container. A default list of images will be used.
331
- If a list or a str of image name(s) is provided, the code will be executed in a docker container
332
- with the first image successfully pulled.
333
- If False, the code will be executed in the current environment.
334
- We strongly recommend using docker for code execution.
335
- - timeout (Optional, int): The maximum execution time in seconds.
336
- - last_n_messages (Experimental, Optional, int): The number of messages to look back for code execution. Default to 1.
337
- default_auto_reply (str or dict or None): the default auto reply message when no code execution or llm based reply is generated.
338
- llm_config (dict or False): llm inference configuration.
339
- Please refer to [OpenAIWrapper.create](/docs/reference/oai/client#create)
340
- for available options.
341
- Default to false, which disables llm-based auto reply.
342
- system_message (str or List): system message for ChatCompletion inference.
343
- Only used when llm_config is not False. Use it to reprogram the agent.
344
- description (str): a short description of the agent. This description is used by other agents
345
- (e.g. the GroupChatManager) to decide when to call upon this agent. (Default: system_message)
346
- """
347
- description = (
348
- description if description is not None else self.DEFAULT_USER_PROXY_AGENT_DESCRIPTIONS[human_input_mode]
349
- )
350
- super().__init__(
351
- name=name,
352
- system_message=system_message,
353
- is_termination_msg=is_termination_msg,
354
- max_consecutive_auto_reply=max_consecutive_auto_reply,
355
- human_input_mode=human_input_mode,
356
- code_execution_config=code_execution_config,
357
- llm_config=llm_config,
358
- default_auto_reply=default_auto_reply,
359
- description=description,
360
- )
361
- self.register_function(
362
- function_map={
363
- "seek_experts_help": lambda **args: self._run_autobuild(**args),
364
- }
365
- )
366
- self._agent_config_save_path = agent_config_save_path
367
- self._nested_config = nested_config.copy()
368
- self._code_execution_config = code_execution_config
369
- self.build_history = {}
370
- self.tool_history = {}
371
- self.build_times = 0
372
-
373
- def _run_autobuild(self, group_name: str, execution_task: str, building_task: str = "") -> str:
374
- """
375
- Build a group of agents by AutoBuild to solve the task.
376
- This function requires the nested_config to contain the autobuild_init_config, autobuild_llm_config, group_chat_llm_config.
377
- """
378
- print("==> Running AutoBuild...", flush=True)
379
- print("\n==> Building task: ", building_task, flush=True)
380
- print("\n==> Execution task: ", execution_task, flush=True)
381
-
382
- builder = AgentBuilder(**self._nested_config["autobuild_init_config"])
383
- # if the group is already built, load from history
384
- if group_name in self.build_history.keys():
385
- agent_list, agent_configs = builder.load(config_json=json.dumps(self.build_history[group_name]))
386
- if self._nested_config.get("autobuild_tool_config", None) and agent_configs["coding"] is True:
387
- # tool library is enabled, reload tools and bind them to the agents
388
- tool_root_dir = self.tool_root_dir
389
- tool_builder = ToolBuilder(
390
- corpus_path=os.path.join(tool_root_dir, "tool_description.tsv"),
391
- retriever=self._nested_config["autobuild_tool_config"].get("retriever", "all-mpnet-base-v2"),
392
- )
393
- for idx, agent in enumerate(agent_list):
394
- if idx == len(self.tool_history[group_name]):
395
- break
396
- tool_builder.bind(agent, "\n\n".join(self.tool_history[group_name][idx]))
397
- agent_list[-1] = tool_builder.bind_user_proxy(agent_list[-1], tool_root_dir)
398
- else:
399
- if self._nested_config["autobuild_build_config"].get("library_path_or_json", None):
400
- # Build from retrieval
401
- agent_list, agent_configs = builder.build_from_library(
402
- building_task, **self._nested_config["autobuild_build_config"]
403
- )
404
- self.build_history[group_name] = agent_configs.copy()
405
-
406
- if self._nested_config.get("autobuild_tool_config", None) and agent_configs["coding"] is True:
407
- print("==> Retrieving tools...", flush=True)
408
- skills = building_task.split("\n")
409
- if len(skills) == 0:
410
- skills = [building_task]
411
-
412
- if self._nested_config["autobuild_tool_config"].get("tool_root", "default") == "default":
413
- cur_path = os.path.dirname(os.path.abspath(__file__))
414
- tool_root_dir = os.path.join(cur_path, "captainagent", "tools")
415
- else:
416
- tool_root_dir = self._nested_config["autobuild_tool_config"]["tool_root"]
417
- self.tool_root_dir = tool_root_dir
418
-
419
- # Retrieve and build tools based on the smilarities between the skills and the tool description
420
- tool_builder = ToolBuilder(
421
- corpus_path=os.path.join(tool_root_dir, "tool_description.tsv"),
422
- retriever=self._nested_config["autobuild_tool_config"].get("retriever", "all-mpnet-base-v2"),
423
- )
424
- for idx, skill in enumerate(skills):
425
- tools = tool_builder.retrieve(skill)
426
- docstrings = []
427
- for tool in tools:
428
- category, tool_name = tool.split(" ")[0], tool.split(" ")[1]
429
- tool_path = os.path.join(tool_root_dir, category, f"{tool_name}.py")
430
- docstring = get_full_tool_description(tool_path)
431
- docstrings.append(docstring)
432
- tool_builder.bind(agent_list[idx], "\n\n".join(docstrings))
433
- # log tools
434
- tool_history = self.tool_history.get(group_name, [])
435
- tool_history.append(docstrings)
436
- self.tool_history[group_name] = tool_history
437
-
438
- agent_list[-1] = tool_builder.bind_user_proxy(agent_list[-1], tool_root_dir)
439
-
440
- else:
441
- # Build agents from scratch
442
- agent_list, agent_configs = builder.build(
443
- building_task, **self._nested_config["autobuild_build_config"]
444
- )
445
- self.build_history[group_name] = agent_configs.copy()
446
-
447
- if self._agent_config_save_path is not None:
448
- building_task_md5 = hashlib.md5(building_task.encode("utf-8")).hexdigest()
449
- with open(f"{self._agent_config_save_path}/build_history_{building_task_md5}.json", "w") as f:
450
- json.dump(self.build_history, f)
451
-
452
- self.build_times += 1
453
- # start nested chat
454
- nested_group_chat = autogen.GroupChat(
455
- agents=agent_list,
456
- messages=[],
457
- allow_repeat_speaker=agent_list[:-1] if agent_configs["coding"] is True else agent_list,
458
- **self._nested_config["group_chat_config"],
459
- )
460
- manager = autogen.GroupChatManager(
461
- groupchat=nested_group_chat,
462
- llm_config=self._nested_config["group_chat_llm_config"],
463
- )
464
- key = list(self.chat_messages.keys())[0]
465
- general_task = self.chat_messages[key][0]["content"]
466
- agent_list[0].initiate_chat(
467
- manager, message=self.AUTOBUILD_TASK_DESC.format(general_task=general_task, manager_task=execution_task)
468
- )
469
- chat_history = []
470
- key = list(agent_list[0].chat_messages.keys())[0]
471
- chat_messages = agent_list[0].chat_messages[key]
472
- for item in chat_messages:
473
- chat_history.append(item)
474
-
475
- # Review the group chat history
476
- summary_model = builder.builder_model
477
- summarized_history = (
478
- summary_model.create(
479
- messages=[
480
- {
481
- "role": "user",
482
- "content": self.CONVERSATION_REVIEW_PROMPT.format(chat_history=chat_history),
483
- }
484
- ]
485
- )
486
- .choices[0]
487
- .message.content
488
- )
489
-
490
- return f"# Response from seek_agent_help: \n{summarized_history}"