ag2 0.10.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (423) hide show
  1. ag2-0.10.2.dist-info/METADATA +819 -0
  2. ag2-0.10.2.dist-info/RECORD +423 -0
  3. ag2-0.10.2.dist-info/WHEEL +4 -0
  4. ag2-0.10.2.dist-info/licenses/LICENSE +201 -0
  5. ag2-0.10.2.dist-info/licenses/NOTICE.md +19 -0
  6. autogen/__init__.py +88 -0
  7. autogen/_website/__init__.py +3 -0
  8. autogen/_website/generate_api_references.py +426 -0
  9. autogen/_website/generate_mkdocs.py +1216 -0
  10. autogen/_website/notebook_processor.py +475 -0
  11. autogen/_website/process_notebooks.py +656 -0
  12. autogen/_website/utils.py +413 -0
  13. autogen/a2a/__init__.py +36 -0
  14. autogen/a2a/agent_executor.py +86 -0
  15. autogen/a2a/client.py +357 -0
  16. autogen/a2a/errors.py +18 -0
  17. autogen/a2a/httpx_client_factory.py +79 -0
  18. autogen/a2a/server.py +221 -0
  19. autogen/a2a/utils.py +207 -0
  20. autogen/agentchat/__init__.py +47 -0
  21. autogen/agentchat/agent.py +180 -0
  22. autogen/agentchat/assistant_agent.py +86 -0
  23. autogen/agentchat/chat.py +325 -0
  24. autogen/agentchat/contrib/__init__.py +5 -0
  25. autogen/agentchat/contrib/agent_eval/README.md +7 -0
  26. autogen/agentchat/contrib/agent_eval/agent_eval.py +108 -0
  27. autogen/agentchat/contrib/agent_eval/criterion.py +43 -0
  28. autogen/agentchat/contrib/agent_eval/critic_agent.py +44 -0
  29. autogen/agentchat/contrib/agent_eval/quantifier_agent.py +39 -0
  30. autogen/agentchat/contrib/agent_eval/subcritic_agent.py +45 -0
  31. autogen/agentchat/contrib/agent_eval/task.py +42 -0
  32. autogen/agentchat/contrib/agent_optimizer.py +432 -0
  33. autogen/agentchat/contrib/capabilities/__init__.py +5 -0
  34. autogen/agentchat/contrib/capabilities/agent_capability.py +20 -0
  35. autogen/agentchat/contrib/capabilities/generate_images.py +301 -0
  36. autogen/agentchat/contrib/capabilities/teachability.py +393 -0
  37. autogen/agentchat/contrib/capabilities/text_compressors.py +66 -0
  38. autogen/agentchat/contrib/capabilities/tools_capability.py +22 -0
  39. autogen/agentchat/contrib/capabilities/transform_messages.py +93 -0
  40. autogen/agentchat/contrib/capabilities/transforms.py +578 -0
  41. autogen/agentchat/contrib/capabilities/transforms_util.py +122 -0
  42. autogen/agentchat/contrib/capabilities/vision_capability.py +215 -0
  43. autogen/agentchat/contrib/captainagent/__init__.py +9 -0
  44. autogen/agentchat/contrib/captainagent/agent_builder.py +790 -0
  45. autogen/agentchat/contrib/captainagent/captainagent.py +514 -0
  46. autogen/agentchat/contrib/captainagent/tool_retriever.py +334 -0
  47. autogen/agentchat/contrib/captainagent/tools/README.md +44 -0
  48. autogen/agentchat/contrib/captainagent/tools/__init__.py +5 -0
  49. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_correlation.py +40 -0
  50. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_skewness_and_kurtosis.py +28 -0
  51. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_iqr.py +28 -0
  52. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_zscore.py +28 -0
  53. autogen/agentchat/contrib/captainagent/tools/data_analysis/explore_csv.py +21 -0
  54. autogen/agentchat/contrib/captainagent/tools/data_analysis/shapiro_wilk_test.py +30 -0
  55. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_download.py +27 -0
  56. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_search.py +53 -0
  57. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_image.py +53 -0
  58. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_text.py +38 -0
  59. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_wikipedia_text.py +21 -0
  60. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_youtube_caption.py +34 -0
  61. autogen/agentchat/contrib/captainagent/tools/information_retrieval/image_qa.py +60 -0
  62. autogen/agentchat/contrib/captainagent/tools/information_retrieval/optical_character_recognition.py +61 -0
  63. autogen/agentchat/contrib/captainagent/tools/information_retrieval/perform_web_search.py +47 -0
  64. autogen/agentchat/contrib/captainagent/tools/information_retrieval/scrape_wikipedia_tables.py +33 -0
  65. autogen/agentchat/contrib/captainagent/tools/information_retrieval/transcribe_audio_file.py +21 -0
  66. autogen/agentchat/contrib/captainagent/tools/information_retrieval/youtube_download.py +35 -0
  67. autogen/agentchat/contrib/captainagent/tools/math/calculate_circle_area_from_diameter.py +21 -0
  68. autogen/agentchat/contrib/captainagent/tools/math/calculate_day_of_the_week.py +18 -0
  69. autogen/agentchat/contrib/captainagent/tools/math/calculate_fraction_sum.py +28 -0
  70. autogen/agentchat/contrib/captainagent/tools/math/calculate_matrix_power.py +31 -0
  71. autogen/agentchat/contrib/captainagent/tools/math/calculate_reflected_point.py +16 -0
  72. autogen/agentchat/contrib/captainagent/tools/math/complex_numbers_product.py +25 -0
  73. autogen/agentchat/contrib/captainagent/tools/math/compute_currency_conversion.py +23 -0
  74. autogen/agentchat/contrib/captainagent/tools/math/count_distinct_permutations.py +27 -0
  75. autogen/agentchat/contrib/captainagent/tools/math/evaluate_expression.py +28 -0
  76. autogen/agentchat/contrib/captainagent/tools/math/find_continuity_point.py +34 -0
  77. autogen/agentchat/contrib/captainagent/tools/math/fraction_to_mixed_numbers.py +39 -0
  78. autogen/agentchat/contrib/captainagent/tools/math/modular_inverse_sum.py +23 -0
  79. autogen/agentchat/contrib/captainagent/tools/math/simplify_mixed_numbers.py +36 -0
  80. autogen/agentchat/contrib/captainagent/tools/math/sum_of_digit_factorials.py +15 -0
  81. autogen/agentchat/contrib/captainagent/tools/math/sum_of_primes_below.py +15 -0
  82. autogen/agentchat/contrib/captainagent/tools/requirements.txt +10 -0
  83. autogen/agentchat/contrib/captainagent/tools/tool_description.tsv +34 -0
  84. autogen/agentchat/contrib/gpt_assistant_agent.py +526 -0
  85. autogen/agentchat/contrib/graph_rag/__init__.py +9 -0
  86. autogen/agentchat/contrib/graph_rag/document.py +29 -0
  87. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +167 -0
  88. autogen/agentchat/contrib/graph_rag/falkor_graph_rag_capability.py +103 -0
  89. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +53 -0
  90. autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +63 -0
  91. autogen/agentchat/contrib/graph_rag/neo4j_graph_query_engine.py +263 -0
  92. autogen/agentchat/contrib/graph_rag/neo4j_graph_rag_capability.py +83 -0
  93. autogen/agentchat/contrib/graph_rag/neo4j_native_graph_query_engine.py +210 -0
  94. autogen/agentchat/contrib/graph_rag/neo4j_native_graph_rag_capability.py +93 -0
  95. autogen/agentchat/contrib/img_utils.py +397 -0
  96. autogen/agentchat/contrib/llamaindex_conversable_agent.py +117 -0
  97. autogen/agentchat/contrib/llava_agent.py +189 -0
  98. autogen/agentchat/contrib/math_user_proxy_agent.py +464 -0
  99. autogen/agentchat/contrib/multimodal_conversable_agent.py +125 -0
  100. autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +325 -0
  101. autogen/agentchat/contrib/rag/__init__.py +10 -0
  102. autogen/agentchat/contrib/rag/chromadb_query_engine.py +268 -0
  103. autogen/agentchat/contrib/rag/llamaindex_query_engine.py +195 -0
  104. autogen/agentchat/contrib/rag/mongodb_query_engine.py +319 -0
  105. autogen/agentchat/contrib/rag/query_engine.py +76 -0
  106. autogen/agentchat/contrib/retrieve_assistant_agent.py +59 -0
  107. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +704 -0
  108. autogen/agentchat/contrib/society_of_mind_agent.py +200 -0
  109. autogen/agentchat/contrib/swarm_agent.py +1404 -0
  110. autogen/agentchat/contrib/text_analyzer_agent.py +79 -0
  111. autogen/agentchat/contrib/vectordb/__init__.py +5 -0
  112. autogen/agentchat/contrib/vectordb/base.py +224 -0
  113. autogen/agentchat/contrib/vectordb/chromadb.py +316 -0
  114. autogen/agentchat/contrib/vectordb/couchbase.py +405 -0
  115. autogen/agentchat/contrib/vectordb/mongodb.py +551 -0
  116. autogen/agentchat/contrib/vectordb/pgvectordb.py +927 -0
  117. autogen/agentchat/contrib/vectordb/qdrant.py +320 -0
  118. autogen/agentchat/contrib/vectordb/utils.py +126 -0
  119. autogen/agentchat/contrib/web_surfer.py +304 -0
  120. autogen/agentchat/conversable_agent.py +4307 -0
  121. autogen/agentchat/group/__init__.py +67 -0
  122. autogen/agentchat/group/available_condition.py +91 -0
  123. autogen/agentchat/group/context_condition.py +77 -0
  124. autogen/agentchat/group/context_expression.py +238 -0
  125. autogen/agentchat/group/context_str.py +39 -0
  126. autogen/agentchat/group/context_variables.py +182 -0
  127. autogen/agentchat/group/events/transition_events.py +111 -0
  128. autogen/agentchat/group/group_tool_executor.py +324 -0
  129. autogen/agentchat/group/group_utils.py +659 -0
  130. autogen/agentchat/group/guardrails.py +179 -0
  131. autogen/agentchat/group/handoffs.py +303 -0
  132. autogen/agentchat/group/llm_condition.py +93 -0
  133. autogen/agentchat/group/multi_agent_chat.py +291 -0
  134. autogen/agentchat/group/on_condition.py +55 -0
  135. autogen/agentchat/group/on_context_condition.py +51 -0
  136. autogen/agentchat/group/patterns/__init__.py +18 -0
  137. autogen/agentchat/group/patterns/auto.py +160 -0
  138. autogen/agentchat/group/patterns/manual.py +177 -0
  139. autogen/agentchat/group/patterns/pattern.py +295 -0
  140. autogen/agentchat/group/patterns/random.py +106 -0
  141. autogen/agentchat/group/patterns/round_robin.py +117 -0
  142. autogen/agentchat/group/reply_result.py +24 -0
  143. autogen/agentchat/group/safeguards/__init__.py +21 -0
  144. autogen/agentchat/group/safeguards/api.py +241 -0
  145. autogen/agentchat/group/safeguards/enforcer.py +1158 -0
  146. autogen/agentchat/group/safeguards/events.py +140 -0
  147. autogen/agentchat/group/safeguards/validator.py +435 -0
  148. autogen/agentchat/group/speaker_selection_result.py +41 -0
  149. autogen/agentchat/group/targets/__init__.py +4 -0
  150. autogen/agentchat/group/targets/function_target.py +245 -0
  151. autogen/agentchat/group/targets/group_chat_target.py +133 -0
  152. autogen/agentchat/group/targets/group_manager_target.py +151 -0
  153. autogen/agentchat/group/targets/transition_target.py +424 -0
  154. autogen/agentchat/group/targets/transition_utils.py +6 -0
  155. autogen/agentchat/groupchat.py +1832 -0
  156. autogen/agentchat/realtime/__init__.py +3 -0
  157. autogen/agentchat/realtime/experimental/__init__.py +20 -0
  158. autogen/agentchat/realtime/experimental/audio_adapters/__init__.py +8 -0
  159. autogen/agentchat/realtime/experimental/audio_adapters/twilio_audio_adapter.py +148 -0
  160. autogen/agentchat/realtime/experimental/audio_adapters/websocket_audio_adapter.py +139 -0
  161. autogen/agentchat/realtime/experimental/audio_observer.py +42 -0
  162. autogen/agentchat/realtime/experimental/clients/__init__.py +15 -0
  163. autogen/agentchat/realtime/experimental/clients/gemini/__init__.py +7 -0
  164. autogen/agentchat/realtime/experimental/clients/gemini/client.py +274 -0
  165. autogen/agentchat/realtime/experimental/clients/oai/__init__.py +8 -0
  166. autogen/agentchat/realtime/experimental/clients/oai/base_client.py +220 -0
  167. autogen/agentchat/realtime/experimental/clients/oai/rtc_client.py +243 -0
  168. autogen/agentchat/realtime/experimental/clients/oai/utils.py +48 -0
  169. autogen/agentchat/realtime/experimental/clients/realtime_client.py +191 -0
  170. autogen/agentchat/realtime/experimental/function_observer.py +84 -0
  171. autogen/agentchat/realtime/experimental/realtime_agent.py +158 -0
  172. autogen/agentchat/realtime/experimental/realtime_events.py +42 -0
  173. autogen/agentchat/realtime/experimental/realtime_observer.py +100 -0
  174. autogen/agentchat/realtime/experimental/realtime_swarm.py +533 -0
  175. autogen/agentchat/realtime/experimental/websockets.py +21 -0
  176. autogen/agentchat/realtime_agent/__init__.py +21 -0
  177. autogen/agentchat/user_proxy_agent.py +114 -0
  178. autogen/agentchat/utils.py +206 -0
  179. autogen/agents/__init__.py +3 -0
  180. autogen/agents/contrib/__init__.py +10 -0
  181. autogen/agents/contrib/time/__init__.py +8 -0
  182. autogen/agents/contrib/time/time_reply_agent.py +74 -0
  183. autogen/agents/contrib/time/time_tool_agent.py +52 -0
  184. autogen/agents/experimental/__init__.py +27 -0
  185. autogen/agents/experimental/deep_research/__init__.py +7 -0
  186. autogen/agents/experimental/deep_research/deep_research.py +52 -0
  187. autogen/agents/experimental/discord/__init__.py +7 -0
  188. autogen/agents/experimental/discord/discord.py +66 -0
  189. autogen/agents/experimental/document_agent/__init__.py +19 -0
  190. autogen/agents/experimental/document_agent/chroma_query_engine.py +301 -0
  191. autogen/agents/experimental/document_agent/docling_doc_ingest_agent.py +113 -0
  192. autogen/agents/experimental/document_agent/document_agent.py +643 -0
  193. autogen/agents/experimental/document_agent/document_conditions.py +50 -0
  194. autogen/agents/experimental/document_agent/document_utils.py +376 -0
  195. autogen/agents/experimental/document_agent/inmemory_query_engine.py +214 -0
  196. autogen/agents/experimental/document_agent/parser_utils.py +134 -0
  197. autogen/agents/experimental/document_agent/url_utils.py +417 -0
  198. autogen/agents/experimental/reasoning/__init__.py +7 -0
  199. autogen/agents/experimental/reasoning/reasoning_agent.py +1178 -0
  200. autogen/agents/experimental/slack/__init__.py +7 -0
  201. autogen/agents/experimental/slack/slack.py +73 -0
  202. autogen/agents/experimental/telegram/__init__.py +7 -0
  203. autogen/agents/experimental/telegram/telegram.py +76 -0
  204. autogen/agents/experimental/websurfer/__init__.py +7 -0
  205. autogen/agents/experimental/websurfer/websurfer.py +70 -0
  206. autogen/agents/experimental/wikipedia/__init__.py +7 -0
  207. autogen/agents/experimental/wikipedia/wikipedia.py +88 -0
  208. autogen/browser_utils.py +309 -0
  209. autogen/cache/__init__.py +10 -0
  210. autogen/cache/abstract_cache_base.py +71 -0
  211. autogen/cache/cache.py +203 -0
  212. autogen/cache/cache_factory.py +88 -0
  213. autogen/cache/cosmos_db_cache.py +144 -0
  214. autogen/cache/disk_cache.py +97 -0
  215. autogen/cache/in_memory_cache.py +54 -0
  216. autogen/cache/redis_cache.py +119 -0
  217. autogen/code_utils.py +598 -0
  218. autogen/coding/__init__.py +30 -0
  219. autogen/coding/base.py +120 -0
  220. autogen/coding/docker_commandline_code_executor.py +283 -0
  221. autogen/coding/factory.py +56 -0
  222. autogen/coding/func_with_reqs.py +203 -0
  223. autogen/coding/jupyter/__init__.py +23 -0
  224. autogen/coding/jupyter/base.py +36 -0
  225. autogen/coding/jupyter/docker_jupyter_server.py +160 -0
  226. autogen/coding/jupyter/embedded_ipython_code_executor.py +182 -0
  227. autogen/coding/jupyter/import_utils.py +82 -0
  228. autogen/coding/jupyter/jupyter_client.py +224 -0
  229. autogen/coding/jupyter/jupyter_code_executor.py +154 -0
  230. autogen/coding/jupyter/local_jupyter_server.py +164 -0
  231. autogen/coding/local_commandline_code_executor.py +341 -0
  232. autogen/coding/markdown_code_extractor.py +44 -0
  233. autogen/coding/utils.py +55 -0
  234. autogen/coding/yepcode_code_executor.py +197 -0
  235. autogen/doc_utils.py +35 -0
  236. autogen/environments/__init__.py +10 -0
  237. autogen/environments/docker_python_environment.py +365 -0
  238. autogen/environments/python_environment.py +125 -0
  239. autogen/environments/system_python_environment.py +85 -0
  240. autogen/environments/venv_python_environment.py +220 -0
  241. autogen/environments/working_directory.py +74 -0
  242. autogen/events/__init__.py +7 -0
  243. autogen/events/agent_events.py +1016 -0
  244. autogen/events/base_event.py +100 -0
  245. autogen/events/client_events.py +168 -0
  246. autogen/events/helpers.py +44 -0
  247. autogen/events/print_event.py +45 -0
  248. autogen/exception_utils.py +73 -0
  249. autogen/extensions/__init__.py +5 -0
  250. autogen/fast_depends/__init__.py +16 -0
  251. autogen/fast_depends/_compat.py +75 -0
  252. autogen/fast_depends/core/__init__.py +14 -0
  253. autogen/fast_depends/core/build.py +206 -0
  254. autogen/fast_depends/core/model.py +527 -0
  255. autogen/fast_depends/dependencies/__init__.py +15 -0
  256. autogen/fast_depends/dependencies/model.py +30 -0
  257. autogen/fast_depends/dependencies/provider.py +40 -0
  258. autogen/fast_depends/library/__init__.py +10 -0
  259. autogen/fast_depends/library/model.py +46 -0
  260. autogen/fast_depends/py.typed +6 -0
  261. autogen/fast_depends/schema.py +66 -0
  262. autogen/fast_depends/use.py +272 -0
  263. autogen/fast_depends/utils.py +177 -0
  264. autogen/formatting_utils.py +83 -0
  265. autogen/function_utils.py +13 -0
  266. autogen/graph_utils.py +173 -0
  267. autogen/import_utils.py +539 -0
  268. autogen/interop/__init__.py +22 -0
  269. autogen/interop/crewai/__init__.py +7 -0
  270. autogen/interop/crewai/crewai.py +88 -0
  271. autogen/interop/interoperability.py +71 -0
  272. autogen/interop/interoperable.py +46 -0
  273. autogen/interop/langchain/__init__.py +8 -0
  274. autogen/interop/langchain/langchain_chat_model_factory.py +156 -0
  275. autogen/interop/langchain/langchain_tool.py +78 -0
  276. autogen/interop/litellm/__init__.py +7 -0
  277. autogen/interop/litellm/litellm_config_factory.py +178 -0
  278. autogen/interop/pydantic_ai/__init__.py +7 -0
  279. autogen/interop/pydantic_ai/pydantic_ai.py +172 -0
  280. autogen/interop/registry.py +70 -0
  281. autogen/io/__init__.py +15 -0
  282. autogen/io/base.py +151 -0
  283. autogen/io/console.py +56 -0
  284. autogen/io/processors/__init__.py +12 -0
  285. autogen/io/processors/base.py +21 -0
  286. autogen/io/processors/console_event_processor.py +61 -0
  287. autogen/io/run_response.py +294 -0
  288. autogen/io/thread_io_stream.py +63 -0
  289. autogen/io/websockets.py +214 -0
  290. autogen/json_utils.py +42 -0
  291. autogen/llm_clients/MIGRATION_TO_V2.md +782 -0
  292. autogen/llm_clients/__init__.py +77 -0
  293. autogen/llm_clients/client_v2.py +122 -0
  294. autogen/llm_clients/models/__init__.py +55 -0
  295. autogen/llm_clients/models/content_blocks.py +389 -0
  296. autogen/llm_clients/models/unified_message.py +145 -0
  297. autogen/llm_clients/models/unified_response.py +83 -0
  298. autogen/llm_clients/openai_completions_client.py +444 -0
  299. autogen/llm_config/__init__.py +11 -0
  300. autogen/llm_config/client.py +59 -0
  301. autogen/llm_config/config.py +461 -0
  302. autogen/llm_config/entry.py +169 -0
  303. autogen/llm_config/types.py +37 -0
  304. autogen/llm_config/utils.py +223 -0
  305. autogen/logger/__init__.py +11 -0
  306. autogen/logger/base_logger.py +129 -0
  307. autogen/logger/file_logger.py +262 -0
  308. autogen/logger/logger_factory.py +42 -0
  309. autogen/logger/logger_utils.py +57 -0
  310. autogen/logger/sqlite_logger.py +524 -0
  311. autogen/math_utils.py +338 -0
  312. autogen/mcp/__init__.py +7 -0
  313. autogen/mcp/__main__.py +78 -0
  314. autogen/mcp/helpers.py +45 -0
  315. autogen/mcp/mcp_client.py +349 -0
  316. autogen/mcp/mcp_proxy/__init__.py +19 -0
  317. autogen/mcp/mcp_proxy/fastapi_code_generator_helpers.py +62 -0
  318. autogen/mcp/mcp_proxy/mcp_proxy.py +577 -0
  319. autogen/mcp/mcp_proxy/operation_grouping.py +166 -0
  320. autogen/mcp/mcp_proxy/operation_renaming.py +110 -0
  321. autogen/mcp/mcp_proxy/patch_fastapi_code_generator.py +98 -0
  322. autogen/mcp/mcp_proxy/security.py +399 -0
  323. autogen/mcp/mcp_proxy/security_schema_visitor.py +37 -0
  324. autogen/messages/__init__.py +7 -0
  325. autogen/messages/agent_messages.py +946 -0
  326. autogen/messages/base_message.py +108 -0
  327. autogen/messages/client_messages.py +172 -0
  328. autogen/messages/print_message.py +48 -0
  329. autogen/oai/__init__.py +61 -0
  330. autogen/oai/anthropic.py +1516 -0
  331. autogen/oai/bedrock.py +800 -0
  332. autogen/oai/cerebras.py +302 -0
  333. autogen/oai/client.py +1658 -0
  334. autogen/oai/client_utils.py +196 -0
  335. autogen/oai/cohere.py +494 -0
  336. autogen/oai/gemini.py +1045 -0
  337. autogen/oai/gemini_types.py +156 -0
  338. autogen/oai/groq.py +319 -0
  339. autogen/oai/mistral.py +311 -0
  340. autogen/oai/oai_models/__init__.py +23 -0
  341. autogen/oai/oai_models/_models.py +16 -0
  342. autogen/oai/oai_models/chat_completion.py +86 -0
  343. autogen/oai/oai_models/chat_completion_audio.py +32 -0
  344. autogen/oai/oai_models/chat_completion_message.py +97 -0
  345. autogen/oai/oai_models/chat_completion_message_tool_call.py +60 -0
  346. autogen/oai/oai_models/chat_completion_token_logprob.py +62 -0
  347. autogen/oai/oai_models/completion_usage.py +59 -0
  348. autogen/oai/ollama.py +657 -0
  349. autogen/oai/openai_responses.py +451 -0
  350. autogen/oai/openai_utils.py +897 -0
  351. autogen/oai/together.py +387 -0
  352. autogen/remote/__init__.py +18 -0
  353. autogen/remote/agent.py +199 -0
  354. autogen/remote/agent_service.py +197 -0
  355. autogen/remote/errors.py +17 -0
  356. autogen/remote/httpx_client_factory.py +131 -0
  357. autogen/remote/protocol.py +37 -0
  358. autogen/remote/retry.py +102 -0
  359. autogen/remote/runtime.py +96 -0
  360. autogen/retrieve_utils.py +490 -0
  361. autogen/runtime_logging.py +161 -0
  362. autogen/testing/__init__.py +12 -0
  363. autogen/testing/messages.py +45 -0
  364. autogen/testing/test_agent.py +111 -0
  365. autogen/token_count_utils.py +280 -0
  366. autogen/tools/__init__.py +20 -0
  367. autogen/tools/contrib/__init__.py +9 -0
  368. autogen/tools/contrib/time/__init__.py +7 -0
  369. autogen/tools/contrib/time/time.py +40 -0
  370. autogen/tools/dependency_injection.py +249 -0
  371. autogen/tools/experimental/__init__.py +54 -0
  372. autogen/tools/experimental/browser_use/__init__.py +7 -0
  373. autogen/tools/experimental/browser_use/browser_use.py +154 -0
  374. autogen/tools/experimental/code_execution/__init__.py +7 -0
  375. autogen/tools/experimental/code_execution/python_code_execution.py +86 -0
  376. autogen/tools/experimental/crawl4ai/__init__.py +7 -0
  377. autogen/tools/experimental/crawl4ai/crawl4ai.py +150 -0
  378. autogen/tools/experimental/deep_research/__init__.py +7 -0
  379. autogen/tools/experimental/deep_research/deep_research.py +329 -0
  380. autogen/tools/experimental/duckduckgo/__init__.py +7 -0
  381. autogen/tools/experimental/duckduckgo/duckduckgo_search.py +103 -0
  382. autogen/tools/experimental/firecrawl/__init__.py +7 -0
  383. autogen/tools/experimental/firecrawl/firecrawl_tool.py +836 -0
  384. autogen/tools/experimental/google/__init__.py +14 -0
  385. autogen/tools/experimental/google/authentication/__init__.py +11 -0
  386. autogen/tools/experimental/google/authentication/credentials_hosted_provider.py +43 -0
  387. autogen/tools/experimental/google/authentication/credentials_local_provider.py +91 -0
  388. autogen/tools/experimental/google/authentication/credentials_provider.py +35 -0
  389. autogen/tools/experimental/google/drive/__init__.py +9 -0
  390. autogen/tools/experimental/google/drive/drive_functions.py +124 -0
  391. autogen/tools/experimental/google/drive/toolkit.py +88 -0
  392. autogen/tools/experimental/google/model.py +17 -0
  393. autogen/tools/experimental/google/toolkit_protocol.py +19 -0
  394. autogen/tools/experimental/google_search/__init__.py +8 -0
  395. autogen/tools/experimental/google_search/google_search.py +93 -0
  396. autogen/tools/experimental/google_search/youtube_search.py +181 -0
  397. autogen/tools/experimental/messageplatform/__init__.py +17 -0
  398. autogen/tools/experimental/messageplatform/discord/__init__.py +7 -0
  399. autogen/tools/experimental/messageplatform/discord/discord.py +284 -0
  400. autogen/tools/experimental/messageplatform/slack/__init__.py +7 -0
  401. autogen/tools/experimental/messageplatform/slack/slack.py +385 -0
  402. autogen/tools/experimental/messageplatform/telegram/__init__.py +7 -0
  403. autogen/tools/experimental/messageplatform/telegram/telegram.py +271 -0
  404. autogen/tools/experimental/perplexity/__init__.py +7 -0
  405. autogen/tools/experimental/perplexity/perplexity_search.py +249 -0
  406. autogen/tools/experimental/reliable/__init__.py +10 -0
  407. autogen/tools/experimental/reliable/reliable.py +1311 -0
  408. autogen/tools/experimental/searxng/__init__.py +7 -0
  409. autogen/tools/experimental/searxng/searxng_search.py +142 -0
  410. autogen/tools/experimental/tavily/__init__.py +7 -0
  411. autogen/tools/experimental/tavily/tavily_search.py +176 -0
  412. autogen/tools/experimental/web_search_preview/__init__.py +7 -0
  413. autogen/tools/experimental/web_search_preview/web_search_preview.py +120 -0
  414. autogen/tools/experimental/wikipedia/__init__.py +7 -0
  415. autogen/tools/experimental/wikipedia/wikipedia.py +284 -0
  416. autogen/tools/function_utils.py +412 -0
  417. autogen/tools/tool.py +188 -0
  418. autogen/tools/toolkit.py +86 -0
  419. autogen/types.py +29 -0
  420. autogen/version.py +7 -0
  421. templates/client_template/main.jinja2 +72 -0
  422. templates/config_template/config.jinja2 +7 -0
  423. templates/main.jinja2 +61 -0
@@ -0,0 +1,1832 @@
1
+ # Copyright (c) 2023 - 2025, AG2ai, Inc., AG2ai open-source projects maintainers and core contributors
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
+ import logging
10
+ import random
11
+ import re
12
+ import sys
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass, field
15
+ from typing import Any, Literal
16
+
17
+ from ..code_utils import content_str
18
+ from ..doc_utils import export_module
19
+ from ..events.agent_events import (
20
+ ClearAgentsHistoryEvent,
21
+ GroupChatResumeEvent,
22
+ GroupChatRunChatEvent,
23
+ SelectSpeakerEvent,
24
+ SelectSpeakerInvalidInputEvent,
25
+ SelectSpeakerTryCountExceededEvent,
26
+ SpeakerAttemptFailedMultipleAgentsEvent,
27
+ SpeakerAttemptFailedNoAgentsEvent,
28
+ SpeakerAttemptSuccessfulEvent,
29
+ TerminationEvent,
30
+ )
31
+ from ..exception_utils import AgentNameConflictError, NoEligibleSpeakerError, UndefinedNextAgentError
32
+ from ..graph_utils import check_graph_validity, invert_disallowed_to_allowed
33
+ from ..io.base import IOStream
34
+ from ..llm_config import LLMConfig, ModelClient
35
+ from ..runtime_logging import log_new_agent, logging_enabled
36
+ from .agent import Agent
37
+ from .contrib.capabilities import transform_messages
38
+ from .conversable_agent import ConversableAgent
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ SELECT_SPEAKER_PROMPT_TEMPLATE = (
43
+ "Read the above conversation. Then select the next role from {agentlist} to play. Only return the role."
44
+ )
45
+
46
+
47
+ @dataclass
48
+ @export_module("autogen")
49
+ class GroupChat:
50
+ """(In preview) A group chat class that contains the following data fields:
51
+
52
+ - agents: a list of participating agents.
53
+ - messages: a list of messages in the group chat.
54
+ - max_round: the maximum number of rounds.
55
+ - admin_name: the name of the admin agent if there is one. Default is "Admin".
56
+ KeyBoardInterrupt will make the admin agent take over.
57
+ - func_call_filter: whether to enforce function call filter. Default is True.
58
+ When set to True and when a message is a function call suggestion,
59
+ the next speaker will be chosen from an agent which contains the corresponding function name
60
+ in its `function_map`.
61
+ - select_speaker_message_template: customize the select speaker message (used in "auto" speaker selection), which appears first in the message context and generally includes the agent descriptions and list of agents. If the string contains "`{roles}`" it will replaced with the agent's and their role descriptions. If the string contains "`{agentlist}`" it will be replaced with a comma-separated list of agent names in square brackets. The default value is:
62
+ "You are in a role play game. The following roles are available:
63
+ `{roles}`.
64
+ Read the following conversation.
65
+ Then select the next role from `{agentlist}` to play. Only return the role."
66
+ - select_speaker_prompt_template: customize the select speaker prompt (used in "auto" speaker selection), which appears last in the message context and generally includes the list of agents and guidance for the LLM to select the next agent. If the string contains "`{agentlist}`" it will be replaced with a comma-separated list of agent names in square brackets. The default value is:
67
+ "Read the above conversation. Then select the next role from `{agentlist}` to play. Only return the role."
68
+ To ignore this prompt being used, set this to None. If set to None, ensure your instructions for selecting a speaker are in the select_speaker_message_template string.
69
+ - select_speaker_auto_multiple_template: customize the follow-up prompt used when selecting a speaker fails with a response that contains multiple agent names. This prompt guides the LLM to return just one agent name. Applies only to "auto" speaker selection method. If the string contains "`{agentlist}`" it will be replaced with a comma-separated list of agent names in square brackets. The default value is:
70
+ "You provided more than one name in your text, please return just the name of the next speaker. To determine the speaker use these prioritised rules:
71
+ 1. If the context refers to themselves as a speaker e.g. "As the..." , choose that speaker's name
72
+ 2. If it refers to the "next" speaker name, choose that name
73
+ 3. Otherwise, choose the first provided speaker's name in the context
74
+ The names are case-sensitive and should not be abbreviated or changed.
75
+ Respond with ONLY the name of the speaker and DO NOT provide a reason."
76
+ - select_speaker_auto_none_template: customize the follow-up prompt used when selecting a speaker fails with a response that contains no agent names. This prompt guides the LLM to return an agent name and provides a list of agent names. Applies only to "auto" speaker selection method. If the string contains "`{agentlist}`" it will be replaced with a comma-separated list of agent names in square brackets. The default value is:
77
+ "You didn't choose a speaker. As a reminder, to determine the speaker use these prioritised rules:
78
+ 1. If the context refers to themselves as a speaker e.g. "As the..." , choose that speaker's name
79
+ 2. If it refers to the "next" speaker name, choose that name
80
+ 3. Otherwise, choose the first provided speaker's name in the context
81
+ The names are case-sensitive and should not be abbreviated or changed.
82
+ The only names that are accepted are `{agentlist}`.
83
+ Respond with ONLY the name of the speaker and DO NOT provide a reason."
84
+ - speaker_selection_method: the method for selecting the next speaker. Default is "auto".
85
+ Could be any of the following (case insensitive), will raise ValueError if not recognized:
86
+ - "auto": the next speaker is selected automatically by LLM.
87
+ - "manual": the next speaker is selected manually by user input.
88
+ - "random": the next speaker is selected randomly.
89
+ - "round_robin": the next speaker is selected in a round robin fashion, i.e., iterating in the same order as provided in `agents`.
90
+ - a customized speaker selection function (Callable): the function will be called to select the next speaker.
91
+ The function should take the last speaker and the group chat as input and return one of the following:
92
+ 1. an `Agent` class, it must be one of the agents in the group chat.
93
+ 2. a string from ['auto', 'manual', 'random', 'round_robin'] to select a default method to use.
94
+ 3. None, which would terminate the conversation gracefully.
95
+ ```python
96
+ def custom_speaker_selection_func(
97
+ last_speaker: Agent, groupchat: GroupChat
98
+ ) -> Union[Agent, str, None]:
99
+ ```
100
+ - max_retries_for_selecting_speaker: the maximum number of times the speaker selection requery process will run.
101
+ If, during speaker selection, multiple agent names or no agent names are returned by the LLM as the next agent, it will be queried again up to the maximum number
102
+ of times until a single agent is returned or it exhausts the maximum attempts.
103
+ Applies only to "auto" speaker selection method.
104
+ Default is 2.
105
+ - select_speaker_transform_messages: (optional) the message transformations to apply to the nested select speaker agent-to-agent chat messages.
106
+ Takes a TransformMessages object, defaults to None and is only utilised when the speaker selection method is "auto".
107
+ - select_speaker_auto_verbose: whether to output the select speaker responses and selections.
108
+ If set to True, the outputs from the two agents in the nested select speaker chat will be output, along with
109
+ whether the responses were successful, or not, in selecting an agent.
110
+ Applies only to "auto" speaker selection method.
111
+ - allow_repeat_speaker: whether to allow the same speaker to speak consecutively.
112
+ Default is True, in which case all speakers are allowed to speak consecutively.
113
+ If `allow_repeat_speaker` is a list of Agents, then only those listed agents are allowed to repeat.
114
+ If set to False, then no speakers are allowed to repeat.
115
+ `allow_repeat_speaker` and `allowed_or_disallowed_speaker_transitions` are mutually exclusive.
116
+ - allowed_or_disallowed_speaker_transitions: dict.
117
+ The keys are source agents, and the values are agents that the key agent can/can't transit to,
118
+ depending on speaker_transitions_type. Default is None, which means all agents can transit to all other agents.
119
+ `allow_repeat_speaker` and `allowed_or_disallowed_speaker_transitions` are mutually exclusive.
120
+ - speaker_transitions_type: whether the speaker_transitions_type is a dictionary containing lists of allowed agents or disallowed agents.
121
+ "allowed" means the `allowed_or_disallowed_speaker_transitions` is a dictionary containing lists of allowed agents.
122
+ If set to "disallowed", then the `allowed_or_disallowed_speaker_transitions` is a dictionary containing lists of disallowed agents.
123
+ Must be supplied if `allowed_or_disallowed_speaker_transitions` is not None.
124
+ - enable_clear_history: enable possibility to clear history of messages for agents manually by providing
125
+ "clear history" phrase in user prompt. This is experimental feature.
126
+ See description of GroupChatManager.clear_agents_history function for more info.
127
+ - send_introductions: send a round of introductions at the start of the group chat, so agents know who they can speak to (default: False)
128
+ - select_speaker_auto_model_client_cls: Custom model client class for the internal speaker select agent used during 'auto' speaker selection (optional)
129
+ - select_speaker_auto_llm_config: LLM config for the internal speaker select agent used during 'auto' speaker selection (optional)
130
+ - role_for_select_speaker_messages: sets the role name for speaker selection when in 'auto' mode, typically 'user' or 'system'. (default: 'system')
131
+ """
132
+
133
+ agents: list[Agent]
134
+ messages: list[dict[str, Any]] = field(default_factory=list)
135
+ max_round: int = 10
136
+ admin_name: str = "Admin"
137
+ func_call_filter: bool = True
138
+ speaker_selection_method: Literal["auto", "manual", "random", "round_robin"] | Callable[..., Any] = "auto"
139
+ max_retries_for_selecting_speaker: int = 2
140
+ allow_repeat_speaker: bool | list[Agent] | None = None
141
+ allowed_or_disallowed_speaker_transitions: dict[str, Any] | None = None
142
+ speaker_transitions_type: Literal["allowed", "disallowed", None] = None
143
+ enable_clear_history: bool = False
144
+ send_introductions: bool = False
145
+ select_speaker_message_template: str = """You are in a role play game. The following roles are available:
146
+ {roles}.
147
+ Read the following conversation.
148
+ Then select the next role from {agentlist} to play. Only return the role."""
149
+ select_speaker_prompt_template: str = SELECT_SPEAKER_PROMPT_TEMPLATE
150
+ select_speaker_auto_multiple_template: str = """You provided more than one name in your text, please return just the name of the next speaker. To determine the speaker use these prioritised rules:
151
+ 1. If the context refers to themselves as a speaker e.g. "As the..." , choose that speaker's name
152
+ 2. If it refers to the "next" speaker name, choose that name
153
+ 3. Otherwise, choose the first provided speaker's name in the context
154
+ The names are case-sensitive and should not be abbreviated or changed.
155
+ Respond with ONLY the name of the speaker and DO NOT provide a reason."""
156
+ select_speaker_auto_none_template: str = """You didn't choose a speaker. As a reminder, to determine the speaker use these prioritised rules:
157
+ 1. If the context refers to themselves as a speaker e.g. "As the..." , choose that speaker's name
158
+ 2. If it refers to the "next" speaker name, choose that name
159
+ 3. Otherwise, choose the first provided speaker's name in the context
160
+ The names are case-sensitive and should not be abbreviated or changed.
161
+ The only names that are accepted are {agentlist}.
162
+ Respond with ONLY the name of the speaker and DO NOT provide a reason."""
163
+ select_speaker_transform_messages: transform_messages.TransformMessages | None = None
164
+ select_speaker_auto_verbose: bool | None = False
165
+ select_speaker_auto_model_client_cls: ModelClient | list[ModelClient] | None = None
166
+ select_speaker_auto_llm_config: LLMConfig | dict[str, Any] | Literal[False] | None = None
167
+ role_for_select_speaker_messages: str | None = "system"
168
+
169
+ _VALID_SPEAKER_SELECTION_METHODS = ["auto", "manual", "random", "round_robin"]
170
+ _VALID_SPEAKER_TRANSITIONS_TYPE = ["allowed", "disallowed", None]
171
+
172
+ # Define a class attribute for the default introduction message
173
+ DEFAULT_INTRO_MSG = (
174
+ "Hello everyone. We have assembled a great team today to answer questions and solve tasks. In attendance are:"
175
+ )
176
+
177
+ allowed_speaker_transitions_dict: dict[str, list[Agent]] = field(init=False)
178
+ _inter_agent_guardrails: list = field(default_factory=list, init=False)
179
+
180
+ def __post_init__(self):
181
+ # Post init steers clears of the automatically generated __init__ method from dataclass
182
+
183
+ if self.allow_repeat_speaker is not None and not isinstance(self.allow_repeat_speaker, (bool, list)):
184
+ raise ValueError("GroupChat allow_repeat_speaker should be a bool or a list of Agents.")
185
+
186
+ # Here, we create allowed_speaker_transitions_dict from the supplied allowed_or_disallowed_speaker_transitions and speaker_transitions_type, and lastly checks for validity.
187
+
188
+ # Check input
189
+ if self.speaker_transitions_type is not None:
190
+ self.speaker_transitions_type = self.speaker_transitions_type.lower()
191
+
192
+ if self.speaker_transitions_type not in self._VALID_SPEAKER_TRANSITIONS_TYPE:
193
+ raise ValueError(
194
+ f"GroupChat speaker_transitions_type is set to '{self.speaker_transitions_type}'. "
195
+ f"It should be one of {self._VALID_SPEAKER_TRANSITIONS_TYPE} (case insensitive). "
196
+ )
197
+
198
+ # If both self.allowed_or_disallowed_speaker_transitions is None and self.allow_repeat_speaker is None, set allow_repeat_speaker to True to ensure backward compatibility
199
+ # Discussed in https://github.com/microsoft/autogen/pull/857#discussion_r1451541204
200
+ if self.allowed_or_disallowed_speaker_transitions is None and self.allow_repeat_speaker is None:
201
+ self.allow_repeat_speaker = True
202
+
203
+ # self.allowed_or_disallowed_speaker_transitions and self.allow_repeat_speaker are mutually exclusive parameters.
204
+ # Discussed in https://github.com/microsoft/autogen/pull/857#discussion_r1451266661
205
+ if self.allowed_or_disallowed_speaker_transitions is not None and self.allow_repeat_speaker is not None:
206
+ raise ValueError(
207
+ "Don't provide both allowed_or_disallowed_speaker_transitions and allow_repeat_speaker in group chat. "
208
+ "Please set one of them to None."
209
+ )
210
+
211
+ # Asks the user to specify whether the speaker_transitions_type is allowed or disallowed if speaker_transitions_type is supplied
212
+ # Discussed in https://github.com/microsoft/autogen/pull/857#discussion_r1451259524
213
+ if self.allowed_or_disallowed_speaker_transitions is not None and self.speaker_transitions_type is None:
214
+ raise ValueError(
215
+ "GroupChat allowed_or_disallowed_speaker_transitions is not None, but speaker_transitions_type is None. "
216
+ "Please set speaker_transitions_type to either 'allowed' or 'disallowed'."
217
+ )
218
+
219
+ # Inferring self.allowed_speaker_transitions_dict
220
+ # Create self.allowed_speaker_transitions_dict if allowed_or_disallowed_speaker_transitions is None, using allow_repeat_speaker
221
+ if self.allowed_or_disallowed_speaker_transitions is None:
222
+ self.allowed_speaker_transitions_dict = {}
223
+
224
+ # Create a fully connected allowed_speaker_transitions_dict not including self loops
225
+ for agent in self.agents:
226
+ self.allowed_speaker_transitions_dict[agent] = [
227
+ other_agent for other_agent in self.agents if other_agent != agent
228
+ ]
229
+
230
+ # If self.allow_repeat_speaker is True, add self loops to all agents
231
+ if self.allow_repeat_speaker is True:
232
+ for agent in self.agents:
233
+ self.allowed_speaker_transitions_dict[agent].append(agent)
234
+
235
+ # Else if self.allow_repeat_speaker is a list of Agents, add self loops to the agents in the list
236
+ elif isinstance(self.allow_repeat_speaker, list):
237
+ for agent in self.allow_repeat_speaker:
238
+ self.allowed_speaker_transitions_dict[agent].append(agent)
239
+
240
+ # Create self.allowed_speaker_transitions_dict if allowed_or_disallowed_speaker_transitions is not None, using allowed_or_disallowed_speaker_transitions
241
+ else:
242
+ # Process based on speaker_transitions_type
243
+ if self.speaker_transitions_type == "allowed":
244
+ self.allowed_speaker_transitions_dict = self.allowed_or_disallowed_speaker_transitions
245
+ else:
246
+ # Logic for processing disallowed allowed_or_disallowed_speaker_transitions to allowed_speaker_transitions_dict
247
+ self.allowed_speaker_transitions_dict = invert_disallowed_to_allowed(
248
+ self.allowed_or_disallowed_speaker_transitions, self.agents
249
+ )
250
+
251
+ # Check for validity
252
+ check_graph_validity(
253
+ allowed_speaker_transitions_dict=self.allowed_speaker_transitions_dict,
254
+ agents=self.agents,
255
+ )
256
+
257
+ # Check select speaker messages, prompts, roles, and retries have values
258
+ if self.select_speaker_message_template is None or len(self.select_speaker_message_template) == 0:
259
+ raise ValueError("select_speaker_message_template cannot be empty or None.")
260
+
261
+ if self.select_speaker_prompt_template is not None and len(self.select_speaker_prompt_template) == 0:
262
+ self.select_speaker_prompt_template = None
263
+
264
+ if self.role_for_select_speaker_messages is None or len(self.role_for_select_speaker_messages) == 0:
265
+ raise ValueError("role_for_select_speaker_messages cannot be empty or None.")
266
+
267
+ if self.select_speaker_auto_multiple_template is None or len(self.select_speaker_auto_multiple_template) == 0:
268
+ raise ValueError("select_speaker_auto_multiple_template cannot be empty or None.")
269
+
270
+ if self.select_speaker_auto_none_template is None or len(self.select_speaker_auto_none_template) == 0:
271
+ raise ValueError("select_speaker_auto_none_template cannot be empty or None.")
272
+
273
+ if self.max_retries_for_selecting_speaker is None or len(self.role_for_select_speaker_messages) == 0:
274
+ raise ValueError("role_for_select_speaker_messages cannot be empty or None.")
275
+
276
+ # Validate max select speakers retries
277
+ if self.max_retries_for_selecting_speaker is None or not isinstance(
278
+ self.max_retries_for_selecting_speaker, int
279
+ ):
280
+ raise ValueError("max_retries_for_selecting_speaker cannot be None or non-int")
281
+ elif self.max_retries_for_selecting_speaker < 0:
282
+ raise ValueError("max_retries_for_selecting_speaker must be greater than or equal to zero")
283
+
284
+ # Load message transforms here (load once for the Group Chat so we don't have to re-initiate it and it maintains the cache across subsequent select speaker calls)
285
+ if self.select_speaker_transform_messages is not None:
286
+ if isinstance(self.select_speaker_transform_messages, transform_messages.TransformMessages):
287
+ self._speaker_selection_transforms = self.select_speaker_transform_messages
288
+ else:
289
+ raise ValueError("select_speaker_transform_messages must be None or MessageTransforms.")
290
+ else:
291
+ self._speaker_selection_transforms = None
292
+
293
+ # Validate select_speaker_auto_verbose
294
+ if self.select_speaker_auto_verbose is None or not isinstance(self.select_speaker_auto_verbose, bool):
295
+ raise ValueError("select_speaker_auto_verbose cannot be None or non-bool")
296
+
297
+ @property
298
+ def agent_names(self) -> list[str]:
299
+ """Return the names of the agents in the group chat."""
300
+ return [agent.name for agent in self.agents]
301
+
302
+ def reset(self):
303
+ """Reset the group chat."""
304
+ self.messages.clear()
305
+
306
+ def append(self, message: dict[str, Any], speaker: Agent):
307
+ """Append a message to the group chat.
308
+ We cast the content to str here so that it can be managed by text-based
309
+ model.
310
+ """
311
+ # set the name to speaker's name if the role is not function
312
+ # if the role is tool, it is OK to modify the name
313
+ if message["role"] != "function":
314
+ message["name"] = speaker.name
315
+ if not isinstance(message["content"], str) and not isinstance(message["content"], list):
316
+ message["content"] = str(message["content"])
317
+ if not isinstance(message["content"], list):
318
+ message["content"] = content_str(message["content"])
319
+ self.messages.append(message)
320
+
321
+ def agent_by_name(self, name: str, recursive: bool = False, raise_on_name_conflict: bool = False) -> Agent | None:
322
+ """Returns the agent with a given name. If recursive is True, it will search in nested teams."""
323
+ agents = self.nested_agents() if recursive else self.agents
324
+ filtered_agents = [agent for agent in agents if agent.name == name]
325
+
326
+ if raise_on_name_conflict and len(filtered_agents) > 1:
327
+ raise AgentNameConflictError()
328
+
329
+ return filtered_agents[0] if filtered_agents else None
330
+
331
+ def nested_agents(self) -> list[Agent]:
332
+ """Returns all agents in the group chat manager."""
333
+ agents = self.agents.copy()
334
+ for agent in agents:
335
+ if isinstance(agent, GroupChatManager):
336
+ # Recursive call for nested teams
337
+ agents.extend(agent.groupchat.nested_agents())
338
+ return agents
339
+
340
+ def next_agent(self, agent: Agent, agents: list[Agent] | None = None) -> Agent:
341
+ """Return the next agent in the list."""
342
+ if agents is None:
343
+ agents = self.agents
344
+
345
+ # Ensure the provided list of agents is a subset of self.agents
346
+ if not set(agents).issubset(set(self.agents)):
347
+ raise UndefinedNextAgentError()
348
+
349
+ # What index is the agent? (-1 if not present)
350
+ idx = self.agent_names.index(agent.name) if agent.name in self.agent_names else -1
351
+
352
+ # Return the next agent
353
+ if agents == self.agents:
354
+ return agents[(idx + 1) % len(agents)]
355
+ else:
356
+ offset = idx + 1
357
+ for i in range(len(self.agents)):
358
+ if self.agents[(offset + i) % len(self.agents)] in agents:
359
+ return self.agents[(offset + i) % len(self.agents)]
360
+
361
+ # Explicitly handle cases where no valid next agent exists in the provided subset.
362
+ raise UndefinedNextAgentError()
363
+
364
+ def select_speaker_msg(self, agents: list[Agent] | None = None) -> str:
365
+ """Return the system message for selecting the next speaker. This is always the *first* message in the context."""
366
+ if agents is None:
367
+ agents = self.agents
368
+
369
+ roles = self._participant_roles(agents)
370
+ agentlist = f"{[agent.name for agent in agents]}"
371
+
372
+ return_msg = self.select_speaker_message_template.format(roles=roles, agentlist=agentlist)
373
+ return return_msg
374
+
375
+ def select_speaker_prompt(self, agents: list[Agent] | None = None) -> str:
376
+ """Return the floating system prompt selecting the next speaker.
377
+ This is always the *last* message in the context.
378
+ Will return None if the select_speaker_prompt_template is None.
379
+ """
380
+ if self.select_speaker_prompt_template is None:
381
+ return None
382
+
383
+ if agents is None:
384
+ agents = self.agents
385
+
386
+ agentlist = f"{[agent.name for agent in agents]}"
387
+
388
+ return_prompt = f"{self.select_speaker_prompt_template}".replace("{agentlist}", agentlist)
389
+ return return_prompt
390
+
391
+ def introductions_msg(self, agents: list[Agent] | None = None) -> str:
392
+ """Return the system message for selecting the next speaker. This is always the *first* message in the context."""
393
+ if agents is None:
394
+ agents = self.agents
395
+
396
+ # Use the class attribute instead of a hardcoded string
397
+ intro_msg = self.DEFAULT_INTRO_MSG
398
+ participant_roles = self._participant_roles(agents)
399
+
400
+ return f"{intro_msg}\n\n{participant_roles}"
401
+
402
+ def manual_select_speaker(self, agents: list[Agent] | None = None) -> Agent | None:
403
+ """Manually select the next speaker."""
404
+ iostream = IOStream.get_default()
405
+
406
+ if agents is None:
407
+ agents = self.agents
408
+
409
+ iostream.send(SelectSpeakerEvent(agents=agents))
410
+
411
+ try_count = 0
412
+ # Assume the user will enter a valid number within 3 tries, otherwise use auto selection to avoid blocking.
413
+ while try_count <= 3:
414
+ try_count += 1
415
+ if try_count >= 3:
416
+ iostream.send(SelectSpeakerTryCountExceededEvent(try_count=try_count, agents=agents))
417
+ break
418
+ try:
419
+ i = iostream.input(
420
+ "Enter the number of the next speaker (enter nothing or `q` to use auto selection): "
421
+ )
422
+ if i == "" or i == "q":
423
+ break
424
+ i = int(i)
425
+ if i > 0 and i <= len(agents):
426
+ return agents[i - 1]
427
+ else:
428
+ raise ValueError
429
+ except ValueError:
430
+ iostream.send(SelectSpeakerInvalidInputEvent(agents=agents))
431
+ return None
432
+
433
+ def random_select_speaker(self, agents: list[Agent] | None = None) -> Agent | None:
434
+ """Randomly select the next speaker."""
435
+ if agents is None:
436
+ agents = self.agents
437
+ return random.choice(agents)
438
+
439
+ def _prepare_and_select_agents(
440
+ self,
441
+ last_speaker: Agent,
442
+ ) -> tuple[Agent | None, list[Agent], list[dict[str, Any]] | None]:
443
+ # If self.speaker_selection_method is a callable, call it to get the next speaker.
444
+ # If self.speaker_selection_method is a string, return it.
445
+ speaker_selection_method = self.speaker_selection_method
446
+ if isinstance(self.speaker_selection_method, Callable):
447
+ selected_agent = self.speaker_selection_method(last_speaker, self)
448
+ if selected_agent is None:
449
+ raise NoEligibleSpeakerError(
450
+ "Custom speaker selection function returned None. Terminating conversation."
451
+ )
452
+ elif isinstance(selected_agent, Agent):
453
+ if selected_agent in self.agents:
454
+ return selected_agent, self.agents, None
455
+ else:
456
+ raise ValueError(
457
+ f"Custom speaker selection function returned an agent {selected_agent.name} not in the group chat."
458
+ )
459
+ elif isinstance(selected_agent, str):
460
+ # If returned a string, assume it is a speaker selection method
461
+ speaker_selection_method = selected_agent
462
+ else:
463
+ raise ValueError(
464
+ f"Custom speaker selection function returned an object of type {type(selected_agent)} instead of Agent or str."
465
+ )
466
+
467
+ if speaker_selection_method.lower() not in self._VALID_SPEAKER_SELECTION_METHODS:
468
+ raise ValueError(
469
+ f"GroupChat speaker_selection_method is set to '{speaker_selection_method}'. "
470
+ f"It should be one of {self._VALID_SPEAKER_SELECTION_METHODS} (case insensitive). "
471
+ )
472
+
473
+ # If provided a list, make sure the agent is in the list
474
+ allow_repeat_speaker = (
475
+ self.allow_repeat_speaker
476
+ if isinstance(self.allow_repeat_speaker, bool) or self.allow_repeat_speaker is None
477
+ else last_speaker in self.allow_repeat_speaker
478
+ )
479
+
480
+ agents = self.agents
481
+ n_agents = len(agents)
482
+ # Warn if GroupChat is underpopulated
483
+ if n_agents < 2:
484
+ raise ValueError(
485
+ f"GroupChat is underpopulated with {n_agents} agents. "
486
+ "Please add more agents to the GroupChat or use direct communication instead."
487
+ )
488
+ elif n_agents == 2 and speaker_selection_method.lower() != "round_robin" and allow_repeat_speaker:
489
+ logger.warning(
490
+ f"GroupChat is underpopulated with {n_agents} agents. "
491
+ "Consider setting speaker_selection_method to 'round_robin' or allow_repeat_speaker to False, "
492
+ "or use direct communication, unless repeated speaker is desired."
493
+ )
494
+
495
+ if (
496
+ self.func_call_filter
497
+ and self.messages
498
+ and ("function_call" in self.messages[-1] or "tool_calls" in self.messages[-1])
499
+ ):
500
+ funcs = []
501
+ if "function_call" in self.messages[-1]:
502
+ funcs += [self.messages[-1]["function_call"]["name"]]
503
+ if "tool_calls" in self.messages[-1]:
504
+ funcs += [
505
+ tool["function"]["name"] for tool in self.messages[-1]["tool_calls"] if tool["type"] == "function"
506
+ ]
507
+
508
+ # find agents with the right function_map which contains the function name
509
+ agents = [agent for agent in self.agents if agent.can_execute_function(funcs)]
510
+ if len(agents) == 1:
511
+ # only one agent can execute the function
512
+ return agents[0], agents, None
513
+ elif not agents:
514
+ # find all the agents with function_map
515
+ agents = [agent for agent in self.agents if agent.function_map]
516
+ if len(agents) == 1:
517
+ return agents[0], agents, None
518
+ elif not agents:
519
+ raise ValueError(
520
+ f"No agent can execute the function {', '.join(funcs)}. "
521
+ "Please check the function_map of the agents."
522
+ )
523
+ # remove the last speaker from the list to avoid selecting the same speaker if allow_repeat_speaker is False
524
+ agents = [agent for agent in agents if agent != last_speaker] if allow_repeat_speaker is False else agents
525
+
526
+ # Filter agents with allowed_speaker_transitions_dict
527
+
528
+ is_last_speaker_in_group = last_speaker in self.agents
529
+
530
+ # this condition means last_speaker is a sink in the graph, then no agents are eligible
531
+ if last_speaker not in self.allowed_speaker_transitions_dict and is_last_speaker_in_group:
532
+ raise NoEligibleSpeakerError(
533
+ f"Last speaker {last_speaker.name} is not in the allowed_speaker_transitions_dict."
534
+ )
535
+ # last_speaker is not in the group, so all agents are eligible
536
+ elif last_speaker not in self.allowed_speaker_transitions_dict and not is_last_speaker_in_group:
537
+ graph_eligible_agents = []
538
+ else:
539
+ # Extract agent names from the list of agents
540
+ graph_eligible_agents = [
541
+ agent for agent in agents if agent in self.allowed_speaker_transitions_dict[last_speaker]
542
+ ]
543
+
544
+ # If there is only one eligible agent, just return it to avoid the speaker selection prompt
545
+ if len(graph_eligible_agents) == 1:
546
+ return graph_eligible_agents[0], graph_eligible_agents, None
547
+
548
+ # If there are no eligible agents, return None, which means all agents will be taken into consideration in the next step
549
+ if len(graph_eligible_agents) == 0:
550
+ graph_eligible_agents = None
551
+
552
+ # Use the selected speaker selection method
553
+ select_speaker_messages = None
554
+ if speaker_selection_method.lower() == "manual":
555
+ selected_agent = self.manual_select_speaker(graph_eligible_agents)
556
+ elif speaker_selection_method.lower() == "round_robin":
557
+ selected_agent = self.next_agent(last_speaker, graph_eligible_agents)
558
+ elif speaker_selection_method.lower() == "random":
559
+ selected_agent = self.random_select_speaker(graph_eligible_agents)
560
+ else: # auto
561
+ selected_agent = None
562
+ select_speaker_messages = self.messages.copy()
563
+ # If last message is a tool call or function call, blank the call so the api doesn't throw
564
+ if select_speaker_messages[-1].get("function_call", False):
565
+ select_speaker_messages[-1] = dict(select_speaker_messages[-1], function_call=None)
566
+ if select_speaker_messages[-1].get("tool_calls", False):
567
+ select_speaker_messages[-1] = dict(select_speaker_messages[-1], tool_calls=None)
568
+ return selected_agent, graph_eligible_agents, select_speaker_messages
569
+
570
+ def select_speaker(self, last_speaker: Agent, selector: ConversableAgent) -> Agent:
571
+ """Select the next speaker (with requery)."""
572
+ # Prepare the list of available agents and select an agent if selection method allows (non-auto)
573
+ selected_agent, agents, messages = self._prepare_and_select_agents(last_speaker)
574
+ if selected_agent:
575
+ return selected_agent
576
+ elif self.speaker_selection_method == "manual":
577
+ # An agent has not been selected while in manual mode, so move to the next agent
578
+ return self.next_agent(last_speaker)
579
+
580
+ # auto speaker selection with 2-agent chat
581
+ return self._auto_select_speaker(last_speaker, selector, messages if messages else self.messages, agents)
582
+
583
+ async def a_select_speaker(self, last_speaker: Agent, selector: ConversableAgent) -> Agent:
584
+ """Select the next speaker (with requery), asynchronously."""
585
+ selected_agent, agents, messages = self._prepare_and_select_agents(last_speaker)
586
+ if selected_agent:
587
+ return selected_agent
588
+ elif self.speaker_selection_method == "manual":
589
+ # An agent has not been selected while in manual mode, so move to the next agent
590
+ return self.next_agent(last_speaker)
591
+
592
+ # auto speaker selection with 2-agent chat
593
+ return await self.a_auto_select_speaker(last_speaker, selector, messages if messages else self.messages, agents)
594
+
595
+ def _finalize_speaker(self, last_speaker: Agent, final: bool, name: str, agents: list[Agent] | None) -> Agent:
596
+ if not final:
597
+ # the LLM client is None, thus no reply is generated. Use round robin instead.
598
+ return self.next_agent(last_speaker, agents)
599
+
600
+ # If exactly one agent is mentioned, use it. Otherwise, leave the OAI response unmodified
601
+ mentions = self._mentioned_agents(name, agents)
602
+ if len(mentions) == 1:
603
+ name = next(iter(mentions))
604
+ else:
605
+ logger.warning(
606
+ f"GroupChat select_speaker failed to resolve the next speaker's name. This is because the speaker selection OAI call returned:\n{name}"
607
+ )
608
+
609
+ # Return the result
610
+ agent = self.agent_by_name(name)
611
+ return agent if agent else self.next_agent(last_speaker, agents)
612
+
613
+ def _register_client_from_config(self, agent: Agent, config: dict):
614
+ model_client_cls_to_match = config.get("model_client_cls")
615
+ if model_client_cls_to_match:
616
+ if not self.select_speaker_auto_model_client_cls:
617
+ raise ValueError(
618
+ "A custom model was detected in the config but no 'model_client_cls' "
619
+ "was supplied for registration in GroupChat."
620
+ )
621
+
622
+ if isinstance(self.select_speaker_auto_model_client_cls, list):
623
+ # Register the first custom model client class matching the name specified in the config
624
+ matching_model_cls = [
625
+ client_cls
626
+ for client_cls in self.select_speaker_auto_model_client_cls
627
+ if client_cls.__name__ == model_client_cls_to_match
628
+ ]
629
+ if len(set(matching_model_cls)) > 1:
630
+ raise RuntimeError(
631
+ f"More than one unique 'model_client_cls' with __name__ '{model_client_cls_to_match}'."
632
+ )
633
+ if not matching_model_cls:
634
+ raise ValueError(
635
+ "No model's __name__ matches the model client class "
636
+ f"'{model_client_cls_to_match}' specified in select_speaker_auto_llm_config."
637
+ )
638
+ select_speaker_auto_model_client_cls = matching_model_cls[0]
639
+ else:
640
+ # Register the only custom model client
641
+ select_speaker_auto_model_client_cls = self.select_speaker_auto_model_client_cls
642
+
643
+ agent.register_model_client(select_speaker_auto_model_client_cls)
644
+
645
+ def _register_custom_model_clients(self, agent: ConversableAgent):
646
+ if not self.select_speaker_auto_llm_config:
647
+ return
648
+
649
+ config_format_is_list = "config_list" in self.select_speaker_auto_llm_config
650
+ if config_format_is_list:
651
+ for config in self.select_speaker_auto_llm_config["config_list"]:
652
+ self._register_client_from_config(agent, config)
653
+ elif not config_format_is_list:
654
+ self._register_client_from_config(agent, self.select_speaker_auto_llm_config)
655
+
656
+ def _create_internal_agents(
657
+ self, agents, max_attempts, messages, validate_speaker_name, selector: ConversableAgent | None = None
658
+ ):
659
+ checking_agent = ConversableAgent("checking_agent", default_auto_reply=max_attempts)
660
+
661
+ # Register the speaker validation function with the checking agent
662
+ checking_agent.register_reply(
663
+ [ConversableAgent, None],
664
+ reply_func=validate_speaker_name, # Validate each response
665
+ remove_other_reply_funcs=True,
666
+ )
667
+
668
+ # Override the selector's config if one was passed as a parameter to this class
669
+ speaker_selection_llm_config = self.select_speaker_auto_llm_config or selector.llm_config
670
+
671
+ if speaker_selection_llm_config is False:
672
+ raise ValueError(
673
+ "The group chat's internal speaker selection agent does not have an LLM configuration. Please provide a valid LLM config to the group chat's GroupChatManager or set it with the select_speaker_auto_llm_config parameter."
674
+ )
675
+
676
+ # Agent for selecting a single agent name from the response
677
+ speaker_selection_agent = ConversableAgent(
678
+ "speaker_selection_agent",
679
+ system_message=self.select_speaker_msg(agents),
680
+ chat_messages={checking_agent: messages},
681
+ llm_config=speaker_selection_llm_config,
682
+ human_input_mode="NEVER",
683
+ # Suppresses some extra terminal outputs, outputs will be handled by select_speaker_auto_verbose
684
+ )
685
+
686
+ # Register any custom model passed in select_speaker_auto_llm_config with the speaker_selection_agent
687
+ self._register_custom_model_clients(speaker_selection_agent)
688
+
689
+ return checking_agent, speaker_selection_agent
690
+
691
+ def _auto_select_speaker(
692
+ self,
693
+ last_speaker: Agent,
694
+ selector: ConversableAgent,
695
+ messages: list[dict[str, Any]] | None,
696
+ agents: list[Agent] | None,
697
+ ) -> Agent:
698
+ """Selects next speaker for the "auto" speaker selection method. Utilises its own two-agent chat to determine the next speaker and supports requerying.
699
+
700
+ Speaker selection for "auto" speaker selection method:
701
+ 1. Create a two-agent chat with a speaker selector agent and a speaker validator agent, like a nested chat
702
+ 2. Inject the group messages into the new chat
703
+ 3. Run the two-agent chat, evaluating the result of response from the speaker selector agent:
704
+ - If a single agent is provided then we return it and finish. If not, we add an additional message to this nested chat in an attempt to guide the LLM to a single agent response
705
+ 4. Chat continues until a single agent is nominated or there are no more attempts left
706
+ 5. If we run out of turns and no single agent can be determined, the next speaker in the list of agents is returned
707
+
708
+ Args:
709
+ last_speaker: The previous speaker in the group chat
710
+ selector: The ConversableAgent that initiated the speaker selection
711
+ messages: Current chat messages
712
+ agents: Valid list of agents for speaker selection
713
+
714
+ Returns:
715
+ A counter for mentioned agents.
716
+ """
717
+ # If no agents are passed in, assign all the group chat's agents
718
+ if agents is None:
719
+ agents = self.agents
720
+
721
+ # The maximum number of speaker selection attempts (including requeries)
722
+ # is the initial speaker selection attempt plus the maximum number of retries.
723
+ # We track these and use them in the validation function as we can't
724
+ # access the max_turns from within validate_speaker_name.
725
+ max_attempts = 1 + self.max_retries_for_selecting_speaker
726
+ attempts_left = max_attempts
727
+ attempt = 0
728
+
729
+ # Registered reply function for checking_agent, checks the result of the response for agent names
730
+ def validate_speaker_name(recipient, messages, sender, config) -> tuple[bool, str | dict[str, Any] | None]:
731
+ # The number of retries left, starting at max_retries_for_selecting_speaker
732
+ nonlocal attempts_left
733
+ nonlocal attempt
734
+
735
+ attempt = attempt + 1
736
+ attempts_left = attempts_left - 1
737
+
738
+ return self._validate_speaker_name(recipient, messages, sender, config, attempts_left, attempt, agents)
739
+
740
+ # Two-agent chat for speaker selection
741
+
742
+ # Agent for checking the response from the speaker_select_agent
743
+ checking_agent, speaker_selection_agent = self._create_internal_agents(
744
+ agents, max_attempts, messages, validate_speaker_name, selector
745
+ )
746
+
747
+ # Create the starting message
748
+ if self.select_speaker_prompt_template is not None:
749
+ start_message = {
750
+ "content": self.select_speaker_prompt(agents),
751
+ "name": "checking_agent",
752
+ "override_role": self.role_for_select_speaker_messages,
753
+ }
754
+ else:
755
+ start_message = messages[-1]
756
+
757
+ # Add the message transforms, if any, to the speaker selection agent
758
+ if self._speaker_selection_transforms is not None:
759
+ self._speaker_selection_transforms.add_to_agent(speaker_selection_agent)
760
+
761
+ # Run the speaker selection chat
762
+ result = checking_agent.initiate_chat(
763
+ speaker_selection_agent,
764
+ cache=None, # don't use caching for the speaker selection chat
765
+ message=start_message,
766
+ max_turns=2
767
+ * max(1, max_attempts), # Limiting the chat to the number of attempts, including the initial one
768
+ clear_history=False,
769
+ silent=not self.select_speaker_auto_verbose, # Base silence on the verbose attribute
770
+ )
771
+
772
+ return self._process_speaker_selection_result(result, last_speaker, agents)
773
+
774
+ async def a_auto_select_speaker(
775
+ self,
776
+ last_speaker: Agent,
777
+ selector: ConversableAgent,
778
+ messages: list[dict[str, Any]] | None,
779
+ agents: list[Agent] | None,
780
+ ) -> Agent:
781
+ """(Asynchronous) Selects next speaker for the "auto" speaker selection method. Utilises its own two-agent chat to determine the next speaker and supports requerying.
782
+
783
+ Speaker selection for "auto" speaker selection method:
784
+ 1. Create a two-agent chat with a speaker selector agent and a speaker validator agent, like a nested chat
785
+ 2. Inject the group messages into the new chat
786
+ 3. Run the two-agent chat, evaluating the result of response from the speaker selector agent:
787
+ - If a single agent is provided then we return it and finish. If not, we add an additional message to this nested chat in an attempt to guide the LLM to a single agent response
788
+ 4. Chat continues until a single agent is nominated or there are no more attempts left
789
+ 5. If we run out of turns and no single agent can be determined, the next speaker in the list of agents is returned
790
+
791
+ Args:
792
+ last_speaker: The previous speaker in the group chat
793
+ selector: The ConversableAgent that initiated the speaker selection
794
+ messages: Current chat messages
795
+ agents: Valid list of agents for speaker selection
796
+
797
+ Returns:
798
+ A counter for mentioned agents.
799
+ """
800
+ # If no agents are passed in, assign all the group chat's agents
801
+ if agents is None:
802
+ agents = self.agents
803
+
804
+ # The maximum number of speaker selection attempts (including requeries)
805
+ # We track these and use them in the validation function as we can't
806
+ # access the max_turns from within validate_speaker_name
807
+ max_attempts = 1 + self.max_retries_for_selecting_speaker
808
+ attempts_left = max_attempts
809
+ attempt = 0
810
+
811
+ # Registered reply function for checking_agent, checks the result of the response for agent names
812
+ def validate_speaker_name(recipient, messages, sender, config) -> tuple[bool, str | dict[str, Any] | None]:
813
+ # The number of retries left, starting at max_retries_for_selecting_speaker
814
+ nonlocal attempts_left
815
+ nonlocal attempt
816
+
817
+ attempt = attempt + 1
818
+ attempts_left = attempts_left - 1
819
+
820
+ return self._validate_speaker_name(recipient, messages, sender, config, attempts_left, attempt, agents)
821
+
822
+ # Two-agent chat for speaker selection
823
+
824
+ # Agent for checking the response from the speaker_select_agent
825
+ checking_agent, speaker_selection_agent = self._create_internal_agents(
826
+ agents, max_attempts, messages, validate_speaker_name, selector
827
+ )
828
+
829
+ # Create the starting message
830
+ if self.select_speaker_prompt_template is not None:
831
+ start_message = {
832
+ "content": self.select_speaker_prompt(agents),
833
+ "override_role": self.role_for_select_speaker_messages,
834
+ }
835
+ else:
836
+ start_message = messages[-1]
837
+
838
+ # Add the message transforms, if any, to the speaker selection agent
839
+ if self._speaker_selection_transforms is not None:
840
+ self._speaker_selection_transforms.add_to_agent(speaker_selection_agent)
841
+
842
+ # Run the speaker selection chat
843
+ result = await checking_agent.a_initiate_chat(
844
+ speaker_selection_agent,
845
+ cache=None, # don't use caching for the speaker selection chat
846
+ message=start_message,
847
+ max_turns=2
848
+ * max(1, max_attempts), # Limiting the chat to the number of attempts, including the initial one
849
+ clear_history=False,
850
+ silent=not self.select_speaker_auto_verbose, # Base silence on the verbose attribute
851
+ )
852
+
853
+ return self._process_speaker_selection_result(result, last_speaker, agents)
854
+
855
+ def _validate_speaker_name(
856
+ self, recipient, messages, sender, config, attempts_left, attempt, agents
857
+ ) -> tuple[bool, str | dict[str, Any] | None]:
858
+ """Validates the speaker response for each round in the internal 2-agent
859
+ chat within the auto select speaker method.
860
+
861
+ Used by auto_select_speaker and a_auto_select_speaker.
862
+ """
863
+ # Validate the speaker name selected
864
+ if messages and (name := messages[-1].get("content")):
865
+ mentions = self._mentioned_agents(name.strip(), agents)
866
+ else:
867
+ mentions = []
868
+ no_of_mentions = len(mentions)
869
+
870
+ # Output the query and requery results
871
+ if self.select_speaker_auto_verbose:
872
+ iostream = IOStream.get_default()
873
+ if no_of_mentions == 1:
874
+ # Success on retry, we have just one name mentioned
875
+ iostream.send(
876
+ SpeakerAttemptSuccessfulEvent(
877
+ mentions=mentions,
878
+ attempt=attempt,
879
+ attempts_left=attempts_left,
880
+ select_speaker_auto_verbose=self.select_speaker_auto_verbose,
881
+ )
882
+ )
883
+ elif no_of_mentions == 1:
884
+ iostream.send(
885
+ SpeakerAttemptFailedMultipleAgentsEvent(
886
+ mentions=mentions,
887
+ attempt=attempt,
888
+ attempts_left=attempts_left,
889
+ select_speaker_auto_verbose=self.select_speaker_auto_verbose,
890
+ )
891
+ )
892
+ else:
893
+ iostream.send(
894
+ SpeakerAttemptFailedNoAgentsEvent(
895
+ mentions=mentions,
896
+ attempt=attempt,
897
+ attempts_left=attempts_left,
898
+ select_speaker_auto_verbose=self.select_speaker_auto_verbose,
899
+ )
900
+ )
901
+
902
+ if no_of_mentions == 1:
903
+ # Success on retry, we have just one name mentioned
904
+ selected_agent_name = next(iter(mentions))
905
+
906
+ # Add the selected agent to the response so we can return it
907
+ messages.append({"role": "user", "content": f"[AGENT SELECTED]{selected_agent_name}"})
908
+
909
+ elif no_of_mentions > 1:
910
+ # More than one name on requery so add additional reminder prompt for next retry
911
+
912
+ if attempts_left:
913
+ # Message to return to the chat for the next attempt
914
+ agentlist = f"{[agent.name for agent in agents]}"
915
+
916
+ return True, {
917
+ "content": self.select_speaker_auto_multiple_template.format(agentlist=agentlist),
918
+ "name": "checking_agent",
919
+ "override_role": self.role_for_select_speaker_messages,
920
+ }
921
+ else:
922
+ # Final failure, no attempts left
923
+ messages.append({
924
+ "role": "user",
925
+ "content": f"[AGENT SELECTION FAILED]Select speaker attempt #{attempt} of {attempt + attempts_left} failed as it returned multiple names.",
926
+ })
927
+
928
+ else:
929
+ # No names at all on requery so add additional reminder prompt for next retry
930
+
931
+ if attempts_left:
932
+ # Message to return to the chat for the next attempt
933
+ agentlist = f"{[agent.name for agent in agents]}"
934
+
935
+ return True, {
936
+ "content": self.select_speaker_auto_none_template.format(agentlist=agentlist),
937
+ "name": "checking_agent",
938
+ "override_role": self.role_for_select_speaker_messages,
939
+ }
940
+ else:
941
+ # Final failure, no attempts left
942
+ messages.append({
943
+ "role": "user",
944
+ "content": f"[AGENT SELECTION FAILED]Select speaker attempt #{attempt} of {attempt + attempts_left} failed as it did not include any agent names.",
945
+ })
946
+
947
+ return True, None
948
+
949
+ def _process_speaker_selection_result(self, result, last_speaker: ConversableAgent, agents: list[Agent] | None):
950
+ """Checks the result of the auto_select_speaker function, returning the
951
+ agent to speak.
952
+
953
+ Used by auto_select_speaker and a_auto_select_speaker.
954
+ """
955
+ if len(result.chat_history) > 0:
956
+ # Use the final message, which will have the selected agent or reason for failure
957
+ final_message = result.chat_history[-1]["content"]
958
+
959
+ if "[AGENT SELECTED]" in final_message:
960
+ # Have successfully selected an agent, return it
961
+ return self.agent_by_name(final_message.replace("[AGENT SELECTED]", ""))
962
+
963
+ else: # "[AGENT SELECTION FAILED]"
964
+ # Failed to select an agent, so we'll select the next agent in the list
965
+ next_agent = self.next_agent(last_speaker, agents)
966
+
967
+ # No agent, return the failed reason
968
+ return next_agent
969
+
970
+ def _participant_roles(self, agents: list[Agent] = None) -> str:
971
+ # Default to all agents registered
972
+ if agents is None:
973
+ agents = self.agents
974
+
975
+ roles = []
976
+ for agent in agents:
977
+ if agent.description.strip() == "":
978
+ logger.warning(
979
+ f"The agent '{agent.name}' has an empty description, and may not work well with GroupChat."
980
+ )
981
+ roles.append(f"{agent.name}: {agent.description}".strip())
982
+ return "\n".join(roles)
983
+
984
+ def _mentioned_agents(self, message_content: str | list, agents: list[Agent] | None) -> dict:
985
+ """Counts the number of times each agent is mentioned in the provided message content.
986
+ Agent names will match under any of the following conditions (all case-sensitive):
987
+ - Exact name match
988
+ - If the agent name has underscores it will match with spaces instead (e.g. 'Story_writer' == 'Story writer')
989
+ - If the agent name has underscores it will match with '\\_' instead of '_' (e.g. 'Story_writer' == 'Story\\_writer')
990
+
991
+ Args:
992
+ message_content (Union[str, List]): The content of the message, either as a single string or a list of strings.
993
+ agents (List[Agent]): A list of Agent objects, each having a 'name' attribute to be searched in the message content.
994
+
995
+ Returns:
996
+ Dict: a counter for mentioned agents.
997
+ """
998
+ if agents is None:
999
+ agents = self.agents
1000
+
1001
+ # Cast message content to str
1002
+ if isinstance(message_content, dict):
1003
+ message_content = message_content["content"]
1004
+ message_content = content_str(message_content)
1005
+
1006
+ mentions = {}
1007
+ for agent in agents:
1008
+ # Finds agent mentions, taking word boundaries into account,
1009
+ # accommodates escaping underscores and underscores as spaces
1010
+ regex = (
1011
+ r"(?<=\W)("
1012
+ + re.escape(agent.name)
1013
+ + r"|"
1014
+ + re.escape(agent.name.replace("_", " "))
1015
+ + r"|"
1016
+ + re.escape(agent.name.replace("_", r"\_"))
1017
+ + r")(?=\W)"
1018
+ )
1019
+ count = len(re.findall(regex, f" {message_content} ")) # Pad the message to help with matching
1020
+ if count > 0:
1021
+ mentions[agent.name] = count
1022
+ return mentions
1023
+
1024
+ def _run_input_guardrails(
1025
+ self, agent: "ConversableAgent", messages: list[dict[str, Any]] | None = None
1026
+ ) -> str | None:
1027
+ """Run input guardrails for an agent before the reply is generated.
1028
+
1029
+ Args:
1030
+ agent (ConversableAgent): The agent whose input guardrails to run.
1031
+ messages (Optional[list[dict[str, Any]]]): The messages to check against the guardrails.
1032
+ """
1033
+ if guardrail_result := agent.run_input_guardrails(messages):
1034
+ guardrail_result.guardrail.target.activate_target(self)
1035
+ return guardrail_result.reply
1036
+ return None
1037
+
1038
+ def _run_output_guardrails(self, agent: "ConversableAgent", reply: str | dict[str, Any]) -> str | None:
1039
+ """Run output guardrails for an agent after the reply is generated.
1040
+
1041
+ Args:
1042
+ agent (ConversableAgent): The agent whose output guardrails to run.
1043
+ reply (str | dict[str, Any]): The reply generated by the agent.
1044
+ """
1045
+ if guardrail_result := agent.run_output_guardrails(reply):
1046
+ guardrail_result.guardrail.target.activate_target(self)
1047
+ return guardrail_result.reply
1048
+ return None
1049
+
1050
+ def _run_inter_agent_guardrails(
1051
+ self,
1052
+ *,
1053
+ src_agent_name: str,
1054
+ dst_agent_name: str,
1055
+ message_content: str,
1056
+ ) -> str | None:
1057
+ """Run policy-driven inter-agent guardrails, if any are configured.
1058
+
1059
+ Returns optional replacement content when a guardrail triggers.
1060
+ """
1061
+ guardrails = getattr(self, "_inter_agent_guardrails", None)
1062
+ if not guardrails:
1063
+ return None
1064
+ for gr in guardrails:
1065
+ reply = gr.check_and_act(
1066
+ src_agent_name=src_agent_name,
1067
+ dst_agent_name=dst_agent_name,
1068
+ message_content=message_content,
1069
+ )
1070
+ if reply is not None:
1071
+ return reply
1072
+ return None
1073
+
1074
+
1075
+ @export_module("autogen")
1076
+ class GroupChatManager(ConversableAgent):
1077
+ """(In preview) A chat manager agent that can manage a group chat of multiple agents."""
1078
+
1079
+ def __init__(
1080
+ self,
1081
+ groupchat: GroupChat,
1082
+ name: str | None = "chat_manager",
1083
+ # unlimited consecutive auto reply by default
1084
+ max_consecutive_auto_reply: int | None = sys.maxsize,
1085
+ human_input_mode: Literal["ALWAYS", "NEVER", "TERMINATE"] = "NEVER",
1086
+ system_message: str | list | None = "Group chat manager.",
1087
+ silent: bool = False,
1088
+ **kwargs: Any,
1089
+ ):
1090
+ if (
1091
+ kwargs.get("llm_config")
1092
+ and isinstance(kwargs["llm_config"], dict)
1093
+ and (kwargs["llm_config"].get("functions") or kwargs["llm_config"].get("tools"))
1094
+ ):
1095
+ raise ValueError(
1096
+ "GroupChatManager is not allowed to make function/tool calls. Please remove the 'functions' or 'tools' config in 'llm_config' you passed in."
1097
+ )
1098
+
1099
+ super().__init__(
1100
+ name=name,
1101
+ max_consecutive_auto_reply=max_consecutive_auto_reply,
1102
+ human_input_mode=human_input_mode,
1103
+ system_message=system_message,
1104
+ **kwargs,
1105
+ )
1106
+ if logging_enabled():
1107
+ log_new_agent(self, locals())
1108
+ # Store groupchat
1109
+ self._groupchat = groupchat
1110
+
1111
+ self._last_speaker = None
1112
+ self._silent = silent
1113
+
1114
+ # Order of register_reply is important.
1115
+ # Allow sync chat if initiated using initiate_chat
1116
+ self.register_reply(Agent, GroupChatManager.run_chat, config=groupchat, reset_config=GroupChat.reset)
1117
+ # Allow async chat if initiated using a_initiate_chat
1118
+ self.register_reply(
1119
+ Agent,
1120
+ GroupChatManager.a_run_chat,
1121
+ config=groupchat,
1122
+ reset_config=GroupChat.reset,
1123
+ ignore_async_in_sync_chat=True,
1124
+ )
1125
+
1126
+ @property
1127
+ def groupchat(self) -> GroupChat:
1128
+ """Returns the group chat managed by the group chat manager."""
1129
+ return self._groupchat
1130
+
1131
+ def chat_messages_for_summary(self, agent: Agent) -> list[dict[str, Any]]:
1132
+ """The list of messages in the group chat as a conversation to summarize.
1133
+ The agent is ignored.
1134
+ """
1135
+ return self._groupchat.messages
1136
+
1137
+ def _prepare_chat(
1138
+ self,
1139
+ recipient: ConversableAgent,
1140
+ clear_history: bool,
1141
+ prepare_recipient: bool = True,
1142
+ reply_at_receive: bool = True,
1143
+ ) -> None:
1144
+ super()._prepare_chat(recipient, clear_history, prepare_recipient, reply_at_receive)
1145
+
1146
+ if clear_history:
1147
+ self._groupchat.reset()
1148
+
1149
+ for agent in self._groupchat.agents:
1150
+ if (recipient != agent or prepare_recipient) and isinstance(agent, ConversableAgent):
1151
+ agent._prepare_chat(self, clear_history, False, reply_at_receive)
1152
+
1153
+ @property
1154
+ def last_speaker(self) -> Agent:
1155
+ """Return the agent who sent the last message to group chat manager.
1156
+
1157
+ In a group chat, an agent will always send a message to the group chat manager, and the group chat manager will
1158
+ send the message to all other agents in the group chat. So, when an agent receives a message, it will always be
1159
+ from the group chat manager. With this property, the agent receiving the message can know who actually sent the
1160
+ message.
1161
+
1162
+ Example:
1163
+ ```python
1164
+ from autogen import ConversableAgent
1165
+ from autogen import GroupChat, GroupChatManager
1166
+
1167
+
1168
+ def print_messages(recipient, messages, sender, config):
1169
+ # Print the message immediately
1170
+ print(f"Sender: {sender.name} | Recipient: {recipient.name} | Message: {messages[-1].get('content')}")
1171
+ print(f"Real Sender: {sender.last_speaker.name}")
1172
+ assert sender.last_speaker.name in messages[-1].get("content")
1173
+ return False, None # Required to ensure the agent communication flow continues
1174
+
1175
+
1176
+ agent_a = ConversableAgent("agent A", default_auto_reply="I'm agent A.")
1177
+ agent_b = ConversableAgent("agent B", default_auto_reply="I'm agent B.")
1178
+ agent_c = ConversableAgent("agent C", default_auto_reply="I'm agent C.")
1179
+ for agent in [agent_a, agent_b, agent_c]:
1180
+ agent.register_reply([ConversableAgent, None], reply_func=print_messages, config=None)
1181
+ group_chat = GroupChat(
1182
+ [agent_a, agent_b, agent_c],
1183
+ messages=[],
1184
+ max_round=6,
1185
+ speaker_selection_method="random",
1186
+ allow_repeat_speaker=True,
1187
+ )
1188
+ chat_manager = GroupChatManager(group_chat)
1189
+ groupchat_result = agent_a.initiate_chat(chat_manager, message="Hi, there, I'm agent A.")
1190
+ ```
1191
+ """
1192
+ return self._last_speaker
1193
+
1194
+ def run_chat(
1195
+ self,
1196
+ messages: list[dict[str, Any]] | None = None,
1197
+ sender: Agent | None = None,
1198
+ config: GroupChat | None = None,
1199
+ ) -> tuple[bool, str | None]:
1200
+ """Run a group chat."""
1201
+ iostream = IOStream.get_default()
1202
+
1203
+ if messages is None:
1204
+ messages = self._oai_messages[sender]
1205
+ message = messages[-1]
1206
+ speaker = sender
1207
+ groupchat = config
1208
+ send_introductions = getattr(groupchat, "send_introductions", False)
1209
+ silent = getattr(self, "_silent", False)
1210
+ termination_reason = None
1211
+
1212
+ if send_introductions:
1213
+ # Broadcast the intro
1214
+ intro = groupchat.introductions_msg()
1215
+ for agent in groupchat.agents:
1216
+ self.send(intro, agent, request_reply=False, silent=True)
1217
+ # NOTE: We do not also append to groupchat.messages,
1218
+ # since groupchat handles its own introductions
1219
+
1220
+ if self.client_cache is not None:
1221
+ for a in groupchat.agents:
1222
+ a.previous_cache = a.client_cache
1223
+ a.client_cache = self.client_cache
1224
+ for i in range(groupchat.max_round):
1225
+ self._last_speaker = speaker
1226
+ groupchat.append(message, speaker)
1227
+ # broadcast the message to all agents except the speaker
1228
+ for agent in groupchat.agents:
1229
+ if agent != speaker:
1230
+ inter_reply = groupchat._run_inter_agent_guardrails(
1231
+ src_agent_name=speaker.name,
1232
+ dst_agent_name=agent.name,
1233
+ message_content=message,
1234
+ )
1235
+ if inter_reply is not None:
1236
+ replacement = (
1237
+ {"content": inter_reply, "name": speaker.name}
1238
+ if not isinstance(inter_reply, dict)
1239
+ else inter_reply
1240
+ )
1241
+ self.send(replacement, agent, request_reply=False, silent=True)
1242
+ else:
1243
+ self.send(message, agent, request_reply=False, silent=True)
1244
+
1245
+ if self._is_termination_msg(message):
1246
+ # The conversation is over
1247
+ termination_reason = f"Termination message condition on the GroupChatManager '{self.name}' met"
1248
+ break
1249
+ elif i == groupchat.max_round - 1:
1250
+ # It's the last round
1251
+ termination_reason = f"Maximum rounds ({groupchat.max_round}) reached"
1252
+ break
1253
+ try:
1254
+ # select the next speaker
1255
+ speaker = groupchat.select_speaker(speaker, self)
1256
+ if not silent:
1257
+ iostream = IOStream.get_default()
1258
+ iostream.send(GroupChatRunChatEvent(speaker=speaker, silent=silent))
1259
+
1260
+ guardrails_activated = False
1261
+ guardrails_reply = groupchat._run_input_guardrails(speaker, speaker._oai_messages[self])
1262
+
1263
+ if guardrails_reply is not None:
1264
+ # if a guardrail has been activated, then the next target has been set and the guardrail reply will be sent
1265
+ guardrails_activated = True
1266
+ reply = guardrails_reply
1267
+ else:
1268
+ # let the speaker speak
1269
+ reply = speaker.generate_reply(sender=self)
1270
+ except KeyboardInterrupt:
1271
+ # let the admin agent speak if interrupted
1272
+ if groupchat.admin_name in groupchat.agent_names:
1273
+ # admin agent is one of the participants
1274
+ speaker = groupchat.agent_by_name(groupchat.admin_name)
1275
+ reply = speaker.generate_reply(sender=self)
1276
+ else:
1277
+ # admin agent is not found in the participants
1278
+ raise
1279
+ except NoEligibleSpeakerError:
1280
+ # No eligible speaker, terminate the conversation
1281
+ termination_reason = "No next speaker selected"
1282
+ break
1283
+
1284
+ if reply is None:
1285
+ # no reply is generated, exit the chat
1286
+ termination_reason = "No reply generated"
1287
+ break
1288
+
1289
+ if not guardrails_activated:
1290
+ # if the input guardrails were not activated, and the agent returned a reply
1291
+ guardrails_reply = groupchat._run_output_guardrails(speaker, reply)
1292
+
1293
+ if guardrails_reply is not None:
1294
+ # if a guardrail has been activated, then the next target has been set and the guardrail reply will be sent
1295
+ guardrails_activated = True
1296
+ reply = guardrails_reply
1297
+
1298
+ # check for "clear history" phrase in reply and activate clear history function if found
1299
+ if groupchat.enable_clear_history and isinstance(reply, dict) and reply.get("content"):
1300
+ raw_content = reply.get("content")
1301
+ normalized_content = (
1302
+ content_str(raw_content)
1303
+ if isinstance(raw_content, (str, list)) or raw_content is None
1304
+ else str(raw_content)
1305
+ )
1306
+ if "CLEAR HISTORY" in normalized_content.upper():
1307
+ reply["content"] = normalized_content
1308
+ reply["content"] = self.clear_agents_history(reply, groupchat)
1309
+
1310
+ # The speaker sends the message without requesting a reply
1311
+ speaker.send(reply, self, request_reply=False, silent=silent)
1312
+ message = self.last_message(speaker)
1313
+ if self.client_cache is not None:
1314
+ for a in groupchat.agents:
1315
+ a.client_cache = a.previous_cache
1316
+ a.previous_cache = None
1317
+
1318
+ if termination_reason:
1319
+ iostream.send(
1320
+ TerminationEvent(
1321
+ termination_reason=termination_reason, sender=self, recipient=speaker if speaker else None
1322
+ )
1323
+ )
1324
+
1325
+ return True, None
1326
+
1327
+ async def a_run_chat(
1328
+ self,
1329
+ messages: list[dict[str, Any]] | None = None,
1330
+ sender: Agent | None = None,
1331
+ config: GroupChat | None = None,
1332
+ ):
1333
+ """Run a group chat asynchronously."""
1334
+ iostream = IOStream.get_default()
1335
+
1336
+ if messages is None:
1337
+ messages = self._oai_messages[sender]
1338
+ message = messages[-1]
1339
+ speaker = sender
1340
+ groupchat = config
1341
+ send_introductions = getattr(groupchat, "send_introductions", False)
1342
+ silent = getattr(self, "_silent", False)
1343
+ termination_reason = None
1344
+
1345
+ if send_introductions:
1346
+ # Broadcast the intro
1347
+ intro = groupchat.introductions_msg()
1348
+ for agent in groupchat.agents:
1349
+ await self.a_send(intro, agent, request_reply=False, silent=True)
1350
+ # NOTE: We do not also append to groupchat.messages,
1351
+ # since groupchat handles its own introductions
1352
+
1353
+ if self.client_cache is not None:
1354
+ for a in groupchat.agents:
1355
+ a.previous_cache = a.client_cache
1356
+ a.client_cache = self.client_cache
1357
+ for i in range(groupchat.max_round):
1358
+ groupchat.append(message, speaker)
1359
+ self._last_speaker = speaker
1360
+
1361
+ if self._is_termination_msg(message):
1362
+ # The conversation is over
1363
+ termination_reason = f"Termination message condition on the GroupChatManager '{self.name}' met"
1364
+ break
1365
+
1366
+ # broadcast the message to all agents except the speaker
1367
+ for agent in groupchat.agents:
1368
+ if agent != speaker:
1369
+ await self.a_send(message, agent, request_reply=False, silent=True)
1370
+ if i == groupchat.max_round - 1:
1371
+ # the last round
1372
+ termination_reason = f"Maximum rounds ({groupchat.max_round}) reached"
1373
+ break
1374
+ try:
1375
+ # select the next speaker
1376
+ speaker = await groupchat.a_select_speaker(speaker, self)
1377
+ if not silent:
1378
+ iostream.send(GroupChatRunChatEvent(speaker=speaker, silent=silent))
1379
+
1380
+ guardrails_activated = False
1381
+ guardrails_reply = groupchat._run_input_guardrails(speaker, speaker._oai_messages[self])
1382
+
1383
+ if guardrails_reply is not None:
1384
+ # if a guardrail has been activated, then the next target has been set and the guardrail reply will be sent
1385
+ guardrails_activated = True
1386
+ reply = guardrails_reply
1387
+ else:
1388
+ # let the speaker speak
1389
+ reply = await speaker.a_generate_reply(sender=self)
1390
+ except KeyboardInterrupt:
1391
+ # let the admin agent speak if interrupted
1392
+ if groupchat.admin_name in groupchat.agent_names:
1393
+ # admin agent is one of the participants
1394
+ speaker = groupchat.agent_by_name(groupchat.admin_name)
1395
+ reply = await speaker.a_generate_reply(sender=self)
1396
+ else:
1397
+ # admin agent is not found in the participants
1398
+ raise
1399
+ except NoEligibleSpeakerError:
1400
+ # No eligible speaker, terminate the conversation
1401
+ termination_reason = "No next speaker selected"
1402
+ break
1403
+
1404
+ if reply is None:
1405
+ # no reply is generated, exit the chat
1406
+ termination_reason = "No reply generated"
1407
+ break
1408
+
1409
+ if not guardrails_activated:
1410
+ # if the input guardrails were not activated, and the agent returned a reply
1411
+ guardrails_reply = groupchat._run_output_guardrails(speaker, reply)
1412
+
1413
+ if guardrails_reply is not None:
1414
+ # if a guardrail has been activated, then the next target has been set and the guardrail reply will be sent
1415
+ guardrails_activated = True
1416
+ reply = guardrails_reply
1417
+
1418
+ # check for "clear history" phrase in reply and activate clear history function if found
1419
+ if groupchat.enable_clear_history and isinstance(reply, dict) and reply.get("content"):
1420
+ raw_content = reply.get("content")
1421
+ normalized_content = (
1422
+ content_str(raw_content)
1423
+ if isinstance(raw_content, (str, list)) or raw_content is None
1424
+ else str(raw_content)
1425
+ )
1426
+ if "CLEAR HISTORY" in normalized_content.upper():
1427
+ reply["content"] = normalized_content
1428
+ reply["content"] = self.clear_agents_history(reply, groupchat)
1429
+
1430
+ # The speaker sends the message without requesting a reply
1431
+ await speaker.a_send(reply, self, request_reply=False, silent=silent)
1432
+ message = self.last_message(speaker)
1433
+ if self.client_cache is not None:
1434
+ for a in groupchat.agents:
1435
+ a.client_cache = a.previous_cache
1436
+ a.previous_cache = None
1437
+
1438
+ if termination_reason:
1439
+ iostream.send(
1440
+ TerminationEvent(
1441
+ termination_reason=termination_reason, sender=self, recipient=speaker if speaker else None
1442
+ )
1443
+ )
1444
+
1445
+ return True, None
1446
+
1447
+ def resume(
1448
+ self,
1449
+ messages: list[dict[str, Any]] | str,
1450
+ remove_termination_string: str | Callable[[str], str] | None = None,
1451
+ silent: bool | None = False,
1452
+ ) -> tuple[ConversableAgent, dict[str, Any]]:
1453
+ """Resumes a group chat using the previous messages as a starting point. Requires the agents, group chat, and group chat manager to be established
1454
+ as per the original group chat.
1455
+
1456
+ Args:
1457
+ messages: The content of the previous chat's messages, either as a Json string or a list of message dictionaries.
1458
+ remove_termination_string: Remove the termination string from the last message to prevent immediate termination
1459
+ If a string is provided, this string will be removed from last message.
1460
+ If a function is provided, the last message will be passed to this function.
1461
+ silent: (Experimental) whether to print the messages for this conversation. Default is False.
1462
+
1463
+ Returns:
1464
+ A tuple containing the last agent who spoke and their message
1465
+ """
1466
+ # Convert messages from string to messages list, if needed
1467
+ if isinstance(messages, str):
1468
+ messages = self.messages_from_string(messages)
1469
+ elif isinstance(messages, list) and all(isinstance(item, dict) for item in messages):
1470
+ messages = copy.deepcopy(messages)
1471
+ else:
1472
+ raise Exception("Messages is not of type str or List[Dict]")
1473
+
1474
+ # Clean up the objects, ensuring there are no messages in the agents and group chat
1475
+
1476
+ # Clear agent message history
1477
+ for agent in self._groupchat.agents:
1478
+ if isinstance(agent, ConversableAgent):
1479
+ agent.clear_history()
1480
+
1481
+ # Clear Manager message history
1482
+ self.clear_history()
1483
+
1484
+ # Clear GroupChat messages
1485
+ self._groupchat.reset()
1486
+
1487
+ # Validation of message and agents
1488
+
1489
+ try:
1490
+ self._valid_resume_messages(messages)
1491
+ except:
1492
+ raise
1493
+
1494
+ # Load the messages into the group chat
1495
+ for i, message in enumerate(messages):
1496
+ if "name" in message:
1497
+ message_speaker_agent = self._groupchat.agent_by_name(message["name"])
1498
+ else:
1499
+ # If there's no name, assign the group chat manager (this is an indication the ChatResult messages was used instead of groupchat.messages as state)
1500
+ message_speaker_agent = self
1501
+ message["name"] = self.name
1502
+
1503
+ # If it wasn't an agent speaking, it may be the manager
1504
+ if not message_speaker_agent and message["name"] == self.name:
1505
+ message_speaker_agent = self
1506
+
1507
+ # Add previous messages to each agent (except the last message, as we'll kick off the conversation with it)
1508
+ if i != len(messages) - 1:
1509
+ for agent in self._groupchat.agents:
1510
+ if agent.name == message["name"]:
1511
+ # An agent`s message is sent to the Group Chat Manager
1512
+ agent.send(message, self, request_reply=False, silent=True)
1513
+ else:
1514
+ # Otherwise, messages are sent from the Group Chat Manager to the agent
1515
+ self.send(message, agent, request_reply=False, silent=True)
1516
+
1517
+ # Add previous message to the new groupchat, if it's an admin message the name may not match so add the message directly
1518
+ if message_speaker_agent:
1519
+ self._groupchat.append(message, message_speaker_agent)
1520
+ else:
1521
+ self._groupchat.messages.append(message)
1522
+
1523
+ # Last speaker agent
1524
+ last_speaker_name = message["name"]
1525
+
1526
+ # Last message to check for termination (we could avoid this by ignoring termination check for resume in the future)
1527
+ last_message = message
1528
+
1529
+ # Get last speaker as an agent
1530
+ previous_last_agent = self._groupchat.agent_by_name(name=last_speaker_name)
1531
+
1532
+ # If we didn't match a last speaker agent, we check that it's the group chat's admin name and assign the manager, if so
1533
+ if not previous_last_agent and (
1534
+ last_speaker_name == self._groupchat.admin_name or last_speaker_name == self.name
1535
+ ):
1536
+ previous_last_agent = self
1537
+
1538
+ # Termination removal and check
1539
+ self._process_resume_termination(remove_termination_string, messages)
1540
+
1541
+ if not silent:
1542
+ iostream = IOStream.get_default()
1543
+ iostream.send(GroupChatResumeEvent(last_speaker_name=last_speaker_name, events=messages, silent=silent))
1544
+
1545
+ # Update group chat settings for resuming
1546
+ self._groupchat.send_introductions = False
1547
+
1548
+ return previous_last_agent, last_message
1549
+
1550
+ async def a_resume(
1551
+ self,
1552
+ messages: list[dict[str, Any]] | str,
1553
+ remove_termination_string: str | Callable[[str], str] | None = None,
1554
+ silent: bool | None = False,
1555
+ ) -> tuple[ConversableAgent, dict[str, Any]]:
1556
+ """Resumes a group chat using the previous messages as a starting point, asynchronously. Requires the agents, group chat, and group chat manager to be established
1557
+ as per the original group chat.
1558
+
1559
+ Args:
1560
+ messages: The content of the previous chat's messages, either as a Json string or a list of message dictionaries.
1561
+ remove_termination_string: Remove the termination string from the last message to prevent immediate termination
1562
+ If a string is provided, this string will be removed from last message.
1563
+ If a function is provided, the last message will be passed to this function, and the function returns the string after processing.
1564
+ silent: (Experimental) whether to print the messages for this conversation. Default is False.
1565
+
1566
+ Returns:
1567
+ A tuple containing the last agent who spoke and their message
1568
+ """
1569
+ # Convert messages from string to messages list, if needed
1570
+ if isinstance(messages, str):
1571
+ messages = self.messages_from_string(messages)
1572
+ elif isinstance(messages, list) and all(isinstance(item, dict) for item in messages):
1573
+ messages = copy.deepcopy(messages)
1574
+ else:
1575
+ raise Exception("Messages is not of type str or List[Dict]")
1576
+
1577
+ # Clean up the objects, ensuring there are no messages in the agents and group chat
1578
+
1579
+ # Clear agent message history
1580
+ for agent in self._groupchat.agents:
1581
+ if isinstance(agent, ConversableAgent):
1582
+ agent.clear_history()
1583
+
1584
+ # Clear Manager message history
1585
+ self.clear_history()
1586
+
1587
+ # Clear GroupChat messages
1588
+ self._groupchat.reset()
1589
+
1590
+ # Validation of message and agents
1591
+
1592
+ try:
1593
+ self._valid_resume_messages(messages)
1594
+ except:
1595
+ raise
1596
+
1597
+ # Load the messages into the group chat
1598
+ for i, message in enumerate(messages):
1599
+ if "name" in message:
1600
+ message_speaker_agent = self._groupchat.agent_by_name(message["name"])
1601
+ else:
1602
+ # If there's no name, assign the group chat manager (this is an indication the ChatResult messages was used instead of groupchat.messages as state)
1603
+ message_speaker_agent = self
1604
+ message["name"] = self.name
1605
+
1606
+ # If it wasn't an agent speaking, it may be the manager
1607
+ if not message_speaker_agent and message["name"] == self.name:
1608
+ message_speaker_agent = self
1609
+
1610
+ # Add previous messages to each agent (except the last message, as we'll kick off the conversation with it)
1611
+ if i != len(messages) - 1:
1612
+ for agent in self._groupchat.agents:
1613
+ if agent.name == message["name"]:
1614
+ # An agent`s message is sent to the Group Chat Manager
1615
+ await agent.a_send(message, self, request_reply=False, silent=True)
1616
+ else:
1617
+ # Otherwise, messages are sent from the Group Chat Manager to the agent
1618
+ await self.a_send(message, agent, request_reply=False, silent=True)
1619
+
1620
+ # Add previous message to the new groupchat, if it's an admin message the name may not match so add the message directly
1621
+ if message_speaker_agent:
1622
+ self._groupchat.append(message, message_speaker_agent)
1623
+ else:
1624
+ self._groupchat.messages.append(message)
1625
+
1626
+ # Last speaker agent
1627
+ last_speaker_name = message["name"]
1628
+
1629
+ # Last message to check for termination (we could avoid this by ignoring termination check for resume in the future)
1630
+ last_message = message
1631
+
1632
+ # Get last speaker as an agent
1633
+ previous_last_agent = self._groupchat.agent_by_name(name=last_speaker_name)
1634
+
1635
+ # If we didn't match a last speaker agent, we check that it's the group chat's admin name and assign the manager, if so
1636
+ if not previous_last_agent and (
1637
+ last_speaker_name == self._groupchat.admin_name or last_speaker_name == self.name
1638
+ ):
1639
+ previous_last_agent = self
1640
+
1641
+ # Termination removal and check
1642
+ self._process_resume_termination(remove_termination_string, messages)
1643
+
1644
+ if not silent:
1645
+ iostream = IOStream.get_default()
1646
+ iostream.send(GroupChatResumeEvent(last_speaker_name=last_speaker_name, events=messages, silent=silent))
1647
+
1648
+ # Update group chat settings for resuming
1649
+ self._groupchat.send_introductions = False
1650
+
1651
+ return previous_last_agent, last_message
1652
+
1653
+ def _valid_resume_messages(self, messages: list[dict[str, Any]]):
1654
+ """Validates the messages used for resuming
1655
+
1656
+ Args:
1657
+ messages (List[Dict]): list of messages to resume with
1658
+
1659
+ Returns:
1660
+ - bool: Whether they are valid for resuming
1661
+ """
1662
+ # Must have messages to start with, otherwise they should run run_chat
1663
+ if not messages:
1664
+ raise Exception(
1665
+ "Cannot resume group chat as no messages were provided. Use GroupChatManager.run_chat or ConversableAgent.initiate_chat to start a new chat."
1666
+ )
1667
+
1668
+ # Check that all agents in the chat messages exist in the group chat
1669
+ for message in messages:
1670
+ if message.get("name") and (
1671
+ not self._groupchat.agent_by_name(message["name"])
1672
+ and not message["name"] == self._groupchat.admin_name # ignore group chat's name
1673
+ and not message["name"] == self.name # ignore group chat manager's name
1674
+ ):
1675
+ raise Exception(f"Agent name in message doesn't exist as agent in group chat: {message['name']}")
1676
+
1677
+ def _process_resume_termination(
1678
+ self, remove_termination_string: str | Callable[[str], str], messages: list[dict[str, Any]]
1679
+ ):
1680
+ """Removes termination string, if required, and checks if termination may occur.
1681
+
1682
+ Args:
1683
+ remove_termination_string: Remove the termination string from the last message to prevent immediate termination
1684
+ If a string is provided, this string will be removed from last message.
1685
+ If a function is provided, the last message will be passed to this function, and the function returns the string after processing.
1686
+ messages: List of chat messages
1687
+
1688
+ Returns:
1689
+ None
1690
+ """
1691
+ last_message = messages[-1]
1692
+
1693
+ # Replace any given termination string in the last message
1694
+ if isinstance(remove_termination_string, str):
1695
+
1696
+ def _remove_termination_string(content: str) -> str:
1697
+ return content.replace(remove_termination_string, "")
1698
+
1699
+ else:
1700
+ _remove_termination_string = remove_termination_string
1701
+
1702
+ if _remove_termination_string and messages[-1].get("content"):
1703
+ content_value = messages[-1]["content"]
1704
+ if isinstance(content_value, str):
1705
+ messages[-1]["content"] = _remove_termination_string(content_value)
1706
+ elif isinstance(content_value, list):
1707
+ messages[-1]["content"] = _remove_termination_string(content_str(content_value))
1708
+ else:
1709
+ messages[-1]["content"] = _remove_termination_string(str(content_value))
1710
+
1711
+ # Check if the last message meets termination (if it has one)
1712
+ if self._is_termination_msg and self._is_termination_msg(last_message):
1713
+ logger.warning("WARNING: Last message meets termination criteria and this may terminate the chat.")
1714
+
1715
+ def messages_from_string(self, message_string: str) -> list[dict[str, Any]]:
1716
+ """Reads the saved state of messages in Json format for resume and returns as a messages list
1717
+
1718
+ Args:
1719
+ message_string: Json string, the saved state
1720
+
1721
+ Returns:
1722
+ A list of messages
1723
+ """
1724
+ try:
1725
+ state = json.loads(message_string)
1726
+ except json.JSONDecodeError:
1727
+ raise Exception("Messages string is not a valid JSON string")
1728
+
1729
+ return state
1730
+
1731
+ def messages_to_string(self, messages: list[dict[str, Any]]) -> str:
1732
+ """Converts the provided messages into a Json string that can be used for resuming the chat.
1733
+ The state is made up of a list of messages
1734
+
1735
+ Args:
1736
+ messages: set of messages to convert to a string
1737
+
1738
+ Returns:
1739
+ A JSON representation of the messages which can be persisted for resuming later
1740
+ """
1741
+ return json.dumps(messages)
1742
+
1743
+ def _raise_exception_on_async_reply_functions(self) -> None:
1744
+ """Raise an exception if any async reply functions are registered.
1745
+
1746
+ Raises:
1747
+ RuntimeError: if any async reply functions are registered.
1748
+ """
1749
+ super()._raise_exception_on_async_reply_functions()
1750
+
1751
+ for agent in self._groupchat.agents:
1752
+ agent._raise_exception_on_async_reply_functions()
1753
+
1754
+ def clear_agents_history(self, reply: dict[str, Any], groupchat: GroupChat) -> str:
1755
+ """Clears history of messages for all agents or a selected one. Can preserve a selected number of last messages.\n
1756
+ \n
1757
+ This function is called when the user manually provides the "clear history" phrase in their reply.\n
1758
+ When "clear history" is provided, the history of messages for all agents is cleared.\n
1759
+ When "clear history `<agent_name>`" is provided, the history of messages for the selected agent is cleared.\n
1760
+ When "clear history `<nr_of_messages_to_preserve>`" is provided, the history of messages for all agents is cleared\n
1761
+ except for the last `<nr_of_messages_to_preserve>` messages.\n
1762
+ When "clear history `<agent_name>` `<nr_of_messages_to_preserve>`" is provided, the history of messages for the selected\n
1763
+ agent is cleared except for the last `<nr_of_messages_to_preserve>` messages.\n
1764
+ The phrase "clear history" and optional arguments are cut out from the reply before it is passed to the chat.\n
1765
+ \n
1766
+ Args:\n
1767
+ reply (dict): reply message dict to analyze.\n
1768
+ groupchat (GroupChat): GroupChat object.\n
1769
+ """
1770
+ iostream = IOStream.get_default()
1771
+
1772
+ raw_reply_content = reply.get("content")
1773
+ if isinstance(raw_reply_content, str):
1774
+ reply_content = raw_reply_content
1775
+ elif isinstance(raw_reply_content, (list, type(None))):
1776
+ reply_content = content_str(raw_reply_content)
1777
+ reply["content"] = reply_content
1778
+ else:
1779
+ reply_content = str(raw_reply_content)
1780
+ reply["content"] = reply_content
1781
+ # Split the reply into words
1782
+ words = reply_content.split()
1783
+ # Find the position of "clear" to determine where to start processing
1784
+ clear_word_index = next(i for i in reversed(range(len(words))) if words[i].upper() == "CLEAR")
1785
+ # Extract potential agent name and steps
1786
+ words_to_check = words[clear_word_index + 2 : clear_word_index + 4]
1787
+ nr_messages_to_preserve = None
1788
+ nr_messages_to_preserve_provided = False
1789
+ agent_to_memory_clear = None
1790
+
1791
+ for word in words_to_check:
1792
+ if word.isdigit():
1793
+ nr_messages_to_preserve = int(word)
1794
+ nr_messages_to_preserve_provided = True
1795
+ elif word[:-1].isdigit(): # for the case when number of messages is followed by dot or other sign
1796
+ nr_messages_to_preserve = int(word[:-1])
1797
+ nr_messages_to_preserve_provided = True
1798
+ else:
1799
+ for agent in groupchat.agents:
1800
+ if agent.name == word or agent.name == word[:-1]:
1801
+ agent_to_memory_clear = agent
1802
+ break
1803
+ # preserve last tool call message if clear history called inside of tool response
1804
+ if "tool_responses" in reply and not nr_messages_to_preserve:
1805
+ nr_messages_to_preserve = 1
1806
+ logger.warning(
1807
+ "The last tool call message will be saved to prevent errors caused by tool response without tool call."
1808
+ )
1809
+ # clear history
1810
+ iostream.send(
1811
+ ClearAgentsHistoryEvent(agent=agent_to_memory_clear, nr_events_to_preserve=nr_messages_to_preserve)
1812
+ )
1813
+ if agent_to_memory_clear:
1814
+ agent_to_memory_clear.clear_history(nr_messages_to_preserve=nr_messages_to_preserve)
1815
+ else:
1816
+ if nr_messages_to_preserve:
1817
+ # clearing history for groupchat here
1818
+ temp = groupchat.messages[-nr_messages_to_preserve:]
1819
+ groupchat.messages.clear()
1820
+ groupchat.messages.extend(temp)
1821
+ else:
1822
+ # clearing history for groupchat here
1823
+ groupchat.messages.clear()
1824
+ # clearing history for agents
1825
+ for agent in groupchat.agents:
1826
+ agent.clear_history(nr_messages_to_preserve=nr_messages_to_preserve)
1827
+
1828
+ # Reconstruct the reply without the "clear history" command and parameters
1829
+ skip_words_number = 2 + int(bool(agent_to_memory_clear)) + int(nr_messages_to_preserve_provided)
1830
+ reply_content = " ".join(words[:clear_word_index] + words[clear_word_index + skip_words_number :])
1831
+
1832
+ return reply_content