ag2 0.9.1a1__py3-none-any.whl → 0.9.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.

Potentially problematic release.


This version of ag2 might be problematic. Click here for more details.

Files changed (371) hide show
  1. {ag2-0.9.1a1.dist-info → ag2-0.9.2.dist-info}/METADATA +272 -75
  2. ag2-0.9.2.dist-info/RECORD +406 -0
  3. {ag2-0.9.1a1.dist-info → ag2-0.9.2.dist-info}/WHEEL +1 -2
  4. autogen/__init__.py +89 -0
  5. autogen/_website/__init__.py +3 -0
  6. autogen/_website/generate_api_references.py +427 -0
  7. autogen/_website/generate_mkdocs.py +1174 -0
  8. autogen/_website/notebook_processor.py +476 -0
  9. autogen/_website/process_notebooks.py +656 -0
  10. autogen/_website/utils.py +412 -0
  11. autogen/agentchat/__init__.py +44 -0
  12. autogen/agentchat/agent.py +182 -0
  13. autogen/agentchat/assistant_agent.py +85 -0
  14. autogen/agentchat/chat.py +309 -0
  15. autogen/agentchat/contrib/__init__.py +5 -0
  16. autogen/agentchat/contrib/agent_eval/README.md +7 -0
  17. autogen/agentchat/contrib/agent_eval/agent_eval.py +108 -0
  18. autogen/agentchat/contrib/agent_eval/criterion.py +43 -0
  19. autogen/agentchat/contrib/agent_eval/critic_agent.py +44 -0
  20. autogen/agentchat/contrib/agent_eval/quantifier_agent.py +39 -0
  21. autogen/agentchat/contrib/agent_eval/subcritic_agent.py +45 -0
  22. autogen/agentchat/contrib/agent_eval/task.py +42 -0
  23. autogen/agentchat/contrib/agent_optimizer.py +429 -0
  24. autogen/agentchat/contrib/capabilities/__init__.py +5 -0
  25. autogen/agentchat/contrib/capabilities/agent_capability.py +20 -0
  26. autogen/agentchat/contrib/capabilities/generate_images.py +301 -0
  27. autogen/agentchat/contrib/capabilities/teachability.py +393 -0
  28. autogen/agentchat/contrib/capabilities/text_compressors.py +66 -0
  29. autogen/agentchat/contrib/capabilities/tools_capability.py +22 -0
  30. autogen/agentchat/contrib/capabilities/transform_messages.py +93 -0
  31. autogen/agentchat/contrib/capabilities/transforms.py +566 -0
  32. autogen/agentchat/contrib/capabilities/transforms_util.py +122 -0
  33. autogen/agentchat/contrib/capabilities/vision_capability.py +214 -0
  34. autogen/agentchat/contrib/captainagent/__init__.py +9 -0
  35. autogen/agentchat/contrib/captainagent/agent_builder.py +790 -0
  36. autogen/agentchat/contrib/captainagent/captainagent.py +512 -0
  37. autogen/agentchat/contrib/captainagent/tool_retriever.py +335 -0
  38. autogen/agentchat/contrib/captainagent/tools/README.md +44 -0
  39. autogen/agentchat/contrib/captainagent/tools/__init__.py +5 -0
  40. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_correlation.py +40 -0
  41. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_skewness_and_kurtosis.py +28 -0
  42. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_iqr.py +28 -0
  43. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_zscore.py +28 -0
  44. autogen/agentchat/contrib/captainagent/tools/data_analysis/explore_csv.py +21 -0
  45. autogen/agentchat/contrib/captainagent/tools/data_analysis/shapiro_wilk_test.py +30 -0
  46. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_download.py +27 -0
  47. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_search.py +53 -0
  48. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_image.py +53 -0
  49. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_text.py +38 -0
  50. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_wikipedia_text.py +21 -0
  51. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_youtube_caption.py +34 -0
  52. autogen/agentchat/contrib/captainagent/tools/information_retrieval/image_qa.py +60 -0
  53. autogen/agentchat/contrib/captainagent/tools/information_retrieval/optical_character_recognition.py +61 -0
  54. autogen/agentchat/contrib/captainagent/tools/information_retrieval/perform_web_search.py +47 -0
  55. autogen/agentchat/contrib/captainagent/tools/information_retrieval/scrape_wikipedia_tables.py +33 -0
  56. autogen/agentchat/contrib/captainagent/tools/information_retrieval/transcribe_audio_file.py +21 -0
  57. autogen/agentchat/contrib/captainagent/tools/information_retrieval/youtube_download.py +35 -0
  58. autogen/agentchat/contrib/captainagent/tools/math/calculate_circle_area_from_diameter.py +21 -0
  59. autogen/agentchat/contrib/captainagent/tools/math/calculate_day_of_the_week.py +18 -0
  60. autogen/agentchat/contrib/captainagent/tools/math/calculate_fraction_sum.py +28 -0
  61. autogen/agentchat/contrib/captainagent/tools/math/calculate_matrix_power.py +31 -0
  62. autogen/agentchat/contrib/captainagent/tools/math/calculate_reflected_point.py +16 -0
  63. autogen/agentchat/contrib/captainagent/tools/math/complex_numbers_product.py +25 -0
  64. autogen/agentchat/contrib/captainagent/tools/math/compute_currency_conversion.py +23 -0
  65. autogen/agentchat/contrib/captainagent/tools/math/count_distinct_permutations.py +27 -0
  66. autogen/agentchat/contrib/captainagent/tools/math/evaluate_expression.py +28 -0
  67. autogen/agentchat/contrib/captainagent/tools/math/find_continuity_point.py +34 -0
  68. autogen/agentchat/contrib/captainagent/tools/math/fraction_to_mixed_numbers.py +39 -0
  69. autogen/agentchat/contrib/captainagent/tools/math/modular_inverse_sum.py +23 -0
  70. autogen/agentchat/contrib/captainagent/tools/math/simplify_mixed_numbers.py +36 -0
  71. autogen/agentchat/contrib/captainagent/tools/math/sum_of_digit_factorials.py +15 -0
  72. autogen/agentchat/contrib/captainagent/tools/math/sum_of_primes_below.py +15 -0
  73. autogen/agentchat/contrib/captainagent/tools/requirements.txt +10 -0
  74. autogen/agentchat/contrib/captainagent/tools/tool_description.tsv +34 -0
  75. autogen/agentchat/contrib/gpt_assistant_agent.py +526 -0
  76. autogen/agentchat/contrib/graph_rag/__init__.py +9 -0
  77. autogen/agentchat/contrib/graph_rag/document.py +29 -0
  78. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +170 -0
  79. autogen/agentchat/contrib/graph_rag/falkor_graph_rag_capability.py +103 -0
  80. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +53 -0
  81. autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +63 -0
  82. autogen/agentchat/contrib/graph_rag/neo4j_graph_query_engine.py +268 -0
  83. autogen/agentchat/contrib/graph_rag/neo4j_graph_rag_capability.py +83 -0
  84. autogen/agentchat/contrib/graph_rag/neo4j_native_graph_query_engine.py +210 -0
  85. autogen/agentchat/contrib/graph_rag/neo4j_native_graph_rag_capability.py +93 -0
  86. autogen/agentchat/contrib/img_utils.py +397 -0
  87. autogen/agentchat/contrib/llamaindex_conversable_agent.py +117 -0
  88. autogen/agentchat/contrib/llava_agent.py +187 -0
  89. autogen/agentchat/contrib/math_user_proxy_agent.py +464 -0
  90. autogen/agentchat/contrib/multimodal_conversable_agent.py +125 -0
  91. autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +324 -0
  92. autogen/agentchat/contrib/rag/__init__.py +10 -0
  93. autogen/agentchat/contrib/rag/chromadb_query_engine.py +272 -0
  94. autogen/agentchat/contrib/rag/llamaindex_query_engine.py +198 -0
  95. autogen/agentchat/contrib/rag/mongodb_query_engine.py +329 -0
  96. autogen/agentchat/contrib/rag/query_engine.py +74 -0
  97. autogen/agentchat/contrib/retrieve_assistant_agent.py +56 -0
  98. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +703 -0
  99. autogen/agentchat/contrib/society_of_mind_agent.py +199 -0
  100. autogen/agentchat/contrib/swarm_agent.py +1425 -0
  101. autogen/agentchat/contrib/text_analyzer_agent.py +79 -0
  102. autogen/agentchat/contrib/vectordb/__init__.py +5 -0
  103. autogen/agentchat/contrib/vectordb/base.py +232 -0
  104. autogen/agentchat/contrib/vectordb/chromadb.py +315 -0
  105. autogen/agentchat/contrib/vectordb/couchbase.py +407 -0
  106. autogen/agentchat/contrib/vectordb/mongodb.py +550 -0
  107. autogen/agentchat/contrib/vectordb/pgvectordb.py +928 -0
  108. autogen/agentchat/contrib/vectordb/qdrant.py +320 -0
  109. autogen/agentchat/contrib/vectordb/utils.py +126 -0
  110. autogen/agentchat/contrib/web_surfer.py +303 -0
  111. autogen/agentchat/conversable_agent.py +4023 -0
  112. autogen/agentchat/group/__init__.py +64 -0
  113. autogen/agentchat/group/available_condition.py +91 -0
  114. autogen/agentchat/group/context_condition.py +77 -0
  115. autogen/agentchat/group/context_expression.py +238 -0
  116. autogen/agentchat/group/context_str.py +41 -0
  117. autogen/agentchat/group/context_variables.py +192 -0
  118. autogen/agentchat/group/group_tool_executor.py +202 -0
  119. autogen/agentchat/group/group_utils.py +591 -0
  120. autogen/agentchat/group/handoffs.py +244 -0
  121. autogen/agentchat/group/llm_condition.py +93 -0
  122. autogen/agentchat/group/multi_agent_chat.py +237 -0
  123. autogen/agentchat/group/on_condition.py +58 -0
  124. autogen/agentchat/group/on_context_condition.py +54 -0
  125. autogen/agentchat/group/patterns/__init__.py +18 -0
  126. autogen/agentchat/group/patterns/auto.py +159 -0
  127. autogen/agentchat/group/patterns/manual.py +176 -0
  128. autogen/agentchat/group/patterns/pattern.py +288 -0
  129. autogen/agentchat/group/patterns/random.py +106 -0
  130. autogen/agentchat/group/patterns/round_robin.py +117 -0
  131. autogen/agentchat/group/reply_result.py +26 -0
  132. autogen/agentchat/group/speaker_selection_result.py +41 -0
  133. autogen/agentchat/group/targets/__init__.py +4 -0
  134. autogen/agentchat/group/targets/group_chat_target.py +132 -0
  135. autogen/agentchat/group/targets/group_manager_target.py +151 -0
  136. autogen/agentchat/group/targets/transition_target.py +413 -0
  137. autogen/agentchat/group/targets/transition_utils.py +6 -0
  138. autogen/agentchat/groupchat.py +1694 -0
  139. autogen/agentchat/realtime/__init__.py +3 -0
  140. autogen/agentchat/realtime/experimental/__init__.py +20 -0
  141. autogen/agentchat/realtime/experimental/audio_adapters/__init__.py +8 -0
  142. autogen/agentchat/realtime/experimental/audio_adapters/twilio_audio_adapter.py +148 -0
  143. autogen/agentchat/realtime/experimental/audio_adapters/websocket_audio_adapter.py +139 -0
  144. autogen/agentchat/realtime/experimental/audio_observer.py +42 -0
  145. autogen/agentchat/realtime/experimental/clients/__init__.py +15 -0
  146. autogen/agentchat/realtime/experimental/clients/gemini/__init__.py +7 -0
  147. autogen/agentchat/realtime/experimental/clients/gemini/client.py +274 -0
  148. autogen/agentchat/realtime/experimental/clients/oai/__init__.py +8 -0
  149. autogen/agentchat/realtime/experimental/clients/oai/base_client.py +220 -0
  150. autogen/agentchat/realtime/experimental/clients/oai/rtc_client.py +243 -0
  151. autogen/agentchat/realtime/experimental/clients/oai/utils.py +48 -0
  152. autogen/agentchat/realtime/experimental/clients/realtime_client.py +190 -0
  153. autogen/agentchat/realtime/experimental/function_observer.py +85 -0
  154. autogen/agentchat/realtime/experimental/realtime_agent.py +158 -0
  155. autogen/agentchat/realtime/experimental/realtime_events.py +42 -0
  156. autogen/agentchat/realtime/experimental/realtime_observer.py +100 -0
  157. autogen/agentchat/realtime/experimental/realtime_swarm.py +475 -0
  158. autogen/agentchat/realtime/experimental/websockets.py +21 -0
  159. autogen/agentchat/realtime_agent/__init__.py +21 -0
  160. autogen/agentchat/user_proxy_agent.py +111 -0
  161. autogen/agentchat/utils.py +206 -0
  162. autogen/agents/__init__.py +3 -0
  163. autogen/agents/contrib/__init__.py +10 -0
  164. autogen/agents/contrib/time/__init__.py +8 -0
  165. autogen/agents/contrib/time/time_reply_agent.py +73 -0
  166. autogen/agents/contrib/time/time_tool_agent.py +51 -0
  167. autogen/agents/experimental/__init__.py +27 -0
  168. autogen/agents/experimental/deep_research/__init__.py +7 -0
  169. autogen/agents/experimental/deep_research/deep_research.py +52 -0
  170. autogen/agents/experimental/discord/__init__.py +7 -0
  171. autogen/agents/experimental/discord/discord.py +66 -0
  172. autogen/agents/experimental/document_agent/__init__.py +19 -0
  173. autogen/agents/experimental/document_agent/chroma_query_engine.py +316 -0
  174. autogen/agents/experimental/document_agent/docling_doc_ingest_agent.py +118 -0
  175. autogen/agents/experimental/document_agent/document_agent.py +461 -0
  176. autogen/agents/experimental/document_agent/document_conditions.py +50 -0
  177. autogen/agents/experimental/document_agent/document_utils.py +380 -0
  178. autogen/agents/experimental/document_agent/inmemory_query_engine.py +220 -0
  179. autogen/agents/experimental/document_agent/parser_utils.py +130 -0
  180. autogen/agents/experimental/document_agent/url_utils.py +426 -0
  181. autogen/agents/experimental/reasoning/__init__.py +7 -0
  182. autogen/agents/experimental/reasoning/reasoning_agent.py +1178 -0
  183. autogen/agents/experimental/slack/__init__.py +7 -0
  184. autogen/agents/experimental/slack/slack.py +73 -0
  185. autogen/agents/experimental/telegram/__init__.py +7 -0
  186. autogen/agents/experimental/telegram/telegram.py +77 -0
  187. autogen/agents/experimental/websurfer/__init__.py +7 -0
  188. autogen/agents/experimental/websurfer/websurfer.py +62 -0
  189. autogen/agents/experimental/wikipedia/__init__.py +7 -0
  190. autogen/agents/experimental/wikipedia/wikipedia.py +90 -0
  191. autogen/browser_utils.py +309 -0
  192. autogen/cache/__init__.py +10 -0
  193. autogen/cache/abstract_cache_base.py +75 -0
  194. autogen/cache/cache.py +203 -0
  195. autogen/cache/cache_factory.py +88 -0
  196. autogen/cache/cosmos_db_cache.py +144 -0
  197. autogen/cache/disk_cache.py +102 -0
  198. autogen/cache/in_memory_cache.py +58 -0
  199. autogen/cache/redis_cache.py +123 -0
  200. autogen/code_utils.py +596 -0
  201. autogen/coding/__init__.py +22 -0
  202. autogen/coding/base.py +119 -0
  203. autogen/coding/docker_commandline_code_executor.py +268 -0
  204. autogen/coding/factory.py +47 -0
  205. autogen/coding/func_with_reqs.py +202 -0
  206. autogen/coding/jupyter/__init__.py +23 -0
  207. autogen/coding/jupyter/base.py +36 -0
  208. autogen/coding/jupyter/docker_jupyter_server.py +167 -0
  209. autogen/coding/jupyter/embedded_ipython_code_executor.py +182 -0
  210. autogen/coding/jupyter/import_utils.py +82 -0
  211. autogen/coding/jupyter/jupyter_client.py +231 -0
  212. autogen/coding/jupyter/jupyter_code_executor.py +160 -0
  213. autogen/coding/jupyter/local_jupyter_server.py +172 -0
  214. autogen/coding/local_commandline_code_executor.py +405 -0
  215. autogen/coding/markdown_code_extractor.py +45 -0
  216. autogen/coding/utils.py +56 -0
  217. autogen/doc_utils.py +34 -0
  218. autogen/events/__init__.py +7 -0
  219. autogen/events/agent_events.py +1013 -0
  220. autogen/events/base_event.py +99 -0
  221. autogen/events/client_events.py +167 -0
  222. autogen/events/helpers.py +36 -0
  223. autogen/events/print_event.py +46 -0
  224. autogen/exception_utils.py +73 -0
  225. autogen/extensions/__init__.py +5 -0
  226. autogen/fast_depends/__init__.py +16 -0
  227. autogen/fast_depends/_compat.py +80 -0
  228. autogen/fast_depends/core/__init__.py +14 -0
  229. autogen/fast_depends/core/build.py +225 -0
  230. autogen/fast_depends/core/model.py +576 -0
  231. autogen/fast_depends/dependencies/__init__.py +15 -0
  232. autogen/fast_depends/dependencies/model.py +29 -0
  233. autogen/fast_depends/dependencies/provider.py +39 -0
  234. autogen/fast_depends/library/__init__.py +10 -0
  235. autogen/fast_depends/library/model.py +46 -0
  236. autogen/fast_depends/py.typed +6 -0
  237. autogen/fast_depends/schema.py +66 -0
  238. autogen/fast_depends/use.py +280 -0
  239. autogen/fast_depends/utils.py +187 -0
  240. autogen/formatting_utils.py +83 -0
  241. autogen/function_utils.py +13 -0
  242. autogen/graph_utils.py +178 -0
  243. autogen/import_utils.py +526 -0
  244. autogen/interop/__init__.py +22 -0
  245. autogen/interop/crewai/__init__.py +7 -0
  246. autogen/interop/crewai/crewai.py +88 -0
  247. autogen/interop/interoperability.py +71 -0
  248. autogen/interop/interoperable.py +46 -0
  249. autogen/interop/langchain/__init__.py +8 -0
  250. autogen/interop/langchain/langchain_chat_model_factory.py +155 -0
  251. autogen/interop/langchain/langchain_tool.py +82 -0
  252. autogen/interop/litellm/__init__.py +7 -0
  253. autogen/interop/litellm/litellm_config_factory.py +179 -0
  254. autogen/interop/pydantic_ai/__init__.py +7 -0
  255. autogen/interop/pydantic_ai/pydantic_ai.py +168 -0
  256. autogen/interop/registry.py +69 -0
  257. autogen/io/__init__.py +15 -0
  258. autogen/io/base.py +151 -0
  259. autogen/io/console.py +56 -0
  260. autogen/io/processors/__init__.py +12 -0
  261. autogen/io/processors/base.py +21 -0
  262. autogen/io/processors/console_event_processor.py +56 -0
  263. autogen/io/run_response.py +293 -0
  264. autogen/io/thread_io_stream.py +63 -0
  265. autogen/io/websockets.py +213 -0
  266. autogen/json_utils.py +43 -0
  267. autogen/llm_config.py +382 -0
  268. autogen/logger/__init__.py +11 -0
  269. autogen/logger/base_logger.py +128 -0
  270. autogen/logger/file_logger.py +261 -0
  271. autogen/logger/logger_factory.py +42 -0
  272. autogen/logger/logger_utils.py +57 -0
  273. autogen/logger/sqlite_logger.py +523 -0
  274. autogen/math_utils.py +339 -0
  275. autogen/mcp/__init__.py +7 -0
  276. autogen/mcp/__main__.py +78 -0
  277. autogen/mcp/mcp_client.py +208 -0
  278. autogen/mcp/mcp_proxy/__init__.py +19 -0
  279. autogen/mcp/mcp_proxy/fastapi_code_generator_helpers.py +63 -0
  280. autogen/mcp/mcp_proxy/mcp_proxy.py +581 -0
  281. autogen/mcp/mcp_proxy/operation_grouping.py +158 -0
  282. autogen/mcp/mcp_proxy/operation_renaming.py +114 -0
  283. autogen/mcp/mcp_proxy/patch_fastapi_code_generator.py +98 -0
  284. autogen/mcp/mcp_proxy/security.py +400 -0
  285. autogen/mcp/mcp_proxy/security_schema_visitor.py +37 -0
  286. autogen/messages/__init__.py +7 -0
  287. autogen/messages/agent_messages.py +948 -0
  288. autogen/messages/base_message.py +107 -0
  289. autogen/messages/client_messages.py +171 -0
  290. autogen/messages/print_message.py +49 -0
  291. autogen/oai/__init__.py +53 -0
  292. autogen/oai/anthropic.py +714 -0
  293. autogen/oai/bedrock.py +628 -0
  294. autogen/oai/cerebras.py +299 -0
  295. autogen/oai/client.py +1444 -0
  296. autogen/oai/client_utils.py +169 -0
  297. autogen/oai/cohere.py +479 -0
  298. autogen/oai/gemini.py +998 -0
  299. autogen/oai/gemini_types.py +155 -0
  300. autogen/oai/groq.py +305 -0
  301. autogen/oai/mistral.py +303 -0
  302. autogen/oai/oai_models/__init__.py +11 -0
  303. autogen/oai/oai_models/_models.py +16 -0
  304. autogen/oai/oai_models/chat_completion.py +87 -0
  305. autogen/oai/oai_models/chat_completion_audio.py +32 -0
  306. autogen/oai/oai_models/chat_completion_message.py +86 -0
  307. autogen/oai/oai_models/chat_completion_message_tool_call.py +37 -0
  308. autogen/oai/oai_models/chat_completion_token_logprob.py +63 -0
  309. autogen/oai/oai_models/completion_usage.py +60 -0
  310. autogen/oai/ollama.py +643 -0
  311. autogen/oai/openai_utils.py +881 -0
  312. autogen/oai/together.py +370 -0
  313. autogen/retrieve_utils.py +491 -0
  314. autogen/runtime_logging.py +160 -0
  315. autogen/token_count_utils.py +267 -0
  316. autogen/tools/__init__.py +20 -0
  317. autogen/tools/contrib/__init__.py +9 -0
  318. autogen/tools/contrib/time/__init__.py +7 -0
  319. autogen/tools/contrib/time/time.py +41 -0
  320. autogen/tools/dependency_injection.py +254 -0
  321. autogen/tools/experimental/__init__.py +48 -0
  322. autogen/tools/experimental/browser_use/__init__.py +7 -0
  323. autogen/tools/experimental/browser_use/browser_use.py +161 -0
  324. autogen/tools/experimental/crawl4ai/__init__.py +7 -0
  325. autogen/tools/experimental/crawl4ai/crawl4ai.py +153 -0
  326. autogen/tools/experimental/deep_research/__init__.py +7 -0
  327. autogen/tools/experimental/deep_research/deep_research.py +328 -0
  328. autogen/tools/experimental/duckduckgo/__init__.py +7 -0
  329. autogen/tools/experimental/duckduckgo/duckduckgo_search.py +109 -0
  330. autogen/tools/experimental/google/__init__.py +14 -0
  331. autogen/tools/experimental/google/authentication/__init__.py +11 -0
  332. autogen/tools/experimental/google/authentication/credentials_hosted_provider.py +43 -0
  333. autogen/tools/experimental/google/authentication/credentials_local_provider.py +91 -0
  334. autogen/tools/experimental/google/authentication/credentials_provider.py +35 -0
  335. autogen/tools/experimental/google/drive/__init__.py +9 -0
  336. autogen/tools/experimental/google/drive/drive_functions.py +124 -0
  337. autogen/tools/experimental/google/drive/toolkit.py +88 -0
  338. autogen/tools/experimental/google/model.py +17 -0
  339. autogen/tools/experimental/google/toolkit_protocol.py +19 -0
  340. autogen/tools/experimental/google_search/__init__.py +8 -0
  341. autogen/tools/experimental/google_search/google_search.py +93 -0
  342. autogen/tools/experimental/google_search/youtube_search.py +181 -0
  343. autogen/tools/experimental/messageplatform/__init__.py +17 -0
  344. autogen/tools/experimental/messageplatform/discord/__init__.py +7 -0
  345. autogen/tools/experimental/messageplatform/discord/discord.py +288 -0
  346. autogen/tools/experimental/messageplatform/slack/__init__.py +7 -0
  347. autogen/tools/experimental/messageplatform/slack/slack.py +391 -0
  348. autogen/tools/experimental/messageplatform/telegram/__init__.py +7 -0
  349. autogen/tools/experimental/messageplatform/telegram/telegram.py +275 -0
  350. autogen/tools/experimental/perplexity/__init__.py +7 -0
  351. autogen/tools/experimental/perplexity/perplexity_search.py +260 -0
  352. autogen/tools/experimental/reliable/__init__.py +10 -0
  353. autogen/tools/experimental/reliable/reliable.py +1316 -0
  354. autogen/tools/experimental/tavily/__init__.py +7 -0
  355. autogen/tools/experimental/tavily/tavily_search.py +183 -0
  356. autogen/tools/experimental/web_search_preview/__init__.py +7 -0
  357. autogen/tools/experimental/web_search_preview/web_search_preview.py +114 -0
  358. autogen/tools/experimental/wikipedia/__init__.py +7 -0
  359. autogen/tools/experimental/wikipedia/wikipedia.py +287 -0
  360. autogen/tools/function_utils.py +411 -0
  361. autogen/tools/tool.py +187 -0
  362. autogen/tools/toolkit.py +86 -0
  363. autogen/types.py +29 -0
  364. autogen/version.py +7 -0
  365. templates/client_template/main.jinja2 +69 -0
  366. templates/config_template/config.jinja2 +7 -0
  367. templates/main.jinja2 +61 -0
  368. ag2-0.9.1a1.dist-info/RECORD +0 -6
  369. ag2-0.9.1a1.dist-info/top_level.txt +0 -1
  370. {ag2-0.9.1a1.dist-info → ag2-0.9.2.dist-info/licenses}/LICENSE +0 -0
  371. {ag2-0.9.1a1.dist-info → ag2-0.9.2.dist-info/licenses}/NOTICE.md +0 -0
@@ -0,0 +1,4023 @@
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 asyncio
8
+ import copy
9
+ import functools
10
+ import inspect
11
+ import json
12
+ import logging
13
+ import re
14
+ import threading
15
+ import warnings
16
+ from collections import defaultdict
17
+ from contextlib import contextmanager
18
+ from dataclasses import dataclass
19
+ from inspect import signature
20
+ from typing import (
21
+ TYPE_CHECKING,
22
+ Any,
23
+ Callable,
24
+ Generator,
25
+ Iterable,
26
+ Literal,
27
+ Optional,
28
+ TypeVar,
29
+ Union,
30
+ )
31
+
32
+ from ..cache.cache import AbstractCache, Cache
33
+ from ..code_utils import (
34
+ PYTHON_VARIANTS,
35
+ UNKNOWN,
36
+ check_can_use_docker_or_throw,
37
+ content_str,
38
+ decide_use_docker,
39
+ execute_code,
40
+ extract_code,
41
+ infer_lang,
42
+ )
43
+ from ..coding.base import CodeExecutor
44
+ from ..coding.factory import CodeExecutorFactory
45
+ from ..doc_utils import export_module
46
+ from ..events.agent_events import (
47
+ ClearConversableAgentHistoryEvent,
48
+ ClearConversableAgentHistoryWarningEvent,
49
+ ConversableAgentUsageSummaryEvent,
50
+ ConversableAgentUsageSummaryNoCostIncurredEvent,
51
+ ErrorEvent,
52
+ ExecuteCodeBlockEvent,
53
+ ExecuteFunctionEvent,
54
+ ExecutedFunctionEvent,
55
+ GenerateCodeExecutionReplyEvent,
56
+ PostCarryoverProcessingEvent,
57
+ RunCompletionEvent,
58
+ TerminationAndHumanReplyNoInputEvent,
59
+ TerminationEvent,
60
+ UsingAutoReplyEvent,
61
+ create_received_event_model,
62
+ )
63
+ from ..exception_utils import InvalidCarryOverTypeError, SenderRequiredError
64
+ from ..io.base import IOStream
65
+ from ..io.run_response import AsyncRunResponse, AsyncRunResponseProtocol, RunResponse, RunResponseProtocol
66
+ from ..io.thread_io_stream import AsyncThreadIOStream, ThreadIOStream
67
+ from ..llm_config import LLMConfig
68
+ from ..oai.client import ModelClient, OpenAIWrapper
69
+ from ..runtime_logging import log_event, log_function_use, log_new_agent, logging_enabled
70
+ from ..tools import ChatContext, Tool, load_basemodels_if_needed, serialize_to_str
71
+ from .agent import Agent, LLMAgent
72
+ from .chat import (
73
+ ChatResult,
74
+ _post_process_carryover_item,
75
+ _validate_recipients,
76
+ a_initiate_chats,
77
+ initiate_chats,
78
+ )
79
+ from .group.context_variables import ContextVariables
80
+ from .group.handoffs import Handoffs
81
+ from .utils import consolidate_chat_info, gather_usage_summary
82
+
83
+ if TYPE_CHECKING:
84
+ from .group.on_condition import OnCondition
85
+ from .group.on_context_condition import OnContextCondition
86
+
87
+ __all__ = ("ConversableAgent",)
88
+
89
+ logger = logging.getLogger(__name__)
90
+
91
+ F = TypeVar("F", bound=Callable[..., Any])
92
+
93
+
94
+ @dataclass
95
+ @export_module("autogen")
96
+ class UpdateSystemMessage:
97
+ """Update the agent's system message before they reply
98
+
99
+ Args:
100
+ content_updater: The format string or function to update the agent's system message. Can be a format string or a Callable.
101
+ If a string, it will be used as a template and substitute the context variables.
102
+ If a Callable, it should have the signature:
103
+ def my_content_updater(agent: ConversableAgent, messages: List[Dict[str, Any]]) -> str
104
+ """
105
+
106
+ content_updater: Union[Callable, str]
107
+
108
+ def __post_init__(self):
109
+ if isinstance(self.content_updater, str):
110
+ # find all {var} in the string
111
+ vars = re.findall(r"\{(\w+)\}", self.content_updater)
112
+ if len(vars) == 0:
113
+ warnings.warn("Update function string contains no variables. This is probably unintended.")
114
+
115
+ elif isinstance(self.content_updater, Callable):
116
+ sig = signature(self.content_updater)
117
+ if len(sig.parameters) != 2:
118
+ raise ValueError(
119
+ "The update function must accept two parameters of type ConversableAgent and List[Dict[str, Any]], respectively"
120
+ )
121
+ if sig.return_annotation != str:
122
+ raise ValueError("The update function must return a string")
123
+ else:
124
+ raise ValueError("The update function must be either a string or a callable")
125
+
126
+
127
+ @export_module("autogen")
128
+ class ConversableAgent(LLMAgent):
129
+ """(In preview) A class for generic conversable agents which can be configured as assistant or user proxy.
130
+
131
+ After receiving each message, the agent will send a reply to the sender unless the msg is a termination msg.
132
+ For example, AssistantAgent and UserProxyAgent are subclasses of this class,
133
+ configured with different default settings.
134
+
135
+ To modify auto reply, override `generate_reply` method.
136
+ To disable/enable human response in every turn, set `human_input_mode` to "NEVER" or "ALWAYS".
137
+ To modify the way to get human input, override `get_human_input` method.
138
+ To modify the way to execute code blocks, single code block, or function call, override `execute_code_blocks`,
139
+ `run_code`, and `execute_function` methods respectively.
140
+ """
141
+
142
+ DEFAULT_CONFIG = False # False or dict, the default config for llm inference
143
+ MAX_CONSECUTIVE_AUTO_REPLY = 100 # maximum number of consecutive auto replies (subject to future change)
144
+
145
+ DEFAULT_SUMMARY_PROMPT = "Summarize the takeaway from the conversation. Do not add any introductory phrases."
146
+ DEFAULT_SUMMARY_METHOD = "last_msg"
147
+ llm_config: Union[dict[str, Any], Literal[False]]
148
+
149
+ def __init__(
150
+ self,
151
+ name: str,
152
+ system_message: Optional[Union[str, list]] = "You are a helpful AI Assistant.",
153
+ is_termination_msg: Optional[Callable[[dict[str, Any]], bool]] = None,
154
+ max_consecutive_auto_reply: Optional[int] = None,
155
+ human_input_mode: Literal["ALWAYS", "NEVER", "TERMINATE"] = "TERMINATE",
156
+ function_map: Optional[dict[str, Callable[..., Any]]] = None,
157
+ code_execution_config: Union[dict[str, Any], Literal[False]] = False,
158
+ llm_config: Optional[Union[LLMConfig, dict[str, Any], Literal[False]]] = None,
159
+ default_auto_reply: Union[str, dict[str, Any]] = "",
160
+ description: Optional[str] = None,
161
+ chat_messages: Optional[dict[Agent, list[dict[str, Any]]]] = None,
162
+ silent: Optional[bool] = None,
163
+ context_variables: Optional["ContextVariables"] = None,
164
+ functions: Union[list[Callable[..., Any]], Callable[..., Any]] = None,
165
+ update_agent_state_before_reply: Optional[
166
+ Union[list[Union[Callable, UpdateSystemMessage]], Callable, UpdateSystemMessage]
167
+ ] = None,
168
+ handoffs: Optional[Handoffs] = None,
169
+ ):
170
+ """
171
+ Args:
172
+ name (str): name of the agent.
173
+ system_message (str or list): system message for the ChatCompletion inference.
174
+ is_termination_msg (function): a function that takes a message in the form of a dictionary
175
+ and returns a boolean value indicating if this received message is a termination message.
176
+ The dict can contain the following keys: "content", "role", "name", "function_call".
177
+ max_consecutive_auto_reply (int): the maximum number of consecutive auto replies.
178
+ default to None (no limit provided, class attribute MAX_CONSECUTIVE_AUTO_REPLY will be used as the limit in this case).
179
+ When set to 0, no auto reply will be generated.
180
+ human_input_mode (str): whether to ask for human inputs every time a message is received.
181
+ Possible values are "ALWAYS", "TERMINATE", "NEVER".
182
+ (1) When "ALWAYS", the agent prompts for human input every time a message is received.
183
+ Under this mode, the conversation stops when the human input is "exit",
184
+ or when is_termination_msg is True and there is no human input.
185
+ (2) When "TERMINATE", the agent only prompts for human input only when a termination message is received or
186
+ the number of auto reply reaches the max_consecutive_auto_reply.
187
+ (3) When "NEVER", the agent will never prompt for human input. Under this mode, the conversation stops
188
+ when the number of auto reply reaches the max_consecutive_auto_reply or when is_termination_msg is True.
189
+ function_map (dict[str, callable]): Mapping function names (passed to openai) to callable functions, also used for tool calls.
190
+ code_execution_config (dict or False): config for the code execution.
191
+ To disable code execution, set to False. Otherwise, set to a dictionary with the following keys:
192
+ - work_dir (Optional, str): The working directory for the code execution.
193
+ If None, a default working directory will be used.
194
+ The default working directory is the "extensions" directory under
195
+ "path_to_autogen".
196
+ - use_docker (Optional, list, str or bool): The docker image to use for code execution.
197
+ Default is True, which means the code will be executed in a docker container. A default list of images will be used.
198
+ If a list or a str of image name(s) is provided, the code will be executed in a docker container
199
+ with the first image successfully pulled.
200
+ If False, the code will be executed in the current environment.
201
+ We strongly recommend using docker for code execution.
202
+ - timeout (Optional, int): The maximum execution time in seconds.
203
+ - last_n_messages (Experimental, int or str): The number of messages to look back for code execution.
204
+ If set to 'auto', it will scan backwards through all messages arriving since the agent last spoke, which is typically the last time execution was attempted. (Default: auto)
205
+ llm_config (LLMConfig or dict or False or None): llm inference configuration.
206
+ Please refer to [OpenAIWrapper.create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create)
207
+ for available options.
208
+ When using OpenAI or Azure OpenAI endpoints, please specify a non-empty 'model' either in `llm_config` or in each config of 'config_list' in `llm_config`.
209
+ To disable llm-based auto reply, set to False.
210
+ When set to None, will use self.DEFAULT_CONFIG, which defaults to False.
211
+ default_auto_reply (str or dict): default auto reply when no code execution or llm-based reply is generated.
212
+ description (str): a short description of the agent. This description is used by other agents
213
+ (e.g. the GroupChatManager) to decide when to call upon this agent. (Default: system_message)
214
+ chat_messages (dict or None): the previous chat messages that this agent had in the past with other agents.
215
+ Can be used to give the agent a memory by providing the chat history. This will allow the agent to
216
+ resume previous had conversations. Defaults to an empty chat history.
217
+ silent (bool or None): (Experimental) whether to print the message sent. If None, will use the value of
218
+ silent in each function.
219
+ context_variables (ContextVariables or None): Context variables that provide a persistent context for the agent.
220
+ Note: This will be a reference to a shared context for multi-agent chats.
221
+ Behaves like a dictionary with keys and values (akin to dict[str, Any]).
222
+ functions (List[Callable[..., Any]]): A list of functions to register with the agent, these will be wrapped up as tools and registered for LLM (not execution).
223
+ update_agent_state_before_reply (List[Callable[..., Any]]): A list of functions, including UpdateSystemMessage's, called to update the agent before it replies.
224
+ handoffs (Handoffs): Handoffs object containing all handoff transition conditions.
225
+ """
226
+ self.handoffs = handoffs if handoffs is not None else Handoffs()
227
+
228
+ # we change code_execution_config below and we have to make sure we don't change the input
229
+ # in case of UserProxyAgent, without this we could even change the default value {}
230
+ code_execution_config = (
231
+ code_execution_config.copy() if hasattr(code_execution_config, "copy") else code_execution_config
232
+ )
233
+
234
+ # a dictionary of conversations, default value is list
235
+ if chat_messages is None:
236
+ self._oai_messages = defaultdict(list)
237
+ else:
238
+ self._oai_messages = chat_messages
239
+
240
+ self._oai_system_message = [{"content": system_message, "role": "system"}]
241
+ self._description = description if description is not None else system_message
242
+ self._is_termination_msg = (
243
+ is_termination_msg
244
+ if is_termination_msg is not None
245
+ else (lambda x: content_str(x.get("content")) == "TERMINATE")
246
+ )
247
+ self.silent = silent
248
+ self.run_executor: Optional[ConversableAgent] = None
249
+
250
+ # Take a copy to avoid modifying the given dict
251
+ if isinstance(llm_config, dict):
252
+ try:
253
+ llm_config = copy.deepcopy(llm_config)
254
+ except TypeError as e:
255
+ raise TypeError(
256
+ "Please implement __deepcopy__ method for each value class in llm_config to support deepcopy."
257
+ " Refer to the docs for more details: https://docs.ag2.ai/docs/user-guide/advanced-concepts/llm-configuration-deep-dive/#adding-http-client-in-llm_config-for-proxy"
258
+ ) from e
259
+
260
+ self.llm_config = self._validate_llm_config(llm_config)
261
+ self.client = self._create_client(self.llm_config)
262
+ self._validate_name(name)
263
+ self._name = name
264
+
265
+ if logging_enabled():
266
+ log_new_agent(self, locals())
267
+
268
+ # Initialize standalone client cache object.
269
+ self.client_cache = None
270
+
271
+ # To track UI tools
272
+ self._ui_tools: list[Tool] = []
273
+
274
+ self.human_input_mode = human_input_mode
275
+ self._max_consecutive_auto_reply = (
276
+ max_consecutive_auto_reply if max_consecutive_auto_reply is not None else self.MAX_CONSECUTIVE_AUTO_REPLY
277
+ )
278
+ self._consecutive_auto_reply_counter = defaultdict(int)
279
+ self._max_consecutive_auto_reply_dict = defaultdict(self.max_consecutive_auto_reply)
280
+ self._function_map = (
281
+ {}
282
+ if function_map is None
283
+ else {name: callable for name, callable in function_map.items() if self._assert_valid_name(name)}
284
+ )
285
+ self._default_auto_reply = default_auto_reply
286
+ self._reply_func_list = []
287
+ self._human_input = []
288
+ self.reply_at_receive = defaultdict(bool)
289
+ self.register_reply([Agent, None], ConversableAgent.generate_oai_reply)
290
+ self.register_reply([Agent, None], ConversableAgent.a_generate_oai_reply, ignore_async_in_sync_chat=True)
291
+
292
+ self.context_variables = context_variables if context_variables is not None else ContextVariables()
293
+
294
+ self._tools: list[Tool] = []
295
+
296
+ # Register functions to the agent
297
+ if isinstance(functions, list):
298
+ if not all(isinstance(func, Callable) for func in functions):
299
+ raise TypeError("All elements in the functions list must be callable")
300
+ self._add_functions(functions)
301
+ elif isinstance(functions, Callable):
302
+ self._add_single_function(functions)
303
+ elif functions is not None:
304
+ raise TypeError("Functions must be a callable or a list of callables")
305
+
306
+ # Setting up code execution.
307
+ # Do not register code execution reply if code execution is disabled.
308
+ if code_execution_config is not False:
309
+ # If code_execution_config is None, set it to an empty dict.
310
+ if code_execution_config is None:
311
+ warnings.warn(
312
+ "Using None to signal a default code_execution_config is deprecated. "
313
+ "Use {} to use default or False to disable code execution.",
314
+ stacklevel=2,
315
+ )
316
+ code_execution_config = {}
317
+ if not isinstance(code_execution_config, dict):
318
+ raise ValueError("code_execution_config must be a dict or False.")
319
+
320
+ # We have got a valid code_execution_config.
321
+ self._code_execution_config: Union[dict[str, Any], Literal[False]] = code_execution_config
322
+
323
+ if self._code_execution_config.get("executor") is not None:
324
+ if "use_docker" in self._code_execution_config:
325
+ raise ValueError(
326
+ "'use_docker' in code_execution_config is not valid when 'executor' is set. Use the appropriate arg in the chosen executor instead."
327
+ )
328
+
329
+ if "work_dir" in self._code_execution_config:
330
+ raise ValueError(
331
+ "'work_dir' in code_execution_config is not valid when 'executor' is set. Use the appropriate arg in the chosen executor instead."
332
+ )
333
+
334
+ if "timeout" in self._code_execution_config:
335
+ raise ValueError(
336
+ "'timeout' in code_execution_config is not valid when 'executor' is set. Use the appropriate arg in the chosen executor instead."
337
+ )
338
+
339
+ # Use the new code executor.
340
+ self._code_executor = CodeExecutorFactory.create(self._code_execution_config)
341
+ self.register_reply([Agent, None], ConversableAgent._generate_code_execution_reply_using_executor)
342
+ else:
343
+ # Legacy code execution using code_utils.
344
+ use_docker = self._code_execution_config.get("use_docker", None)
345
+ use_docker = decide_use_docker(use_docker)
346
+ check_can_use_docker_or_throw(use_docker)
347
+ self._code_execution_config["use_docker"] = use_docker
348
+ self.register_reply([Agent, None], ConversableAgent.generate_code_execution_reply)
349
+ else:
350
+ # Code execution is disabled.
351
+ self._code_execution_config = False
352
+
353
+ self.register_reply([Agent, None], ConversableAgent.generate_tool_calls_reply)
354
+ self.register_reply([Agent, None], ConversableAgent.a_generate_tool_calls_reply, ignore_async_in_sync_chat=True)
355
+ self.register_reply([Agent, None], ConversableAgent.generate_function_call_reply)
356
+ self.register_reply(
357
+ [Agent, None], ConversableAgent.a_generate_function_call_reply, ignore_async_in_sync_chat=True
358
+ )
359
+ self.register_reply([Agent, None], ConversableAgent.check_termination_and_human_reply)
360
+ self.register_reply(
361
+ [Agent, None], ConversableAgent.a_check_termination_and_human_reply, ignore_async_in_sync_chat=True
362
+ )
363
+
364
+ # Registered hooks are kept in lists, indexed by hookable method, to be called in their order of registration.
365
+ # New hookable methods should be added to this list as required to support new agent capabilities.
366
+ self.hook_lists: dict[str, list[Callable[..., Any]]] = {
367
+ "process_last_received_message": [],
368
+ "process_all_messages_before_reply": [],
369
+ "process_message_before_send": [],
370
+ "update_agent_state": [],
371
+ }
372
+
373
+ # Associate agent update state hooks
374
+ self._register_update_agent_state_before_reply(update_agent_state_before_reply)
375
+
376
+ def _validate_name(self, name: str) -> None:
377
+ if not self.llm_config:
378
+ return
379
+
380
+ if any([
381
+ entry for entry in self.llm_config.config_list if entry.api_type == "openai" and re.search(r"\s", name)
382
+ ]):
383
+ raise ValueError(f"The name of the agent cannot contain any whitespace. The name provided is: '{name}'")
384
+
385
+ def _get_display_name(self):
386
+ """Get the string representation of the agent.
387
+
388
+ If you would like to change the standard string representation for an
389
+ instance of ConversableAgent, you can point it to another function.
390
+ In this example a function called _group_agent_str that returns a string:
391
+ agent._get_display_name = MethodType(_group_agent_str, agent)
392
+ """
393
+ return self.name
394
+
395
+ def __str__(self):
396
+ return self._get_display_name()
397
+
398
+ def _add_functions(self, func_list: list[Callable[..., Any]]):
399
+ """Add (Register) a list of functions to the agent
400
+
401
+ Args:
402
+ func_list (list[Callable[..., Any]]): A list of functions to register with the agent."""
403
+ for func in func_list:
404
+ self._add_single_function(func)
405
+
406
+ def _add_single_function(self, func: Callable, name: Optional[str] = None, description: Optional[str] = ""):
407
+ """Add a single function to the agent
408
+
409
+ Args:
410
+ func (Callable): The function to register.
411
+ name (str): The name of the function. If not provided, the function's name will be used.
412
+ description (str): The description of the function, used by the LLM. If not provided, the function's docstring will be used.
413
+ """
414
+ if name:
415
+ func._name = name
416
+ elif not hasattr(func, "_name"):
417
+ func._name = func.__name__
418
+
419
+ if hasattr(func, "_description") and func._description and not description:
420
+ # If the function already has a description, use it
421
+ description = func._description
422
+ else:
423
+ if description:
424
+ func._description = description
425
+ else:
426
+ # Use function's docstring, strip whitespace, fall back to empty string
427
+ description = (func.__doc__ or "").strip()
428
+ func._description = description
429
+
430
+ # Register the function
431
+ self.register_for_llm(name=name, description=description, silent_override=True)(func)
432
+
433
+ def _register_update_agent_state_before_reply(
434
+ self, functions: Optional[Union[list[Callable[..., Any]], Callable[..., Any]]]
435
+ ):
436
+ """
437
+ Register functions that will be called when the agent is selected and before it speaks.
438
+ You can add your own validation or precondition functions here.
439
+
440
+ Args:
441
+ functions (List[Callable[[], None]]): A list of functions to be registered. Each function
442
+ is called when the agent is selected and before it speaks.
443
+ """
444
+ if functions is None:
445
+ return
446
+ if not isinstance(functions, list) and type(functions) not in [UpdateSystemMessage, Callable[..., Any]]:
447
+ raise ValueError("functions must be a list of callables")
448
+
449
+ if not isinstance(functions, list):
450
+ functions = [functions]
451
+
452
+ for func in functions:
453
+ if isinstance(func, UpdateSystemMessage):
454
+ # Wrapper function that allows this to be used in the update_agent_state hook
455
+ # Its primary purpose, however, is just to update the agent's system message
456
+ # Outer function to create a closure with the update function
457
+ def create_wrapper(update_func: UpdateSystemMessage):
458
+ def update_system_message_wrapper(
459
+ agent: ConversableAgent, messages: list[dict[str, Any]]
460
+ ) -> list[dict[str, Any]]:
461
+ if isinstance(update_func.content_updater, str):
462
+ # Templates like "My context variable passport is {passport}" will
463
+ # use the context_variables for substitution
464
+ sys_message = OpenAIWrapper.instantiate(
465
+ template=update_func.content_updater,
466
+ context=agent.context_variables.to_dict(),
467
+ allow_format_str_template=True,
468
+ )
469
+ else:
470
+ sys_message = update_func.content_updater(agent, messages)
471
+
472
+ agent.update_system_message(sys_message)
473
+ return messages
474
+
475
+ return update_system_message_wrapper
476
+
477
+ self.register_hook(hookable_method="update_agent_state", hook=create_wrapper(func))
478
+
479
+ else:
480
+ self.register_hook(hookable_method="update_agent_state", hook=func)
481
+
482
+ @classmethod
483
+ def _validate_llm_config(
484
+ cls, llm_config: Optional[Union[LLMConfig, dict[str, Any], Literal[False]]]
485
+ ) -> Union[LLMConfig, Literal[False]]:
486
+ # if not(llm_config in (None, False) or isinstance(llm_config, [dict, LLMConfig])):
487
+ # raise ValueError(
488
+ # "llm_config must be a dict or False or None."
489
+ # )
490
+
491
+ if llm_config is None:
492
+ llm_config = LLMConfig.get_current_llm_config()
493
+ if llm_config is None:
494
+ llm_config = cls.DEFAULT_CONFIG
495
+ elif isinstance(llm_config, dict):
496
+ llm_config = LLMConfig(**llm_config)
497
+ elif isinstance(llm_config, LLMConfig):
498
+ llm_config = llm_config.copy()
499
+ elif llm_config is False:
500
+ pass
501
+ else:
502
+ raise ValueError("llm_config must be a LLMConfig, dict or False or None.")
503
+
504
+ return llm_config
505
+
506
+ @classmethod
507
+ def _create_client(cls, llm_config: Union[LLMConfig, Literal[False]]) -> Optional[OpenAIWrapper]:
508
+ return None if llm_config is False else OpenAIWrapper(**llm_config)
509
+
510
+ @staticmethod
511
+ def _is_silent(agent: Agent, silent: Optional[bool] = False) -> bool:
512
+ return agent.silent if agent.silent is not None else silent
513
+
514
+ @property
515
+ def name(self) -> str:
516
+ """Get the name of the agent."""
517
+ return self._name
518
+
519
+ @property
520
+ def description(self) -> str:
521
+ """Get the description of the agent."""
522
+ return self._description
523
+
524
+ @description.setter
525
+ def description(self, description: str):
526
+ """Set the description of the agent."""
527
+ self._description = description
528
+
529
+ @property
530
+ def code_executor(self) -> Optional[CodeExecutor]:
531
+ """The code executor used by this agent. Returns None if code execution is disabled."""
532
+ if not hasattr(self, "_code_executor"):
533
+ return None
534
+ return self._code_executor
535
+
536
+ def register_reply(
537
+ self,
538
+ trigger: Union[type[Agent], str, Agent, Callable[[Agent], bool], list],
539
+ reply_func: Callable,
540
+ position: int = 0,
541
+ config: Optional[Any] = None,
542
+ reset_config: Optional[Callable[..., Any]] = None,
543
+ *,
544
+ ignore_async_in_sync_chat: bool = False,
545
+ remove_other_reply_funcs: bool = False,
546
+ ):
547
+ """Register a reply function.
548
+
549
+ The reply function will be called when the trigger matches the sender.
550
+ The function registered later will be checked earlier by default.
551
+ To change the order, set the position to a positive integer.
552
+
553
+ Both sync and async reply functions can be registered. The sync reply function will be triggered
554
+ from both sync and async chats. However, an async reply function will only be triggered from async
555
+ chats (initiated with `ConversableAgent.a_initiate_chat`). If an `async` reply function is registered
556
+ and a chat is initialized with a sync function, `ignore_async_in_sync_chat` determines the behaviour as follows:
557
+ if `ignore_async_in_sync_chat` is set to `False` (default value), an exception will be raised, and
558
+ if `ignore_async_in_sync_chat` is set to `True`, the reply function will be ignored.
559
+
560
+ Args:
561
+ trigger (Agent class, str, Agent instance, callable, or list): the trigger.
562
+ If a class is provided, the reply function will be called when the sender is an instance of the class.
563
+ If a string is provided, the reply function will be called when the sender's name matches the string.
564
+ If an agent instance is provided, the reply function will be called when the sender is the agent instance.
565
+ If a callable is provided, the reply function will be called when the callable returns True.
566
+ If a list is provided, the reply function will be called when any of the triggers in the list is activated.
567
+ If None is provided, the reply function will be called only when the sender is None.
568
+ Note: Be sure to register `None` as a trigger if you would like to trigger an auto-reply function with non-empty messages and `sender=None`.
569
+ reply_func (Callable): the reply function.
570
+ The function takes a recipient agent, a list of messages, a sender agent and a config as input and returns a reply message.
571
+
572
+ ```python
573
+ def reply_func(
574
+ recipient: ConversableAgent,
575
+ messages: Optional[List[Dict]] = None,
576
+ sender: Optional[Agent] = None,
577
+ config: Optional[Any] = None,
578
+ ) -> Tuple[bool, Union[str, Dict, None]]:
579
+ ```
580
+ position (int): the position of the reply function in the reply function list.
581
+ The function registered later will be checked earlier by default.
582
+ To change the order, set the position to a positive integer.
583
+ config (Any): the config to be passed to the reply function.
584
+ When an agent is reset, the config will be reset to the original value.
585
+ reset_config (Callable): the function to reset the config.
586
+ The function returns None. Signature: ```def reset_config(config: Any)```
587
+ ignore_async_in_sync_chat (bool): whether to ignore the async reply function in sync chats. If `False`, an exception
588
+ will be raised if an async reply function is registered and a chat is initialized with a sync
589
+ function.
590
+ remove_other_reply_funcs (bool): whether to remove other reply functions when registering this reply function.
591
+ """
592
+ if not isinstance(trigger, (type, str, Agent, Callable, list)):
593
+ raise ValueError("trigger must be a class, a string, an agent, a callable or a list.")
594
+ if remove_other_reply_funcs:
595
+ self._reply_func_list.clear()
596
+ self._reply_func_list.insert(
597
+ position,
598
+ {
599
+ "trigger": trigger,
600
+ "reply_func": reply_func,
601
+ "config": copy.copy(config),
602
+ "init_config": config,
603
+ "reset_config": reset_config,
604
+ "ignore_async_in_sync_chat": ignore_async_in_sync_chat and inspect.iscoroutinefunction(reply_func),
605
+ },
606
+ )
607
+
608
+ def replace_reply_func(self, old_reply_func: Callable, new_reply_func: Callable):
609
+ """Replace a registered reply function with a new one.
610
+
611
+ Args:
612
+ old_reply_func (Callable): the old reply function to be replaced.
613
+ new_reply_func (Callable): the new reply function to replace the old one.
614
+ """
615
+ for f in self._reply_func_list:
616
+ if f["reply_func"] == old_reply_func:
617
+ f["reply_func"] = new_reply_func
618
+
619
+ @staticmethod
620
+ def _get_chats_to_run(
621
+ chat_queue: list[dict[str, Any]],
622
+ recipient: Agent,
623
+ messages: Optional[list[dict[str, Any]]],
624
+ sender: Agent,
625
+ config: Any,
626
+ ) -> list[dict[str, Any]]:
627
+ """A simple chat reply function.
628
+ This function initiate one or a sequence of chats between the "recipient" and the agents in the
629
+ chat_queue.
630
+
631
+ It extracts and returns a summary from the nested chat based on the "summary_method" in each chat in chat_queue.
632
+
633
+ Returns:
634
+ Tuple[bool, str]: A tuple where the first element indicates the completion of the chat, and the second element contains the summary of the last chat if any chats were initiated.
635
+ """
636
+ last_msg = messages[-1].get("content")
637
+ chat_to_run = []
638
+ for i, c in enumerate(chat_queue):
639
+ current_c = c.copy()
640
+ if current_c.get("sender") is None:
641
+ current_c["sender"] = recipient
642
+ message = current_c.get("message")
643
+ # If message is not provided in chat_queue, we by default use the last message from the original chat history as the first message in this nested chat (for the first chat in the chat queue).
644
+ # NOTE: This setting is prone to change.
645
+ if message is None and i == 0:
646
+ message = last_msg
647
+ if callable(message):
648
+ message = message(recipient, messages, sender, config)
649
+ # We only run chat that has a valid message. NOTE: This is prone to change depending on applications.
650
+ if message:
651
+ current_c["message"] = message
652
+ chat_to_run.append(current_c)
653
+ return chat_to_run
654
+
655
+ @staticmethod
656
+ def _process_nested_chat_carryover(
657
+ chat: dict[str, Any],
658
+ recipient: Agent,
659
+ messages: list[dict[str, Any]],
660
+ sender: Agent,
661
+ config: Any,
662
+ trim_n_messages: int = 0,
663
+ ) -> None:
664
+ """Process carryover messages for a nested chat (typically for the first chat of a group chat)
665
+
666
+ The carryover_config key is a dictionary containing:
667
+ "summary_method": The method to use to summarise the messages, can be "all", "last_msg", "reflection_with_llm" or a Callable
668
+ "summary_args": Optional arguments for the summary method
669
+
670
+ Supported carryover 'summary_methods' are:
671
+ "all" - all messages will be incorporated
672
+ "last_msg" - the last message will be incorporated
673
+ "reflection_with_llm" - an llm will summarise all the messages and the summary will be incorporated as a single message
674
+ Callable - a callable with the signature: my_method(agent: ConversableAgent, messages: List[Dict[str, Any]]) -> str
675
+
676
+ Args:
677
+ chat: The chat dictionary containing the carryover configuration
678
+ recipient: The recipient agent
679
+ messages: The messages from the parent chat
680
+ sender: The sender agent
681
+ config: The LLM configuration
682
+ trim_n_messages: The number of latest messages to trim from the messages list
683
+ """
684
+
685
+ def concat_carryover(chat_message: str, carryover_message: Union[str, list[dict[str, Any]]]) -> str:
686
+ """Concatenate the carryover message to the chat message."""
687
+ prefix = f"{chat_message}\n" if chat_message else ""
688
+
689
+ if isinstance(carryover_message, str):
690
+ content = carryover_message
691
+ elif isinstance(carryover_message, list):
692
+ content = "\n".join(
693
+ msg["content"] for msg in carryover_message if "content" in msg and msg["content"] is not None
694
+ )
695
+ else:
696
+ raise ValueError("Carryover message must be a string or a list of dictionaries")
697
+
698
+ return f"{prefix}Context:\n{content}"
699
+
700
+ carryover_config = chat["carryover_config"]
701
+
702
+ if "summary_method" not in carryover_config:
703
+ raise ValueError("Carryover configuration must contain a 'summary_method' key")
704
+
705
+ carryover_summary_method = carryover_config["summary_method"]
706
+ carryover_summary_args = carryover_config.get("summary_args") or {}
707
+
708
+ chat_message = ""
709
+ message = chat.get("message")
710
+
711
+ # If the message is a callable, run it and get the result
712
+ if message:
713
+ chat_message = message(recipient, messages, sender, config) if callable(message) else message
714
+
715
+ # deep copy and trim the latest messages
716
+ content_messages = copy.deepcopy(messages)
717
+ content_messages = content_messages[:-trim_n_messages]
718
+
719
+ if carryover_summary_method == "all":
720
+ # Put a string concatenated value of all parent messages into the first message
721
+ # (e.g. message = <first nested chat message>\nContext: \n<chat message 1>\n<chat message 2>\n...)
722
+ carry_over_message = concat_carryover(chat_message, content_messages)
723
+
724
+ elif carryover_summary_method == "last_msg":
725
+ # (e.g. message = <first nested chat message>\nContext: \n<last chat message>)
726
+ carry_over_message = concat_carryover(chat_message, content_messages[-1]["content"])
727
+
728
+ elif carryover_summary_method == "reflection_with_llm":
729
+ # (e.g. message = <first nested chat message>\nContext: \n<llm summary>)
730
+
731
+ # Add the messages to the nested chat agent for reflection (we'll clear after reflection)
732
+ chat["recipient"]._oai_messages[sender] = content_messages
733
+
734
+ carry_over_message_llm = ConversableAgent._reflection_with_llm_as_summary(
735
+ sender=sender,
736
+ recipient=chat["recipient"], # Chat recipient LLM config will be used for the reflection
737
+ summary_args=carryover_summary_args,
738
+ )
739
+
740
+ recipient._oai_messages[sender] = []
741
+
742
+ carry_over_message = concat_carryover(chat_message, carry_over_message_llm)
743
+
744
+ elif isinstance(carryover_summary_method, Callable):
745
+ # (e.g. message = <first nested chat message>\nContext: \n<function's return string>)
746
+ carry_over_message_result = carryover_summary_method(recipient, content_messages, carryover_summary_args)
747
+
748
+ carry_over_message = concat_carryover(chat_message, carry_over_message_result)
749
+
750
+ chat["message"] = carry_over_message
751
+
752
+ @staticmethod
753
+ def _process_chat_queue_carryover(
754
+ chat_queue: list[dict[str, Any]],
755
+ recipient: Agent,
756
+ messages: Union[str, Callable[..., Any]],
757
+ sender: Agent,
758
+ config: Any,
759
+ trim_messages: int = 2,
760
+ ) -> tuple[bool, Optional[str]]:
761
+ """Process carryover configuration for the first chat in the queue.
762
+
763
+ Args:
764
+ chat_queue: List of chat configurations
765
+ recipient: Receiving agent
766
+ messages: Chat messages
767
+ sender: Sending agent
768
+ config: LLM configuration
769
+ trim_messages: Number of messages to trim for nested chat carryover (default 2 for nested chat in group chats)
770
+
771
+ Returns:
772
+ Tuple containing:
773
+ - restore_flag: Whether the original message needs to be restored
774
+ - original_message: The original message to restore (if any)
775
+ """
776
+ restore_chat_queue_message = False
777
+ original_chat_queue_message = None
778
+
779
+ # Carryover configuration allowed on the first chat in the queue only, trim the last two messages specifically for group chat nested chat carryover as these are the messages for the transition to the nested chat agent
780
+ if len(chat_queue) > 0 and "carryover_config" in chat_queue[0]:
781
+ if "message" in chat_queue[0]:
782
+ # As we're updating the message in the nested chat queue, we need to restore it after finishing this nested chat.
783
+ restore_chat_queue_message = True
784
+ original_chat_queue_message = chat_queue[0]["message"]
785
+
786
+ # TODO Check the trimming required if not a group chat, it may not be 2 because other chats don't have the group transition messages. We may need to add as a carryover_config parameter.
787
+ ConversableAgent._process_nested_chat_carryover(
788
+ chat=chat_queue[0],
789
+ recipient=recipient,
790
+ messages=messages,
791
+ sender=sender,
792
+ config=config,
793
+ trim_n_messages=trim_messages,
794
+ )
795
+
796
+ return restore_chat_queue_message, original_chat_queue_message
797
+
798
+ @staticmethod
799
+ def _summary_from_nested_chats(
800
+ chat_queue: list[dict[str, Any]],
801
+ recipient: Agent,
802
+ messages: Optional[list[dict[str, Any]]],
803
+ sender: Agent,
804
+ config: Any,
805
+ ) -> tuple[bool, Union[str, None]]:
806
+ """A simple chat reply function.
807
+ This function initiate one or a sequence of chats between the "recipient" and the agents in the
808
+ chat_queue.
809
+
810
+ It extracts and returns a summary from the nested chat based on the "summary_method" in each chat in chat_queue.
811
+
812
+ The first chat in the queue can contain a 'carryover_config' which is a dictionary that denotes how to carryover messages from the parent chat into the first chat of the nested chats). Only applies to the first chat.
813
+ e.g.: carryover_summarize_chat_config = {"summary_method": "reflection_with_llm", "summary_args": None}
814
+ summary_method can be "last_msg", "all", "reflection_with_llm", Callable
815
+ The Callable signature: my_method(agent: ConversableAgent, messages: List[Dict[str, Any]]) -> str
816
+ The summary will be concatenated to the message of the first chat in the queue.
817
+
818
+ Returns:
819
+ Tuple[bool, str]: A tuple where the first element indicates the completion of the chat, and the second element contains the summary of the last chat if any chats were initiated.
820
+ """
821
+ # Process carryover configuration
822
+ restore_chat_queue_message, original_chat_queue_message = ConversableAgent._process_chat_queue_carryover(
823
+ chat_queue, recipient, messages, sender, config
824
+ )
825
+
826
+ chat_to_run = ConversableAgent._get_chats_to_run(chat_queue, recipient, messages, sender, config)
827
+ if not chat_to_run:
828
+ return True, None
829
+ res = initiate_chats(chat_to_run)
830
+
831
+ # We need to restore the chat queue message if it has been modified so that it will be the original message for subsequent uses
832
+ if restore_chat_queue_message:
833
+ chat_queue[0]["message"] = original_chat_queue_message
834
+
835
+ return True, res[-1].summary
836
+
837
+ @staticmethod
838
+ async def _a_summary_from_nested_chats(
839
+ chat_queue: list[dict[str, Any]],
840
+ recipient: Agent,
841
+ messages: Optional[list[dict[str, Any]]],
842
+ sender: Agent,
843
+ config: Any,
844
+ ) -> tuple[bool, Union[str, None]]:
845
+ """A simple chat reply function.
846
+ This function initiate one or a sequence of chats between the "recipient" and the agents in the
847
+ chat_queue.
848
+
849
+ It extracts and returns a summary from the nested chat based on the "summary_method" in each chat in chat_queue.
850
+
851
+ The first chat in the queue can contain a 'carryover_config' which is a dictionary that denotes how to carryover messages from the parent chat into the first chat of the nested chats). Only applies to the first chat.
852
+ e.g.: carryover_summarize_chat_config = {"summary_method": "reflection_with_llm", "summary_args": None}
853
+ summary_method can be "last_msg", "all", "reflection_with_llm", Callable
854
+ The Callable signature: my_method(agent: ConversableAgent, messages: List[Dict[str, Any]]) -> str
855
+ The summary will be concatenated to the message of the first chat in the queue.
856
+
857
+ Returns:
858
+ Tuple[bool, str]: A tuple where the first element indicates the completion of the chat, and the second element contains the summary of the last chat if any chats were initiated.
859
+ """
860
+ # Process carryover configuration
861
+ restore_chat_queue_message, original_chat_queue_message = ConversableAgent._process_chat_queue_carryover(
862
+ chat_queue, recipient, messages, sender, config
863
+ )
864
+
865
+ chat_to_run = ConversableAgent._get_chats_to_run(chat_queue, recipient, messages, sender, config)
866
+ if not chat_to_run:
867
+ return True, None
868
+ res = await a_initiate_chats(chat_to_run)
869
+ index_of_last_chat = chat_to_run[-1]["chat_id"]
870
+
871
+ # We need to restore the chat queue message if it has been modified so that it will be the original message for subsequent uses
872
+ if restore_chat_queue_message:
873
+ chat_queue[0]["message"] = original_chat_queue_message
874
+
875
+ return True, res[index_of_last_chat].summary
876
+
877
+ def register_nested_chats(
878
+ self,
879
+ chat_queue: list[dict[str, Any]],
880
+ trigger: Union[type[Agent], str, Agent, Callable[[Agent], bool], list],
881
+ reply_func_from_nested_chats: Union[str, Callable[..., Any]] = "summary_from_nested_chats",
882
+ position: int = 2,
883
+ use_async: Union[bool, None] = None,
884
+ **kwargs: Any,
885
+ ) -> None:
886
+ """Register a nested chat reply function.
887
+
888
+ Args:
889
+ chat_queue (list): a list of chat objects to be initiated. If use_async is used, then all messages in chat_queue must have a chat-id associated with them.
890
+ trigger (Agent class, str, Agent instance, callable, or list): refer to `register_reply` for details.
891
+ reply_func_from_nested_chats (Callable, str): the reply function for the nested chat.
892
+ The function takes a chat_queue for nested chat, recipient agent, a list of messages, a sender agent and a config as input and returns a reply message.
893
+ Default to "summary_from_nested_chats", which corresponds to a built-in reply function that get summary from the nested chat_queue.
894
+ ```python
895
+ def reply_func_from_nested_chats(
896
+ chat_queue: List[Dict],
897
+ recipient: ConversableAgent,
898
+ messages: Optional[List[Dict]] = None,
899
+ sender: Optional[Agent] = None,
900
+ config: Optional[Any] = None,
901
+ ) -> Tuple[bool, Union[str, Dict, None]]:
902
+ ```
903
+ position (int): Ref to `register_reply` for details. Default to 2. It means we first check the termination and human reply, then check the registered nested chat reply.
904
+ use_async: Uses a_initiate_chats internally to start nested chats. If the original chat is initiated with a_initiate_chats, you may set this to true so nested chats do not run in sync.
905
+ kwargs: Ref to `register_reply` for details.
906
+ """
907
+ if use_async:
908
+ for chat in chat_queue:
909
+ if chat.get("chat_id") is None:
910
+ raise ValueError("chat_id is required for async nested chats")
911
+
912
+ if use_async:
913
+ if reply_func_from_nested_chats == "summary_from_nested_chats":
914
+ reply_func_from_nested_chats = self._a_summary_from_nested_chats
915
+ if not callable(reply_func_from_nested_chats) or not inspect.iscoroutinefunction(
916
+ reply_func_from_nested_chats
917
+ ):
918
+ raise ValueError("reply_func_from_nested_chats must be a callable and a coroutine")
919
+
920
+ async def wrapped_reply_func(recipient, messages=None, sender=None, config=None):
921
+ return await reply_func_from_nested_chats(chat_queue, recipient, messages, sender, config)
922
+
923
+ else:
924
+ if reply_func_from_nested_chats == "summary_from_nested_chats":
925
+ reply_func_from_nested_chats = self._summary_from_nested_chats
926
+ if not callable(reply_func_from_nested_chats):
927
+ raise ValueError("reply_func_from_nested_chats must be a callable")
928
+
929
+ def wrapped_reply_func(recipient, messages=None, sender=None, config=None):
930
+ return reply_func_from_nested_chats(chat_queue, recipient, messages, sender, config)
931
+
932
+ functools.update_wrapper(wrapped_reply_func, reply_func_from_nested_chats)
933
+
934
+ self.register_reply(
935
+ trigger,
936
+ wrapped_reply_func,
937
+ position,
938
+ kwargs.get("config"),
939
+ kwargs.get("reset_config"),
940
+ ignore_async_in_sync_chat=(
941
+ not use_async if use_async is not None else kwargs.get("ignore_async_in_sync_chat")
942
+ ),
943
+ )
944
+
945
+ @property
946
+ def system_message(self) -> str:
947
+ """Return the system message."""
948
+ return self._oai_system_message[0]["content"]
949
+
950
+ def update_system_message(self, system_message: str) -> None:
951
+ """Update the system message.
952
+
953
+ Args:
954
+ system_message (str): system message for the ChatCompletion inference.
955
+ """
956
+ self._oai_system_message[0]["content"] = system_message
957
+
958
+ def update_max_consecutive_auto_reply(self, value: int, sender: Optional[Agent] = None):
959
+ """Update the maximum number of consecutive auto replies.
960
+
961
+ Args:
962
+ value (int): the maximum number of consecutive auto replies.
963
+ sender (Agent): when the sender is provided, only update the max_consecutive_auto_reply for that sender.
964
+ """
965
+ if sender is None:
966
+ self._max_consecutive_auto_reply = value
967
+ for k in self._max_consecutive_auto_reply_dict:
968
+ self._max_consecutive_auto_reply_dict[k] = value
969
+ else:
970
+ self._max_consecutive_auto_reply_dict[sender] = value
971
+
972
+ def max_consecutive_auto_reply(self, sender: Optional[Agent] = None) -> int:
973
+ """The maximum number of consecutive auto replies."""
974
+ return self._max_consecutive_auto_reply if sender is None else self._max_consecutive_auto_reply_dict[sender]
975
+
976
+ @property
977
+ def chat_messages(self) -> dict[Agent, list[dict[str, Any]]]:
978
+ """A dictionary of conversations from agent to list of messages."""
979
+ return self._oai_messages
980
+
981
+ def chat_messages_for_summary(self, agent: Agent) -> list[dict[str, Any]]:
982
+ """A list of messages as a conversation to summarize."""
983
+ return self._oai_messages[agent]
984
+
985
+ def last_message(self, agent: Optional[Agent] = None) -> Optional[dict[str, Any]]:
986
+ """The last message exchanged with the agent.
987
+
988
+ Args:
989
+ agent (Agent): The agent in the conversation.
990
+ If None and more than one agent's conversations are found, an error will be raised.
991
+ If None and only one conversation is found, the last message of the only conversation will be returned.
992
+
993
+ Returns:
994
+ The last message exchanged with the agent.
995
+ """
996
+ if agent is None:
997
+ n_conversations = len(self._oai_messages)
998
+ if n_conversations == 0:
999
+ return None
1000
+ if n_conversations == 1:
1001
+ for conversation in self._oai_messages.values():
1002
+ return conversation[-1]
1003
+ raise ValueError("More than one conversation is found. Please specify the sender to get the last message.")
1004
+ if agent not in self._oai_messages:
1005
+ raise KeyError(
1006
+ f"The agent '{agent.name}' is not present in any conversation. No history available for this agent."
1007
+ )
1008
+ return self._oai_messages[agent][-1]
1009
+
1010
+ @property
1011
+ def use_docker(self) -> Union[bool, str, None]:
1012
+ """Bool value of whether to use docker to execute the code,
1013
+ or str value of the docker image name to use, or None when code execution is disabled.
1014
+ """
1015
+ return None if self._code_execution_config is False else self._code_execution_config.get("use_docker")
1016
+
1017
+ @staticmethod
1018
+ def _message_to_dict(message: Union[dict[str, Any], str]) -> dict:
1019
+ """Convert a message to a dictionary.
1020
+
1021
+ The message can be a string or a dictionary. The string will be put in the "content" field of the new dictionary.
1022
+ """
1023
+ if isinstance(message, str):
1024
+ return {"content": message}
1025
+ elif isinstance(message, dict):
1026
+ return message
1027
+ else:
1028
+ return dict(message)
1029
+
1030
+ @staticmethod
1031
+ def _normalize_name(name):
1032
+ """LLMs sometimes ask functions while ignoring their own format requirements, this function should be used to replace invalid characters with "_".
1033
+
1034
+ Prefer _assert_valid_name for validating user configuration or input
1035
+ """
1036
+ return re.sub(r"[^a-zA-Z0-9_-]", "_", name)[:64]
1037
+
1038
+ @staticmethod
1039
+ def _assert_valid_name(name):
1040
+ """Ensure that configured names are valid, raises ValueError if not.
1041
+
1042
+ For munging LLM responses use _normalize_name to ensure LLM specified names don't break the API.
1043
+ """
1044
+ if not re.match(r"^[a-zA-Z0-9_-]+$", name):
1045
+ raise ValueError(f"Invalid name: {name}. Only letters, numbers, '_' and '-' are allowed.")
1046
+ if len(name) > 64:
1047
+ raise ValueError(f"Invalid name: {name}. Name must be less than 64 characters.")
1048
+ return name
1049
+
1050
+ def _append_oai_message(
1051
+ self, message: Union[dict[str, Any], str], role, conversation_id: Agent, is_sending: bool
1052
+ ) -> bool:
1053
+ """Append a message to the ChatCompletion conversation.
1054
+
1055
+ If the message received is a string, it will be put in the "content" field of the new dictionary.
1056
+ If the message received is a dictionary but does not have any of the three fields "content", "function_call", or "tool_calls",
1057
+ this message is not a valid ChatCompletion message.
1058
+ If only "function_call" or "tool_calls" is provided, "content" will be set to None if not provided, and the role of the message will be forced "assistant".
1059
+
1060
+ Args:
1061
+ message (dict or str): message to be appended to the ChatCompletion conversation.
1062
+ role (str): role of the message, can be "assistant" or "function".
1063
+ conversation_id (Agent): id of the conversation, should be the recipient or sender.
1064
+ is_sending (bool): If the agent (aka self) is sending to the conversation_id agent, otherwise receiving.
1065
+
1066
+ Returns:
1067
+ bool: whether the message is appended to the ChatCompletion conversation.
1068
+ """
1069
+ message = self._message_to_dict(message)
1070
+ # create oai message to be appended to the oai conversation that can be passed to oai directly.
1071
+ oai_message = {
1072
+ k: message[k]
1073
+ for k in ("content", "function_call", "tool_calls", "tool_responses", "tool_call_id", "name", "context")
1074
+ if k in message and message[k] is not None
1075
+ }
1076
+ if "content" not in oai_message:
1077
+ if "function_call" in oai_message or "tool_calls" in oai_message:
1078
+ oai_message["content"] = None # if only function_call is provided, content will be set to None.
1079
+ else:
1080
+ return False
1081
+
1082
+ if message.get("role") in ["function", "tool"]:
1083
+ oai_message["role"] = message.get("role")
1084
+ if "tool_responses" in oai_message:
1085
+ for tool_response in oai_message["tool_responses"]:
1086
+ tool_response["content"] = str(tool_response["content"])
1087
+ elif "override_role" in message:
1088
+ # If we have a direction to override the role then set the
1089
+ # role accordingly. Used to customise the role for the
1090
+ # select speaker prompt.
1091
+ oai_message["role"] = message.get("override_role")
1092
+ else:
1093
+ oai_message["role"] = role
1094
+
1095
+ if oai_message.get("function_call", False) or oai_message.get("tool_calls", False):
1096
+ oai_message["role"] = "assistant" # only messages with role 'assistant' can have a function call.
1097
+ elif "name" not in oai_message:
1098
+ # If we don't have a name field, append it
1099
+ if is_sending:
1100
+ oai_message["name"] = self.name
1101
+ else:
1102
+ oai_message["name"] = conversation_id.name
1103
+
1104
+ self._oai_messages[conversation_id].append(oai_message)
1105
+
1106
+ return True
1107
+
1108
+ def _process_message_before_send(
1109
+ self, message: Union[dict[str, Any], str], recipient: Agent, silent: bool
1110
+ ) -> Union[dict[str, Any], str]:
1111
+ """Process the message before sending it to the recipient."""
1112
+ hook_list = self.hook_lists["process_message_before_send"]
1113
+ for hook in hook_list:
1114
+ message = hook(
1115
+ sender=self, message=message, recipient=recipient, silent=ConversableAgent._is_silent(self, silent)
1116
+ )
1117
+ return message
1118
+
1119
+ def send(
1120
+ self,
1121
+ message: Union[dict[str, Any], str],
1122
+ recipient: Agent,
1123
+ request_reply: Optional[bool] = None,
1124
+ silent: Optional[bool] = False,
1125
+ ):
1126
+ """Send a message to another agent.
1127
+
1128
+ Args:
1129
+ message (dict or str): message to be sent.
1130
+ The message could contain the following fields:
1131
+ - content (str or List): Required, the content of the message. (Can be None)
1132
+ - function_call (str): the name of the function to be called.
1133
+ - name (str): the name of the function to be called.
1134
+ - role (str): the role of the message, any role that is not "function"
1135
+ will be modified to "assistant".
1136
+ - context (dict): the context of the message, which will be passed to
1137
+ [OpenAIWrapper.create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create).
1138
+ For example, one agent can send a message A as:
1139
+ ```python
1140
+ {
1141
+ "content": lambda context: context["use_tool_msg"],
1142
+ "context": {"use_tool_msg": "Use tool X if they are relevant."},
1143
+ }
1144
+ ```
1145
+ Next time, one agent can send a message B with a different "use_tool_msg".
1146
+ Then the content of message A will be refreshed to the new "use_tool_msg".
1147
+ So effectively, this provides a way for an agent to send a "link" and modify
1148
+ the content of the "link" later.
1149
+ recipient (Agent): the recipient of the message.
1150
+ request_reply (bool or None): whether to request a reply from the recipient.
1151
+ silent (bool or None): (Experimental) whether to print the message sent.
1152
+
1153
+ Raises:
1154
+ ValueError: if the message can't be converted into a valid ChatCompletion message.
1155
+ """
1156
+ message = self._process_message_before_send(message, recipient, ConversableAgent._is_silent(self, silent))
1157
+ # When the agent composes and sends the message, the role of the message is "assistant"
1158
+ # unless it's "function".
1159
+ valid = self._append_oai_message(message, "assistant", recipient, is_sending=True)
1160
+ if valid:
1161
+ recipient.receive(message, self, request_reply, silent)
1162
+ else:
1163
+ raise ValueError(
1164
+ "Message can't be converted into a valid ChatCompletion message. Either content or function_call must be provided."
1165
+ )
1166
+
1167
+ async def a_send(
1168
+ self,
1169
+ message: Union[dict[str, Any], str],
1170
+ recipient: Agent,
1171
+ request_reply: Optional[bool] = None,
1172
+ silent: Optional[bool] = False,
1173
+ ):
1174
+ """(async) Send a message to another agent.
1175
+
1176
+ Args:
1177
+ message (dict or str): message to be sent.
1178
+ The message could contain the following fields:
1179
+ - content (str or List): Required, the content of the message. (Can be None)
1180
+ - function_call (str): the name of the function to be called.
1181
+ - name (str): the name of the function to be called.
1182
+ - role (str): the role of the message, any role that is not "function"
1183
+ will be modified to "assistant".
1184
+ - context (dict): the context of the message, which will be passed to
1185
+ [OpenAIWrapper.create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create).
1186
+ For example, one agent can send a message A as:
1187
+ ```python
1188
+ {
1189
+ "content": lambda context: context["use_tool_msg"],
1190
+ "context": {"use_tool_msg": "Use tool X if they are relevant."},
1191
+ }
1192
+ ```
1193
+ Next time, one agent can send a message B with a different "use_tool_msg".
1194
+ Then the content of message A will be refreshed to the new "use_tool_msg".
1195
+ So effectively, this provides a way for an agent to send a "link" and modify
1196
+ the content of the "link" later.
1197
+ recipient (Agent): the recipient of the message.
1198
+ request_reply (bool or None): whether to request a reply from the recipient.
1199
+ silent (bool or None): (Experimental) whether to print the message sent.
1200
+
1201
+ Raises:
1202
+ ValueError: if the message can't be converted into a valid ChatCompletion message.
1203
+ """
1204
+ message = self._process_message_before_send(message, recipient, ConversableAgent._is_silent(self, silent))
1205
+ # When the agent composes and sends the message, the role of the message is "assistant"
1206
+ # unless it's "function".
1207
+ valid = self._append_oai_message(message, "assistant", recipient, is_sending=True)
1208
+ if valid:
1209
+ await recipient.a_receive(message, self, request_reply, silent)
1210
+ else:
1211
+ raise ValueError(
1212
+ "Message can't be converted into a valid ChatCompletion message. Either content or function_call must be provided."
1213
+ )
1214
+
1215
+ def _print_received_message(self, message: Union[dict[str, Any], str], sender: Agent, skip_head: bool = False):
1216
+ message = self._message_to_dict(message)
1217
+ message_model = create_received_event_model(event=message, sender=sender, recipient=self)
1218
+ iostream = IOStream.get_default()
1219
+ # message_model.print(iostream.print)
1220
+ iostream.send(message_model)
1221
+
1222
+ def _process_received_message(self, message: Union[dict[str, Any], str], sender: Agent, silent: bool):
1223
+ # When the agent receives a message, the role of the message is "user". (If 'role' exists and is 'function', it will remain unchanged.)
1224
+ valid = self._append_oai_message(message, "user", sender, is_sending=False)
1225
+ if logging_enabled():
1226
+ log_event(self, "received_message", message=message, sender=sender.name, valid=valid)
1227
+
1228
+ if not valid:
1229
+ raise ValueError(
1230
+ "Received message can't be converted into a valid ChatCompletion message. Either content or function_call must be provided."
1231
+ )
1232
+
1233
+ if not ConversableAgent._is_silent(sender, silent):
1234
+ self._print_received_message(message, sender)
1235
+
1236
+ def receive(
1237
+ self,
1238
+ message: Union[dict[str, Any], str],
1239
+ sender: Agent,
1240
+ request_reply: Optional[bool] = None,
1241
+ silent: Optional[bool] = False,
1242
+ ):
1243
+ """Receive a message from another agent.
1244
+
1245
+ Once a message is received, this function sends a reply to the sender or stop.
1246
+ The reply can be generated automatically or entered manually by a human.
1247
+
1248
+ Args:
1249
+ message (dict or str): message from the sender. If the type is dict, it may contain the following reserved fields (either content or function_call need to be provided).
1250
+ 1. "content": content of the message, can be None.
1251
+ 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls")
1252
+ 3. "tool_calls": a list of dictionaries containing the function name and arguments.
1253
+ 4. "role": role of the message, can be "assistant", "user", "function", "tool".
1254
+ This field is only needed to distinguish between "function" or "assistant"/"user".
1255
+ 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name.
1256
+ 6. "context" (dict): the context of the message, which will be passed to
1257
+ [OpenAIWrapper.create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create).
1258
+ sender: sender of an Agent instance.
1259
+ request_reply (bool or None): whether a reply is requested from the sender.
1260
+ If None, the value is determined by `self.reply_at_receive[sender]`.
1261
+ silent (bool or None): (Experimental) whether to print the message received.
1262
+
1263
+ Raises:
1264
+ ValueError: if the message can't be converted into a valid ChatCompletion message.
1265
+ """
1266
+ self._process_received_message(message, sender, silent)
1267
+ if request_reply is False or (request_reply is None and self.reply_at_receive[sender] is False):
1268
+ return
1269
+ reply = self.generate_reply(messages=self.chat_messages[sender], sender=sender)
1270
+ if reply is not None:
1271
+ self.send(reply, sender, silent=silent)
1272
+
1273
+ async def a_receive(
1274
+ self,
1275
+ message: Union[dict[str, Any], str],
1276
+ sender: Agent,
1277
+ request_reply: Optional[bool] = None,
1278
+ silent: Optional[bool] = False,
1279
+ ):
1280
+ """(async) Receive a message from another agent.
1281
+
1282
+ Once a message is received, this function sends a reply to the sender or stop.
1283
+ The reply can be generated automatically or entered manually by a human.
1284
+
1285
+ Args:
1286
+ message (dict or str): message from the sender. If the type is dict, it may contain the following reserved fields (either content or function_call need to be provided).
1287
+ 1. "content": content of the message, can be None.
1288
+ 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls")
1289
+ 3. "tool_calls": a list of dictionaries containing the function name and arguments.
1290
+ 4. "role": role of the message, can be "assistant", "user", "function".
1291
+ This field is only needed to distinguish between "function" or "assistant"/"user".
1292
+ 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name.
1293
+ 6. "context" (dict): the context of the message, which will be passed to
1294
+ [OpenAIWrapper.create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create).
1295
+ sender: sender of an Agent instance.
1296
+ request_reply (bool or None): whether a reply is requested from the sender.
1297
+ If None, the value is determined by `self.reply_at_receive[sender]`.
1298
+ silent (bool or None): (Experimental) whether to print the message received.
1299
+
1300
+ Raises:
1301
+ ValueError: if the message can't be converted into a valid ChatCompletion message.
1302
+ """
1303
+ self._process_received_message(message, sender, silent)
1304
+ if request_reply is False or (request_reply is None and self.reply_at_receive[sender] is False):
1305
+ return
1306
+ reply = await self.a_generate_reply(messages=self.chat_messages[sender], sender=sender)
1307
+ if reply is not None:
1308
+ await self.a_send(reply, sender, silent=silent)
1309
+
1310
+ def _prepare_chat(
1311
+ self,
1312
+ recipient: "ConversableAgent",
1313
+ clear_history: bool,
1314
+ prepare_recipient: bool = True,
1315
+ reply_at_receive: bool = True,
1316
+ ) -> None:
1317
+ self.reset_consecutive_auto_reply_counter(recipient)
1318
+ self.reply_at_receive[recipient] = reply_at_receive
1319
+ if clear_history:
1320
+ self.clear_history(recipient)
1321
+ self._human_input = []
1322
+ if prepare_recipient:
1323
+ recipient._prepare_chat(self, clear_history, False, reply_at_receive)
1324
+
1325
+ def _raise_exception_on_async_reply_functions(self) -> None:
1326
+ """Raise an exception if any async reply functions are registered.
1327
+
1328
+ Raises:
1329
+ RuntimeError: if any async reply functions are registered.
1330
+ """
1331
+ reply_functions = {
1332
+ f["reply_func"] for f in self._reply_func_list if not f.get("ignore_async_in_sync_chat", False)
1333
+ }
1334
+
1335
+ async_reply_functions = [f for f in reply_functions if inspect.iscoroutinefunction(f)]
1336
+ if async_reply_functions:
1337
+ msg = (
1338
+ "Async reply functions can only be used with ConversableAgent.a_initiate_chat(). The following async reply functions are found: "
1339
+ + ", ".join([f.__name__ for f in async_reply_functions])
1340
+ )
1341
+
1342
+ raise RuntimeError(msg)
1343
+
1344
+ def initiate_chat(
1345
+ self,
1346
+ recipient: "ConversableAgent",
1347
+ clear_history: bool = True,
1348
+ silent: Optional[bool] = False,
1349
+ cache: Optional[AbstractCache] = None,
1350
+ max_turns: Optional[int] = None,
1351
+ summary_method: Optional[Union[str, Callable[..., Any]]] = DEFAULT_SUMMARY_METHOD,
1352
+ summary_args: Optional[dict[str, Any]] = {},
1353
+ message: Optional[Union[dict[str, Any], str, Callable[..., Any]]] = None,
1354
+ **kwargs: Any,
1355
+ ) -> ChatResult:
1356
+ """Initiate a chat with the recipient agent.
1357
+
1358
+ Reset the consecutive auto reply counter.
1359
+ If `clear_history` is True, the chat history with the recipient agent will be cleared.
1360
+
1361
+
1362
+ Args:
1363
+ recipient: the recipient agent.
1364
+ clear_history (bool): whether to clear the chat history with the agent. Default is True.
1365
+ silent (bool or None): (Experimental) whether to print the messages for this conversation. Default is False.
1366
+ cache (AbstractCache or None): the cache client to be used for this conversation. Default is None.
1367
+ max_turns (int or None): the maximum number of turns for the chat between the two agents. One turn means one conversation round trip. Note that this is different from
1368
+ `max_consecutive_auto_reply` which is the maximum number of consecutive auto replies; and it is also different from `max_rounds` in GroupChat which is the maximum number of rounds in a group chat session.
1369
+ If max_turns is set to None, the chat will continue until a termination condition is met. Default is None.
1370
+ summary_method (str or callable): a method to get a summary from the chat. Default is DEFAULT_SUMMARY_METHOD, i.e., "last_msg".
1371
+ Supported strings are "last_msg" and "reflection_with_llm":
1372
+ - when set to "last_msg", it returns the last message of the dialog as the summary.
1373
+ - when set to "reflection_with_llm", it returns a summary extracted using an llm client.
1374
+ `llm_config` must be set in either the recipient or sender.
1375
+
1376
+ A callable summary_method should take the recipient and sender agent in a chat as input and return a string of summary. E.g.,
1377
+
1378
+ ```python
1379
+ def my_summary_method(
1380
+ sender: ConversableAgent,
1381
+ recipient: ConversableAgent,
1382
+ summary_args: dict,
1383
+ ):
1384
+ return recipient.last_message(sender)["content"]
1385
+ ```
1386
+ summary_args (dict): a dictionary of arguments to be passed to the summary_method.
1387
+ One example key is "summary_prompt", and value is a string of text used to prompt a LLM-based agent (the sender or recipient agent) to reflect
1388
+ on the conversation and extract a summary when summary_method is "reflection_with_llm".
1389
+ The default summary_prompt is DEFAULT_SUMMARY_PROMPT, i.e., "Summarize takeaway from the conversation. Do not add any introductory phrases. If the intended request is NOT properly addressed, please point it out."
1390
+ Another available key is "summary_role", which is the role of the message sent to the agent in charge of summarizing. Default is "system".
1391
+ message (str, dict or Callable): the initial message to be sent to the recipient. Needs to be provided. Otherwise, input() will be called to get the initial message.
1392
+ - If a string or a dict is provided, it will be used as the initial message. `generate_init_message` is called to generate the initial message for the agent based on this string and the context.
1393
+ If dict, it may contain the following reserved fields (either content or tool_calls need to be provided).
1394
+
1395
+ 1. "content": content of the message, can be None.
1396
+ 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls")
1397
+ 3. "tool_calls": a list of dictionaries containing the function name and arguments.
1398
+ 4. "role": role of the message, can be "assistant", "user", "function".
1399
+ This field is only needed to distinguish between "function" or "assistant"/"user".
1400
+ 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name.
1401
+ 6. "context" (dict): the context of the message, which will be passed to
1402
+ `OpenAIWrapper.create`.
1403
+
1404
+ - If a callable is provided, it will be called to get the initial message in the form of a string or a dict.
1405
+ If the returned type is dict, it may contain the reserved fields mentioned above.
1406
+
1407
+ Example of a callable message (returning a string):
1408
+
1409
+ ```python
1410
+ def my_message(
1411
+ sender: ConversableAgent, recipient: ConversableAgent, context: dict
1412
+ ) -> Union[str, Dict]:
1413
+ carryover = context.get("carryover", "")
1414
+ if isinstance(message, list):
1415
+ carryover = carryover[-1]
1416
+ final_msg = "Write a blogpost." + "\\nContext: \\n" + carryover
1417
+ return final_msg
1418
+ ```
1419
+
1420
+ Example of a callable message (returning a dict):
1421
+
1422
+ ```python
1423
+ def my_message(
1424
+ sender: ConversableAgent, recipient: ConversableAgent, context: dict
1425
+ ) -> Union[str, Dict]:
1426
+ final_msg = {}
1427
+ carryover = context.get("carryover", "")
1428
+ if isinstance(message, list):
1429
+ carryover = carryover[-1]
1430
+ final_msg["content"] = "Write a blogpost." + "\\nContext: \\n" + carryover
1431
+ final_msg["context"] = {"prefix": "Today I feel"}
1432
+ return final_msg
1433
+ ```
1434
+ **kwargs: any additional information. It has the following reserved fields:
1435
+ - "carryover": a string or a list of string to specify the carryover information to be passed to this chat.
1436
+ If provided, we will combine this carryover (by attaching a "context: " string and the carryover content after the message content) with the "message" content when generating the initial chat
1437
+ message in `generate_init_message`.
1438
+ - "verbose": a boolean to specify whether to print the message and carryover in a chat. Default is False.
1439
+
1440
+ Raises:
1441
+ RuntimeError: if any async reply functions are registered and not ignored in sync chat.
1442
+
1443
+ Returns:
1444
+ ChatResult: an ChatResult object.
1445
+ """
1446
+ iostream = IOStream.get_default()
1447
+
1448
+ cache = Cache.get_current_cache(cache)
1449
+ _chat_info = locals().copy()
1450
+ _chat_info["sender"] = self
1451
+ consolidate_chat_info(_chat_info, uniform_sender=self)
1452
+ for agent in [self, recipient]:
1453
+ agent._raise_exception_on_async_reply_functions()
1454
+ agent.previous_cache = agent.client_cache
1455
+ agent.client_cache = cache
1456
+ if isinstance(max_turns, int):
1457
+ self._prepare_chat(recipient, clear_history, reply_at_receive=False)
1458
+ for i in range(max_turns):
1459
+ # check recipient max consecutive auto reply limit
1460
+ if self._consecutive_auto_reply_counter[recipient] >= recipient._max_consecutive_auto_reply:
1461
+ break
1462
+ if i == 0:
1463
+ if isinstance(message, Callable):
1464
+ msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)
1465
+ else:
1466
+ msg2send = self.generate_init_message(message, **kwargs)
1467
+ else:
1468
+ msg2send = self.generate_reply(messages=self.chat_messages[recipient], sender=recipient)
1469
+ if msg2send is None:
1470
+ break
1471
+ self.send(msg2send, recipient, request_reply=True, silent=silent)
1472
+
1473
+ else: # No breaks in the for loop, so we have reached max turns
1474
+ iostream.send(TerminationEvent(termination_reason=f"Maximum turns ({max_turns}) reached"))
1475
+ else:
1476
+ self._prepare_chat(recipient, clear_history)
1477
+ if isinstance(message, Callable):
1478
+ msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)
1479
+ else:
1480
+ msg2send = self.generate_init_message(message, **kwargs)
1481
+ self.send(msg2send, recipient, silent=silent)
1482
+ summary = self._summarize_chat(
1483
+ summary_method,
1484
+ summary_args,
1485
+ recipient,
1486
+ cache=cache,
1487
+ )
1488
+ for agent in [self, recipient]:
1489
+ agent.client_cache = agent.previous_cache
1490
+ agent.previous_cache = None
1491
+ chat_result = ChatResult(
1492
+ chat_history=self.chat_messages[recipient],
1493
+ summary=summary,
1494
+ cost=gather_usage_summary([self, recipient]),
1495
+ human_input=self._human_input,
1496
+ )
1497
+ return chat_result
1498
+
1499
+ def run(
1500
+ self,
1501
+ recipient: Optional["ConversableAgent"] = None,
1502
+ clear_history: bool = True,
1503
+ silent: Optional[bool] = False,
1504
+ cache: Optional[AbstractCache] = None,
1505
+ max_turns: Optional[int] = None,
1506
+ summary_method: Optional[Union[str, Callable[..., Any]]] = DEFAULT_SUMMARY_METHOD,
1507
+ summary_args: Optional[dict[str, Any]] = {},
1508
+ message: Optional[Union[dict[str, Any], str, Callable[..., Any]]] = None,
1509
+ executor_kwargs: Optional[dict[str, Any]] = None,
1510
+ tools: Optional[Union[Tool, Iterable[Tool]]] = None,
1511
+ user_input: Optional[bool] = False,
1512
+ msg_to: Optional[str] = "agent",
1513
+ **kwargs: Any,
1514
+ ) -> RunResponseProtocol:
1515
+ iostream = ThreadIOStream()
1516
+ agents = [self, recipient] if recipient else [self]
1517
+ response = RunResponse(iostream, agents=agents)
1518
+
1519
+ if recipient is None:
1520
+
1521
+ def initiate_chat(
1522
+ self=self,
1523
+ iostream: ThreadIOStream = iostream,
1524
+ response: RunResponse = response,
1525
+ ) -> None:
1526
+ with (
1527
+ IOStream.set_default(iostream),
1528
+ self._create_or_get_executor(
1529
+ executor_kwargs=executor_kwargs,
1530
+ tools=tools,
1531
+ agent_name="user",
1532
+ agent_human_input_mode="ALWAYS" if user_input else "NEVER",
1533
+ ) as executor,
1534
+ ):
1535
+ try:
1536
+ if msg_to == "agent":
1537
+ chat_result = executor.initiate_chat(
1538
+ self,
1539
+ message=message,
1540
+ clear_history=clear_history,
1541
+ max_turns=max_turns,
1542
+ summary_method=summary_method,
1543
+ )
1544
+ else:
1545
+ chat_result = self.initiate_chat(
1546
+ executor,
1547
+ message=message,
1548
+ clear_history=clear_history,
1549
+ max_turns=max_turns,
1550
+ summary_method=summary_method,
1551
+ )
1552
+
1553
+ IOStream.get_default().send(
1554
+ RunCompletionEvent(
1555
+ history=chat_result.chat_history,
1556
+ summary=chat_result.summary,
1557
+ cost=chat_result.cost,
1558
+ last_speaker=self.name,
1559
+ )
1560
+ )
1561
+ except Exception as e:
1562
+ response.iostream.send(ErrorEvent(error=e))
1563
+
1564
+ else:
1565
+
1566
+ def initiate_chat(
1567
+ self=self,
1568
+ iostream: ThreadIOStream = iostream,
1569
+ response: RunResponse = response,
1570
+ ) -> None:
1571
+ with IOStream.set_default(iostream): # type: ignore[arg-type]
1572
+ try:
1573
+ chat_result = self.initiate_chat(
1574
+ recipient,
1575
+ clear_history=clear_history,
1576
+ silent=silent,
1577
+ cache=cache,
1578
+ max_turns=max_turns,
1579
+ summary_method=summary_method,
1580
+ summary_args=summary_args,
1581
+ message=message,
1582
+ **kwargs,
1583
+ )
1584
+
1585
+ response._summary = chat_result.summary
1586
+ response._messages = chat_result.chat_history
1587
+
1588
+ _last_speaker = recipient if chat_result.chat_history[-1]["name"] == recipient.name else self
1589
+ if hasattr(recipient, "last_speaker"):
1590
+ _last_speaker = recipient.last_speaker
1591
+
1592
+ IOStream.get_default().send(
1593
+ RunCompletionEvent(
1594
+ history=chat_result.chat_history,
1595
+ summary=chat_result.summary,
1596
+ cost=chat_result.cost,
1597
+ last_speaker=_last_speaker.name,
1598
+ )
1599
+ )
1600
+ except Exception as e:
1601
+ response.iostream.send(ErrorEvent(error=e))
1602
+
1603
+ threading.Thread(
1604
+ target=initiate_chat,
1605
+ ).start()
1606
+
1607
+ return response
1608
+
1609
+ async def a_initiate_chat(
1610
+ self,
1611
+ recipient: "ConversableAgent",
1612
+ clear_history: bool = True,
1613
+ silent: Optional[bool] = False,
1614
+ cache: Optional[AbstractCache] = None,
1615
+ max_turns: Optional[int] = None,
1616
+ summary_method: Optional[Union[str, Callable[..., Any]]] = DEFAULT_SUMMARY_METHOD,
1617
+ summary_args: Optional[dict[str, Any]] = {},
1618
+ message: Optional[Union[str, Callable[..., Any]]] = None,
1619
+ **kwargs: Any,
1620
+ ) -> ChatResult:
1621
+ """(async) Initiate a chat with the recipient agent.
1622
+
1623
+ Reset the consecutive auto reply counter.
1624
+ If `clear_history` is True, the chat history with the recipient agent will be cleared.
1625
+ `a_generate_init_message` is called to generate the initial message for the agent.
1626
+
1627
+ Args: Please refer to `initiate_chat`.
1628
+
1629
+ Returns:
1630
+ ChatResult: an ChatResult object.
1631
+ """
1632
+ iostream = IOStream.get_default()
1633
+
1634
+ _chat_info = locals().copy()
1635
+ _chat_info["sender"] = self
1636
+ consolidate_chat_info(_chat_info, uniform_sender=self)
1637
+ for agent in [self, recipient]:
1638
+ agent.previous_cache = agent.client_cache
1639
+ agent.client_cache = cache
1640
+ if isinstance(max_turns, int):
1641
+ self._prepare_chat(recipient, clear_history, reply_at_receive=False)
1642
+ for _ in range(max_turns):
1643
+ if _ == 0:
1644
+ if isinstance(message, Callable):
1645
+ msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)
1646
+ else:
1647
+ msg2send = await self.a_generate_init_message(message, **kwargs)
1648
+ else:
1649
+ msg2send = await self.a_generate_reply(messages=self.chat_messages[recipient], sender=recipient)
1650
+ if msg2send is None:
1651
+ break
1652
+ await self.a_send(msg2send, recipient, request_reply=True, silent=silent)
1653
+ else: # No breaks in the for loop, so we have reached max turns
1654
+ iostream.send(TerminationEvent(termination_reason=f"Maximum turns ({max_turns}) reached"))
1655
+ else:
1656
+ self._prepare_chat(recipient, clear_history)
1657
+ if isinstance(message, Callable):
1658
+ msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)
1659
+ else:
1660
+ msg2send = await self.a_generate_init_message(message, **kwargs)
1661
+ await self.a_send(msg2send, recipient, silent=silent)
1662
+ summary = self._summarize_chat(
1663
+ summary_method,
1664
+ summary_args,
1665
+ recipient,
1666
+ cache=cache,
1667
+ )
1668
+ for agent in [self, recipient]:
1669
+ agent.client_cache = agent.previous_cache
1670
+ agent.previous_cache = None
1671
+ chat_result = ChatResult(
1672
+ chat_history=self.chat_messages[recipient],
1673
+ summary=summary,
1674
+ cost=gather_usage_summary([self, recipient]),
1675
+ human_input=self._human_input,
1676
+ )
1677
+ return chat_result
1678
+
1679
+ async def a_run(
1680
+ self,
1681
+ recipient: Optional["ConversableAgent"] = None,
1682
+ clear_history: bool = True,
1683
+ silent: Optional[bool] = False,
1684
+ cache: Optional[AbstractCache] = None,
1685
+ max_turns: Optional[int] = None,
1686
+ summary_method: Optional[Union[str, Callable[..., Any]]] = DEFAULT_SUMMARY_METHOD,
1687
+ summary_args: Optional[dict[str, Any]] = {},
1688
+ message: Optional[Union[dict[str, Any], str, Callable[..., Any]]] = None,
1689
+ executor_kwargs: Optional[dict[str, Any]] = None,
1690
+ tools: Optional[Union[Tool, Iterable[Tool]]] = None,
1691
+ user_input: Optional[bool] = False,
1692
+ msg_to: Optional[str] = "agent",
1693
+ **kwargs: Any,
1694
+ ) -> AsyncRunResponseProtocol:
1695
+ iostream = AsyncThreadIOStream()
1696
+ agents = [self, recipient] if recipient else [self]
1697
+ response = AsyncRunResponse(iostream, agents=agents)
1698
+
1699
+ if recipient is None:
1700
+
1701
+ async def initiate_chat(
1702
+ self=self,
1703
+ iostream: AsyncThreadIOStream = iostream,
1704
+ response: AsyncRunResponse = response,
1705
+ ) -> None:
1706
+ with (
1707
+ IOStream.set_default(iostream),
1708
+ self._create_or_get_executor(
1709
+ executor_kwargs=executor_kwargs,
1710
+ tools=tools,
1711
+ agent_name="user",
1712
+ agent_human_input_mode="ALWAYS" if user_input else "NEVER",
1713
+ ) as executor,
1714
+ ):
1715
+ try:
1716
+ if msg_to == "agent":
1717
+ chat_result = await executor.a_initiate_chat(
1718
+ self,
1719
+ message=message,
1720
+ clear_history=clear_history,
1721
+ max_turns=max_turns,
1722
+ summary_method=summary_method,
1723
+ )
1724
+ else:
1725
+ chat_result = await self.a_initiate_chat(
1726
+ executor,
1727
+ message=message,
1728
+ clear_history=clear_history,
1729
+ max_turns=max_turns,
1730
+ summary_method=summary_method,
1731
+ )
1732
+
1733
+ IOStream.get_default().send(
1734
+ RunCompletionEvent(
1735
+ history=chat_result.chat_history,
1736
+ summary=chat_result.summary,
1737
+ cost=chat_result.cost,
1738
+ last_speaker=self.name,
1739
+ )
1740
+ )
1741
+ except Exception as e:
1742
+ response.iostream.send(ErrorEvent(error=e))
1743
+
1744
+ else:
1745
+
1746
+ async def initiate_chat(
1747
+ self=self,
1748
+ iostream: AsyncThreadIOStream = iostream,
1749
+ response: AsyncRunResponse = response,
1750
+ ) -> None:
1751
+ with IOStream.set_default(iostream): # type: ignore[arg-type]
1752
+ try:
1753
+ chat_result = await self.a_initiate_chat(
1754
+ recipient,
1755
+ clear_history=clear_history,
1756
+ silent=silent,
1757
+ cache=cache,
1758
+ max_turns=max_turns,
1759
+ summary_method=summary_method,
1760
+ summary_args=summary_args,
1761
+ message=message,
1762
+ **kwargs,
1763
+ )
1764
+
1765
+ last_speaker = recipient if chat_result.chat_history[-1]["name"] == recipient.name else self
1766
+ if hasattr(recipient, "last_speaker"):
1767
+ last_speaker = recipient.last_speaker
1768
+
1769
+ IOStream.get_default().send(
1770
+ RunCompletionEvent(
1771
+ history=chat_result.chat_history,
1772
+ summary=chat_result.summary,
1773
+ cost=chat_result.cost,
1774
+ last_speaker=last_speaker.name,
1775
+ )
1776
+ )
1777
+
1778
+ except Exception as e:
1779
+ response.iostream.send(ErrorEvent(error=e))
1780
+
1781
+ asyncio.create_task(initiate_chat())
1782
+
1783
+ return response
1784
+
1785
+ def _summarize_chat(
1786
+ self,
1787
+ summary_method,
1788
+ summary_args,
1789
+ recipient: Optional[Agent] = None,
1790
+ cache: Optional[AbstractCache] = None,
1791
+ ) -> str:
1792
+ """Get a chat summary from an agent participating in a chat.
1793
+
1794
+ Args:
1795
+ summary_method (str or callable): the summary_method to get the summary.
1796
+ The callable summary_method should take the recipient and sender agent in a chat as input and return a string of summary. E.g,
1797
+ ```python
1798
+ def my_summary_method(
1799
+ sender: ConversableAgent,
1800
+ recipient: ConversableAgent,
1801
+ summary_args: dict,
1802
+ ):
1803
+ return recipient.last_message(sender)["content"]
1804
+ ```
1805
+ summary_args (dict): a dictionary of arguments to be passed to the summary_method.
1806
+ recipient: the recipient agent in a chat.
1807
+ cache: the cache client to be used for this conversation. When provided,
1808
+ the cache will be used to store and retrieve LLM responses when generating
1809
+ summaries, which can improve performance and reduce API costs for
1810
+ repetitive summary requests. The cache is passed to the summary_method
1811
+ via summary_args['cache'].
1812
+
1813
+ Returns:
1814
+ str: a chat summary from the agent.
1815
+ """
1816
+ summary = ""
1817
+ if summary_method is None:
1818
+ return summary
1819
+ if "cache" not in summary_args:
1820
+ summary_args["cache"] = cache
1821
+ if summary_method == "reflection_with_llm":
1822
+ summary_method = self._reflection_with_llm_as_summary
1823
+ elif summary_method == "last_msg":
1824
+ summary_method = self._last_msg_as_summary
1825
+
1826
+ if isinstance(summary_method, Callable):
1827
+ summary = summary_method(self, recipient, summary_args)
1828
+ else:
1829
+ raise ValueError(
1830
+ "If not None, the summary_method must be a string from [`reflection_with_llm`, `last_msg`] or a callable."
1831
+ )
1832
+ return summary
1833
+
1834
+ @staticmethod
1835
+ def _last_msg_as_summary(sender, recipient, summary_args) -> str:
1836
+ """Get a chat summary from the last message of the recipient."""
1837
+ summary = ""
1838
+ try:
1839
+ content = recipient.last_message(sender)["content"]
1840
+ if isinstance(content, str):
1841
+ summary = content.replace("TERMINATE", "")
1842
+ elif isinstance(content, list):
1843
+ # Remove the `TERMINATE` word in the content list.
1844
+ summary = "\n".join(
1845
+ x["text"].replace("TERMINATE", "") for x in content if isinstance(x, dict) and "text" in x
1846
+ )
1847
+ except (IndexError, AttributeError) as e:
1848
+ warnings.warn(f"Cannot extract summary using last_msg: {e}. Using an empty str as summary.", UserWarning)
1849
+ return summary
1850
+
1851
+ @staticmethod
1852
+ def _reflection_with_llm_as_summary(sender, recipient, summary_args):
1853
+ prompt = summary_args.get("summary_prompt")
1854
+ prompt = ConversableAgent.DEFAULT_SUMMARY_PROMPT if prompt is None else prompt
1855
+ if not isinstance(prompt, str):
1856
+ raise ValueError("The summary_prompt must be a string.")
1857
+ msg_list = recipient.chat_messages_for_summary(sender)
1858
+ agent = sender if recipient is None else recipient
1859
+ role = summary_args.get("summary_role", None)
1860
+ if role and not isinstance(role, str):
1861
+ raise ValueError("The summary_role in summary_arg must be a string.")
1862
+ try:
1863
+ summary = sender._reflection_with_llm(
1864
+ prompt, msg_list, llm_agent=agent, cache=summary_args.get("cache"), role=role
1865
+ )
1866
+ except Exception as e:
1867
+ warnings.warn(
1868
+ f"Cannot extract summary using reflection_with_llm: {e}. Using an empty str as summary.", UserWarning
1869
+ )
1870
+ summary = ""
1871
+ return summary
1872
+
1873
+ def _reflection_with_llm(
1874
+ self,
1875
+ prompt,
1876
+ messages,
1877
+ llm_agent: Optional[Agent] = None,
1878
+ cache: Optional[AbstractCache] = None,
1879
+ role: Union[str, None] = None,
1880
+ ) -> str:
1881
+ """Get a chat summary using reflection with an llm client based on the conversation history.
1882
+
1883
+ Args:
1884
+ prompt (str): The prompt (in this method it is used as system prompt) used to get the summary.
1885
+ messages (list): The messages generated as part of a chat conversation.
1886
+ llm_agent: the agent with an llm client.
1887
+ cache (AbstractCache or None): the cache client to be used for this conversation.
1888
+ role (str): the role of the message, usually "system" or "user". Default is "system".
1889
+ """
1890
+ if not role:
1891
+ role = "system"
1892
+
1893
+ system_msg = [
1894
+ {
1895
+ "role": role,
1896
+ "content": prompt,
1897
+ }
1898
+ ]
1899
+
1900
+ messages = messages + system_msg
1901
+ if llm_agent and llm_agent.client is not None:
1902
+ llm_client = llm_agent.client
1903
+ elif self.client is not None:
1904
+ llm_client = self.client
1905
+ else:
1906
+ raise ValueError("No OpenAIWrapper client is found.")
1907
+ response = self._generate_oai_reply_from_client(llm_client=llm_client, messages=messages, cache=cache)
1908
+ return response
1909
+
1910
+ def _check_chat_queue_for_sender(self, chat_queue: list[dict[str, Any]]) -> list[dict[str, Any]]:
1911
+ """Check the chat queue and add the "sender" key if it's missing.
1912
+
1913
+ Args:
1914
+ chat_queue (List[Dict[str, Any]]): A list of dictionaries containing chat information.
1915
+
1916
+ Returns:
1917
+ List[Dict[str, Any]]: A new list of dictionaries with the "sender" key added if it was missing.
1918
+ """
1919
+ chat_queue_with_sender = []
1920
+ for chat_info in chat_queue:
1921
+ if chat_info.get("sender") is None:
1922
+ chat_info["sender"] = self
1923
+ chat_queue_with_sender.append(chat_info)
1924
+ return chat_queue_with_sender
1925
+
1926
+ def initiate_chats(self, chat_queue: list[dict[str, Any]]) -> list[ChatResult]:
1927
+ """(Experimental) Initiate chats with multiple agents.
1928
+
1929
+ Args:
1930
+ chat_queue (List[Dict]): a list of dictionaries containing the information of the chats.
1931
+ Each dictionary should contain the input arguments for [`initiate_chat`](#initiate-chat)
1932
+
1933
+ Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.
1934
+ """
1935
+ _chat_queue = self._check_chat_queue_for_sender(chat_queue)
1936
+ self._finished_chats = initiate_chats(_chat_queue)
1937
+
1938
+ return self._finished_chats
1939
+
1940
+ def sequential_run(
1941
+ self,
1942
+ chat_queue: list[dict[str, Any]],
1943
+ ) -> list[RunResponseProtocol]:
1944
+ """(Experimental) Initiate chats with multiple agents sequentially.
1945
+
1946
+ Args:
1947
+ chat_queue (List[Dict]): a list of dictionaries containing the information of the chats.
1948
+ Each dictionary should contain the input arguments for [`initiate_chat`](#initiate-chat)
1949
+
1950
+ Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.
1951
+ """
1952
+ iostreams = [ThreadIOStream() for _ in range(len(chat_queue))]
1953
+ # todo: add agents
1954
+ responses = [RunResponse(iostream, agents=[]) for iostream in iostreams]
1955
+
1956
+ def _initiate_chats(
1957
+ iostreams: list[ThreadIOStream] = iostreams,
1958
+ responses: list[RunResponseProtocol] = responses,
1959
+ ) -> None:
1960
+ response = responses[0]
1961
+ try:
1962
+ _chat_queue = self._check_chat_queue_for_sender(chat_queue)
1963
+
1964
+ consolidate_chat_info(_chat_queue)
1965
+ _validate_recipients(_chat_queue)
1966
+ finished_chats = []
1967
+ for chat_info, response, iostream in zip(_chat_queue, responses, iostreams):
1968
+ with IOStream.set_default(iostream):
1969
+ _chat_carryover = chat_info.get("carryover", [])
1970
+ finished_chat_indexes_to_exclude_from_carryover = chat_info.get(
1971
+ "finished_chat_indexes_to_exclude_from_carryover", []
1972
+ )
1973
+
1974
+ if isinstance(_chat_carryover, str):
1975
+ _chat_carryover = [_chat_carryover]
1976
+ chat_info["carryover"] = _chat_carryover + [
1977
+ r.summary
1978
+ for i, r in enumerate(finished_chats)
1979
+ if i not in finished_chat_indexes_to_exclude_from_carryover
1980
+ ]
1981
+
1982
+ if not chat_info.get("silent", False):
1983
+ IOStream.get_default().send(PostCarryoverProcessingEvent(chat_info=chat_info))
1984
+
1985
+ sender = chat_info["sender"]
1986
+ chat_res = sender.initiate_chat(**chat_info)
1987
+
1988
+ IOStream.get_default().send(
1989
+ RunCompletionEvent(
1990
+ history=chat_res.chat_history,
1991
+ summary=chat_res.summary,
1992
+ cost=chat_res.cost,
1993
+ last_speaker=(self if chat_res.chat_history[-1]["name"] == self.name else sender).name,
1994
+ )
1995
+ )
1996
+
1997
+ finished_chats.append(chat_res)
1998
+ except Exception as e:
1999
+ response.iostream.send(ErrorEvent(error=e))
2000
+
2001
+ threading.Thread(target=_initiate_chats).start()
2002
+
2003
+ return responses
2004
+
2005
+ async def a_initiate_chats(self, chat_queue: list[dict[str, Any]]) -> dict[int, ChatResult]:
2006
+ _chat_queue = self._check_chat_queue_for_sender(chat_queue)
2007
+ self._finished_chats = await a_initiate_chats(_chat_queue)
2008
+ return self._finished_chats
2009
+
2010
+ async def a_sequential_run(
2011
+ self,
2012
+ chat_queue: list[dict[str, Any]],
2013
+ ) -> list[AsyncRunResponseProtocol]:
2014
+ """(Experimental) Initiate chats with multiple agents sequentially.
2015
+
2016
+ Args:
2017
+ chat_queue (List[Dict]): a list of dictionaries containing the information of the chats.
2018
+ Each dictionary should contain the input arguments for [`initiate_chat`](#initiate-chat)
2019
+
2020
+ Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.
2021
+ """
2022
+ iostreams = [AsyncThreadIOStream() for _ in range(len(chat_queue))]
2023
+ # todo: add agents
2024
+ responses = [AsyncRunResponse(iostream, agents=[]) for iostream in iostreams]
2025
+
2026
+ async def _a_initiate_chats(
2027
+ iostreams: list[AsyncThreadIOStream] = iostreams,
2028
+ responses: list[AsyncRunResponseProtocol] = responses,
2029
+ ) -> None:
2030
+ response = responses[0]
2031
+ try:
2032
+ _chat_queue = self._check_chat_queue_for_sender(chat_queue)
2033
+
2034
+ consolidate_chat_info(_chat_queue)
2035
+ _validate_recipients(_chat_queue)
2036
+ finished_chats = []
2037
+ for chat_info, response, iostream in zip(_chat_queue, responses, iostreams):
2038
+ with IOStream.set_default(iostream):
2039
+ _chat_carryover = chat_info.get("carryover", [])
2040
+ finished_chat_indexes_to_exclude_from_carryover = chat_info.get(
2041
+ "finished_chat_indexes_to_exclude_from_carryover", []
2042
+ )
2043
+
2044
+ if isinstance(_chat_carryover, str):
2045
+ _chat_carryover = [_chat_carryover]
2046
+ chat_info["carryover"] = _chat_carryover + [
2047
+ r.summary
2048
+ for i, r in enumerate(finished_chats)
2049
+ if i not in finished_chat_indexes_to_exclude_from_carryover
2050
+ ]
2051
+
2052
+ if not chat_info.get("silent", False):
2053
+ IOStream.get_default().send(PostCarryoverProcessingEvent(chat_info=chat_info))
2054
+
2055
+ sender = chat_info["sender"]
2056
+ chat_res = await sender.a_initiate_chat(**chat_info)
2057
+
2058
+ IOStream.get_default().send(
2059
+ RunCompletionEvent(
2060
+ history=chat_res.chat_history,
2061
+ summary=chat_res.summary,
2062
+ cost=chat_res.cost,
2063
+ last_speaker=(self if chat_res.chat_history[-1]["name"] == self.name else sender).name,
2064
+ )
2065
+ )
2066
+
2067
+ finished_chats.append(chat_res)
2068
+
2069
+ except Exception as e:
2070
+ response.iostream.send(ErrorEvent(error=e))
2071
+
2072
+ asyncio.create_task(_a_initiate_chats())
2073
+
2074
+ return responses
2075
+
2076
+ def get_chat_results(self, chat_index: Optional[int] = None) -> Union[list[ChatResult], ChatResult]:
2077
+ """A summary from the finished chats of particular agents."""
2078
+ if chat_index is not None:
2079
+ return self._finished_chats[chat_index]
2080
+ else:
2081
+ return self._finished_chats
2082
+
2083
+ def reset(self) -> None:
2084
+ """Reset the agent."""
2085
+ self.clear_history()
2086
+ self.reset_consecutive_auto_reply_counter()
2087
+ self.stop_reply_at_receive()
2088
+ if self.client is not None:
2089
+ self.client.clear_usage_summary()
2090
+ for reply_func_tuple in self._reply_func_list:
2091
+ if reply_func_tuple["reset_config"] is not None:
2092
+ reply_func_tuple["reset_config"](reply_func_tuple["config"])
2093
+ else:
2094
+ reply_func_tuple["config"] = copy.copy(reply_func_tuple["init_config"])
2095
+
2096
+ def stop_reply_at_receive(self, sender: Optional[Agent] = None):
2097
+ """Reset the reply_at_receive of the sender."""
2098
+ if sender is None:
2099
+ self.reply_at_receive.clear()
2100
+ else:
2101
+ self.reply_at_receive[sender] = False
2102
+
2103
+ def reset_consecutive_auto_reply_counter(self, sender: Optional[Agent] = None):
2104
+ """Reset the consecutive_auto_reply_counter of the sender."""
2105
+ if sender is None:
2106
+ self._consecutive_auto_reply_counter.clear()
2107
+ else:
2108
+ self._consecutive_auto_reply_counter[sender] = 0
2109
+
2110
+ def clear_history(self, recipient: Optional[Agent] = None, nr_messages_to_preserve: Optional[int] = None):
2111
+ """Clear the chat history of the agent.
2112
+
2113
+ Args:
2114
+ recipient: the agent with whom the chat history to clear. If None, clear the chat history with all agents.
2115
+ nr_messages_to_preserve: the number of newest messages to preserve in the chat history.
2116
+ """
2117
+ iostream = IOStream.get_default()
2118
+ if recipient is None:
2119
+ no_messages_preserved = 0
2120
+ if nr_messages_to_preserve:
2121
+ for key in self._oai_messages:
2122
+ nr_messages_to_preserve_internal = nr_messages_to_preserve
2123
+ # if breaking history between function call and function response, save function call message
2124
+ # additionally, otherwise openai will return error
2125
+ first_msg_to_save = self._oai_messages[key][-nr_messages_to_preserve_internal]
2126
+ if "tool_responses" in first_msg_to_save:
2127
+ nr_messages_to_preserve_internal += 1
2128
+ # clear_conversable_agent_history.print_preserving_message(iostream.print)
2129
+ no_messages_preserved += 1
2130
+ # Remove messages from history except last `nr_messages_to_preserve` messages.
2131
+ self._oai_messages[key] = self._oai_messages[key][-nr_messages_to_preserve_internal:]
2132
+ iostream.send(ClearConversableAgentHistoryEvent(agent=self, no_events_preserved=no_messages_preserved))
2133
+ else:
2134
+ self._oai_messages.clear()
2135
+ else:
2136
+ self._oai_messages[recipient].clear()
2137
+ # clear_conversable_agent_history.print_warning(iostream.print)
2138
+ if nr_messages_to_preserve:
2139
+ iostream.send(ClearConversableAgentHistoryWarningEvent(recipient=self))
2140
+
2141
+ def generate_oai_reply(
2142
+ self,
2143
+ messages: Optional[list[dict[str, Any]]] = None,
2144
+ sender: Optional[Agent] = None,
2145
+ config: Optional[OpenAIWrapper] = None,
2146
+ ) -> tuple[bool, Optional[Union[str, dict[str, Any]]]]:
2147
+ """Generate a reply using autogen.oai."""
2148
+ client = self.client if config is None else config
2149
+ if client is None:
2150
+ return False, None
2151
+ if messages is None:
2152
+ messages = self._oai_messages[sender]
2153
+ extracted_response = self._generate_oai_reply_from_client(
2154
+ client, self._oai_system_message + messages, self.client_cache
2155
+ )
2156
+ return (False, None) if extracted_response is None else (True, extracted_response)
2157
+
2158
+ def _generate_oai_reply_from_client(self, llm_client, messages, cache) -> Optional[Union[str, dict[str, Any]]]:
2159
+ # unroll tool_responses
2160
+ all_messages = []
2161
+ for message in messages:
2162
+ tool_responses = message.get("tool_responses", [])
2163
+ if tool_responses:
2164
+ all_messages += tool_responses
2165
+ # tool role on the parent message means the content is just concatenation of all of the tool_responses
2166
+ if message.get("role") != "tool":
2167
+ all_messages.append({key: message[key] for key in message if key != "tool_responses"})
2168
+ else:
2169
+ all_messages.append(message)
2170
+
2171
+ # TODO: #1143 handle token limit exceeded error
2172
+ response = llm_client.create(
2173
+ context=messages[-1].pop("context", None),
2174
+ messages=all_messages,
2175
+ cache=cache,
2176
+ agent=self,
2177
+ )
2178
+ extracted_response = llm_client.extract_text_or_completion_object(response)[0]
2179
+
2180
+ if extracted_response is None:
2181
+ warnings.warn(f"Extracted_response from {response} is None.", UserWarning)
2182
+ return None
2183
+ # ensure function and tool calls will be accepted when sent back to the LLM
2184
+ if not isinstance(extracted_response, str) and hasattr(extracted_response, "model_dump"):
2185
+ extracted_response = extracted_response.model_dump()
2186
+ if isinstance(extracted_response, dict):
2187
+ if extracted_response.get("function_call"):
2188
+ extracted_response["function_call"]["name"] = self._normalize_name(
2189
+ extracted_response["function_call"]["name"]
2190
+ )
2191
+ for tool_call in extracted_response.get("tool_calls") or []:
2192
+ tool_call["function"]["name"] = self._normalize_name(tool_call["function"]["name"])
2193
+ # Remove id and type if they are not present.
2194
+ # This is to make the tool call object compatible with Mistral API.
2195
+ if tool_call.get("id") is None:
2196
+ tool_call.pop("id")
2197
+ if tool_call.get("type") is None:
2198
+ tool_call.pop("type")
2199
+ return extracted_response
2200
+
2201
+ async def a_generate_oai_reply(
2202
+ self,
2203
+ messages: Optional[list[dict[str, Any]]] = None,
2204
+ sender: Optional[Agent] = None,
2205
+ config: Optional[Any] = None,
2206
+ ) -> tuple[bool, Optional[Union[str, dict[str, Any]]]]:
2207
+ """Generate a reply using autogen.oai asynchronously."""
2208
+ iostream = IOStream.get_default()
2209
+
2210
+ def _generate_oai_reply(
2211
+ self, iostream: IOStream, *args: Any, **kwargs: Any
2212
+ ) -> tuple[bool, Optional[Union[str, dict[str, Any]]]]:
2213
+ with IOStream.set_default(iostream):
2214
+ return self.generate_oai_reply(*args, **kwargs)
2215
+
2216
+ return await asyncio.get_event_loop().run_in_executor(
2217
+ None,
2218
+ functools.partial(
2219
+ _generate_oai_reply, self=self, iostream=iostream, messages=messages, sender=sender, config=config
2220
+ ),
2221
+ )
2222
+
2223
+ def _generate_code_execution_reply_using_executor(
2224
+ self,
2225
+ messages: Optional[list[dict[str, Any]]] = None,
2226
+ sender: Optional[Agent] = None,
2227
+ config: Optional[Union[dict[str, Any], Literal[False]]] = None,
2228
+ ):
2229
+ """Generate a reply using code executor."""
2230
+ iostream = IOStream.get_default()
2231
+
2232
+ if config is not None:
2233
+ raise ValueError("config is not supported for _generate_code_execution_reply_using_executor.")
2234
+ if self._code_execution_config is False:
2235
+ return False, None
2236
+ if messages is None:
2237
+ messages = self._oai_messages[sender]
2238
+ last_n_messages = self._code_execution_config.get("last_n_messages", "auto")
2239
+
2240
+ if not (isinstance(last_n_messages, (int, float)) and last_n_messages >= 0) and last_n_messages != "auto":
2241
+ raise ValueError("last_n_messages must be either a non-negative integer, or the string 'auto'.")
2242
+
2243
+ num_messages_to_scan = last_n_messages
2244
+ if last_n_messages == "auto":
2245
+ # Find when the agent last spoke
2246
+ num_messages_to_scan = 0
2247
+ for message in reversed(messages):
2248
+ if "role" not in message or message["role"] != "user":
2249
+ break
2250
+ else:
2251
+ num_messages_to_scan += 1
2252
+ num_messages_to_scan = min(len(messages), num_messages_to_scan)
2253
+ messages_to_scan = messages[-num_messages_to_scan:]
2254
+
2255
+ # iterate through the last n messages in reverse
2256
+ # if code blocks are found, execute the code blocks and return the output
2257
+ # if no code blocks are found, continue
2258
+ for message in reversed(messages_to_scan):
2259
+ if not message["content"]:
2260
+ continue
2261
+ code_blocks = self._code_executor.code_extractor.extract_code_blocks(message["content"])
2262
+ if len(code_blocks) == 0:
2263
+ continue
2264
+
2265
+ iostream.send(GenerateCodeExecutionReplyEvent(code_blocks=code_blocks, sender=sender, recipient=self))
2266
+
2267
+ # found code blocks, execute code.
2268
+ code_result = self._code_executor.execute_code_blocks(code_blocks)
2269
+ exitcode2str = "execution succeeded" if code_result.exit_code == 0 else "execution failed"
2270
+ return True, f"exitcode: {code_result.exit_code} ({exitcode2str})\nCode output: {code_result.output}"
2271
+
2272
+ return False, None
2273
+
2274
+ def generate_code_execution_reply(
2275
+ self,
2276
+ messages: Optional[list[dict[str, Any]]] = None,
2277
+ sender: Optional[Agent] = None,
2278
+ config: Optional[Union[dict[str, Any], Literal[False]]] = None,
2279
+ ):
2280
+ """Generate a reply using code execution."""
2281
+ code_execution_config = config if config is not None else self._code_execution_config
2282
+ if code_execution_config is False:
2283
+ return False, None
2284
+ if messages is None:
2285
+ messages = self._oai_messages[sender]
2286
+ last_n_messages = code_execution_config.pop("last_n_messages", "auto")
2287
+
2288
+ if not (isinstance(last_n_messages, (int, float)) and last_n_messages >= 0) and last_n_messages != "auto":
2289
+ raise ValueError("last_n_messages must be either a non-negative integer, or the string 'auto'.")
2290
+
2291
+ messages_to_scan = last_n_messages
2292
+ if last_n_messages == "auto":
2293
+ # Find when the agent last spoke
2294
+ messages_to_scan = 0
2295
+ for i in range(len(messages)):
2296
+ message = messages[-(i + 1)]
2297
+ if "role" not in message or message["role"] != "user":
2298
+ break
2299
+ else:
2300
+ messages_to_scan += 1
2301
+
2302
+ # iterate through the last n messages in reverse
2303
+ # if code blocks are found, execute the code blocks and return the output
2304
+ # if no code blocks are found, continue
2305
+ for i in range(min(len(messages), messages_to_scan)):
2306
+ message = messages[-(i + 1)]
2307
+ if not message["content"]:
2308
+ continue
2309
+ code_blocks = extract_code(message["content"])
2310
+ if len(code_blocks) == 1 and code_blocks[0][0] == UNKNOWN:
2311
+ continue
2312
+
2313
+ # found code blocks, execute code and push "last_n_messages" back
2314
+ exitcode, logs = self.execute_code_blocks(code_blocks)
2315
+ code_execution_config["last_n_messages"] = last_n_messages
2316
+ exitcode2str = "execution succeeded" if exitcode == 0 else "execution failed"
2317
+ return True, f"exitcode: {exitcode} ({exitcode2str})\nCode output: {logs}"
2318
+
2319
+ # no code blocks are found, push last_n_messages back and return.
2320
+ code_execution_config["last_n_messages"] = last_n_messages
2321
+
2322
+ return False, None
2323
+
2324
+ def _run_async_in_thread(self, coro):
2325
+ """Run an async coroutine in a separate thread with its own event loop."""
2326
+ result = {}
2327
+
2328
+ def runner():
2329
+ loop = asyncio.new_event_loop()
2330
+ asyncio.set_event_loop(loop)
2331
+ result["value"] = loop.run_until_complete(coro)
2332
+ loop.close()
2333
+
2334
+ t = threading.Thread(target=runner)
2335
+ t.start()
2336
+ t.join()
2337
+ return result["value"]
2338
+
2339
+ def generate_function_call_reply(
2340
+ self,
2341
+ messages: Optional[list[dict[str, Any]]] = None,
2342
+ sender: Optional[Agent] = None,
2343
+ config: Optional[Any] = None,
2344
+ ) -> tuple[bool, Optional[dict[str, Any]]]:
2345
+ """Generate a reply using function call.
2346
+
2347
+ "function_call" replaced by "tool_calls" as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)
2348
+ See https://platform.openai.com/docs/api-reference/chat/create#chat-create-functions
2349
+ """
2350
+ if config is None:
2351
+ config = self
2352
+ if messages is None:
2353
+ messages = self._oai_messages[sender]
2354
+ message = messages[-1]
2355
+ if message.get("function_call"):
2356
+ call_id = message.get("id", None)
2357
+ func_call = message["function_call"]
2358
+ func = self._function_map.get(func_call.get("name", None), None)
2359
+ if inspect.iscoroutinefunction(func):
2360
+ coro = self.a_execute_function(func_call, call_id=call_id)
2361
+ _, func_return = self._run_async_in_thread(coro)
2362
+ else:
2363
+ _, func_return = self.execute_function(message["function_call"], call_id=call_id)
2364
+ return True, func_return
2365
+ return False, None
2366
+
2367
+ async def a_generate_function_call_reply(
2368
+ self,
2369
+ messages: Optional[list[dict[str, Any]]] = None,
2370
+ sender: Optional[Agent] = None,
2371
+ config: Optional[Any] = None,
2372
+ ) -> tuple[bool, Optional[dict[str, Any]]]:
2373
+ """Generate a reply using async function call.
2374
+
2375
+ "function_call" replaced by "tool_calls" as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)
2376
+ See https://platform.openai.com/docs/api-reference/chat/create#chat-create-functions
2377
+ """
2378
+ if config is None:
2379
+ config = self
2380
+ if messages is None:
2381
+ messages = self._oai_messages[sender]
2382
+ message = messages[-1]
2383
+ if "function_call" in message:
2384
+ call_id = message.get("id", None)
2385
+ func_call = message["function_call"]
2386
+ func_name = func_call.get("name", "")
2387
+ func = self._function_map.get(func_name, None)
2388
+ if func and inspect.iscoroutinefunction(func):
2389
+ _, func_return = await self.a_execute_function(func_call, call_id=call_id)
2390
+ else:
2391
+ _, func_return = self.execute_function(func_call, call_id=call_id)
2392
+ return True, func_return
2393
+
2394
+ return False, None
2395
+
2396
+ def _str_for_tool_response(self, tool_response):
2397
+ return str(tool_response.get("content", ""))
2398
+
2399
+ def generate_tool_calls_reply(
2400
+ self,
2401
+ messages: Optional[list[dict[str, Any]]] = None,
2402
+ sender: Optional[Agent] = None,
2403
+ config: Optional[Any] = None,
2404
+ ) -> tuple[bool, Optional[dict[str, Any]]]:
2405
+ """Generate a reply using tool call."""
2406
+ if config is None:
2407
+ config = self
2408
+ if messages is None:
2409
+ messages = self._oai_messages[sender]
2410
+ message = messages[-1]
2411
+ tool_returns = []
2412
+ for tool_call in message.get("tool_calls", []):
2413
+ function_call = tool_call.get("function", {})
2414
+ tool_call_id = tool_call.get("id", None)
2415
+ func = self._function_map.get(function_call.get("name", None), None)
2416
+ if inspect.iscoroutinefunction(func):
2417
+ coro = self.a_execute_function(function_call, call_id=tool_call_id)
2418
+ _, func_return = self._run_async_in_thread(coro)
2419
+ else:
2420
+ _, func_return = self.execute_function(function_call, call_id=tool_call_id)
2421
+ content = func_return.get("content", "")
2422
+ if content is None:
2423
+ content = ""
2424
+
2425
+ if tool_call_id is not None:
2426
+ tool_call_response = {
2427
+ "tool_call_id": tool_call_id,
2428
+ "role": "tool",
2429
+ "content": content,
2430
+ }
2431
+ else:
2432
+ # Do not include tool_call_id if it is not present.
2433
+ # This is to make the tool call object compatible with Mistral API.
2434
+ tool_call_response = {
2435
+ "role": "tool",
2436
+ "content": content,
2437
+ }
2438
+ tool_returns.append(tool_call_response)
2439
+ if tool_returns:
2440
+ return True, {
2441
+ "role": "tool",
2442
+ "tool_responses": tool_returns,
2443
+ "content": "\n\n".join([self._str_for_tool_response(tool_return) for tool_return in tool_returns]),
2444
+ }
2445
+ return False, None
2446
+
2447
+ async def _a_execute_tool_call(self, tool_call):
2448
+ tool_call_id = tool_call["id"]
2449
+ function_call = tool_call.get("function", {})
2450
+ _, func_return = await self.a_execute_function(function_call, call_id=tool_call_id)
2451
+ return {
2452
+ "tool_call_id": tool_call_id,
2453
+ "role": "tool",
2454
+ "content": func_return.get("content", ""),
2455
+ }
2456
+
2457
+ async def a_generate_tool_calls_reply(
2458
+ self,
2459
+ messages: Optional[list[dict[str, Any]]] = None,
2460
+ sender: Optional[Agent] = None,
2461
+ config: Optional[Any] = None,
2462
+ ) -> tuple[bool, Optional[dict[str, Any]]]:
2463
+ """Generate a reply using async function call."""
2464
+ if config is None:
2465
+ config = self
2466
+ if messages is None:
2467
+ messages = self._oai_messages[sender]
2468
+ message = messages[-1]
2469
+ async_tool_calls = []
2470
+ for tool_call in message.get("tool_calls", []):
2471
+ async_tool_calls.append(self._a_execute_tool_call(tool_call))
2472
+ if async_tool_calls:
2473
+ tool_returns = await asyncio.gather(*async_tool_calls)
2474
+ return True, {
2475
+ "role": "tool",
2476
+ "tool_responses": tool_returns,
2477
+ "content": "\n\n".join([self._str_for_tool_response(tool_return) for tool_return in tool_returns]),
2478
+ }
2479
+
2480
+ return False, None
2481
+
2482
+ def check_termination_and_human_reply(
2483
+ self,
2484
+ messages: Optional[list[dict[str, Any]]] = None,
2485
+ sender: Optional[Agent] = None,
2486
+ config: Optional[Any] = None,
2487
+ ) -> tuple[bool, Union[str, None]]:
2488
+ """Check if the conversation should be terminated, and if human reply is provided.
2489
+
2490
+ This method checks for conditions that require the conversation to be terminated, such as reaching
2491
+ a maximum number of consecutive auto-replies or encountering a termination message. Additionally,
2492
+ it prompts for and processes human input based on the configured human input mode, which can be
2493
+ 'ALWAYS', 'NEVER', or 'TERMINATE'. The method also manages the consecutive auto-reply counter
2494
+ for the conversation and prints relevant messages based on the human input received.
2495
+
2496
+ Args:
2497
+ messages: A list of message dictionaries, representing the conversation history.
2498
+ sender: The agent object representing the sender of the message.
2499
+ config: Configuration object, defaults to the current instance if not provided.
2500
+
2501
+ Returns:
2502
+ A tuple containing a boolean indicating if the conversation
2503
+ should be terminated, and a human reply which can be a string, a dictionary, or None.
2504
+ """
2505
+ iostream = IOStream.get_default()
2506
+
2507
+ if config is None:
2508
+ config = self
2509
+ if messages is None:
2510
+ messages = self._oai_messages[sender] if sender else []
2511
+
2512
+ termination_reason = None
2513
+
2514
+ # if there are no messages, continue the conversation
2515
+ if not messages:
2516
+ return False, None
2517
+ message = messages[-1]
2518
+
2519
+ reply = ""
2520
+ no_human_input_msg = ""
2521
+ sender_name = "the sender" if sender is None else sender.name
2522
+ if self.human_input_mode == "ALWAYS":
2523
+ reply = self.get_human_input(
2524
+ f"Replying as {self.name}. Provide feedback to {sender_name}. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: "
2525
+ )
2526
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
2527
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
2528
+ if not reply and self._is_termination_msg(message):
2529
+ termination_reason = f"Termination message condition on agent '{self.name}' met"
2530
+ elif reply == "exit":
2531
+ termination_reason = "User requested to end the conversation"
2532
+
2533
+ reply = reply if reply or not self._is_termination_msg(message) else "exit"
2534
+ else:
2535
+ if self._consecutive_auto_reply_counter[sender] >= self._max_consecutive_auto_reply_dict[sender]:
2536
+ if self.human_input_mode == "NEVER":
2537
+ termination_reason = "Maximum number of consecutive auto-replies reached"
2538
+ reply = "exit"
2539
+ else:
2540
+ # self.human_input_mode == "TERMINATE":
2541
+ terminate = self._is_termination_msg(message)
2542
+ reply = self.get_human_input(
2543
+ f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "
2544
+ if terminate
2545
+ else f"Please give feedback to {sender_name}. Press enter to skip and use auto-reply, or type 'exit' to stop the conversation: "
2546
+ )
2547
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
2548
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
2549
+ if reply != "exit" and terminate:
2550
+ termination_reason = (
2551
+ f"Termination message condition on agent '{self.name}' met and no human input provided"
2552
+ )
2553
+ elif reply == "exit":
2554
+ termination_reason = "User requested to end the conversation"
2555
+
2556
+ reply = reply if reply or not terminate else "exit"
2557
+ elif self._is_termination_msg(message):
2558
+ if self.human_input_mode == "NEVER":
2559
+ termination_reason = f"Termination message condition on agent '{self.name}' met"
2560
+ reply = "exit"
2561
+ else:
2562
+ # self.human_input_mode == "TERMINATE":
2563
+ reply = self.get_human_input(
2564
+ f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "
2565
+ )
2566
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
2567
+
2568
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
2569
+ if not reply or reply == "exit":
2570
+ termination_reason = (
2571
+ f"Termination message condition on agent '{self.name}' met and no human input provided"
2572
+ )
2573
+
2574
+ reply = reply or "exit"
2575
+
2576
+ # print the no_human_input_msg
2577
+ if no_human_input_msg:
2578
+ iostream.send(
2579
+ TerminationAndHumanReplyNoInputEvent(
2580
+ no_human_input_msg=no_human_input_msg, sender=sender, recipient=self
2581
+ )
2582
+ )
2583
+
2584
+ # stop the conversation
2585
+ if reply == "exit":
2586
+ # reset the consecutive_auto_reply_counter
2587
+ self._consecutive_auto_reply_counter[sender] = 0
2588
+
2589
+ if termination_reason:
2590
+ iostream.send(TerminationEvent(termination_reason=termination_reason))
2591
+
2592
+ return True, None
2593
+
2594
+ # send the human reply
2595
+ if reply or self._max_consecutive_auto_reply_dict[sender] == 0:
2596
+ # reset the consecutive_auto_reply_counter
2597
+ self._consecutive_auto_reply_counter[sender] = 0
2598
+ # User provided a custom response, return function and tool failures indicating user interruption
2599
+ tool_returns = []
2600
+ if message.get("function_call", False):
2601
+ tool_returns.append({
2602
+ "role": "function",
2603
+ "name": message["function_call"].get("name", ""),
2604
+ "content": "USER INTERRUPTED",
2605
+ })
2606
+
2607
+ if message.get("tool_calls", False):
2608
+ tool_returns.extend([
2609
+ {"role": "tool", "tool_call_id": tool_call.get("id", ""), "content": "USER INTERRUPTED"}
2610
+ for tool_call in message["tool_calls"]
2611
+ ])
2612
+
2613
+ response = {"role": "user", "content": reply}
2614
+ if tool_returns:
2615
+ response["tool_responses"] = tool_returns
2616
+
2617
+ return True, response
2618
+
2619
+ # increment the consecutive_auto_reply_counter
2620
+ self._consecutive_auto_reply_counter[sender] += 1
2621
+ if self.human_input_mode != "NEVER":
2622
+ iostream.send(UsingAutoReplyEvent(human_input_mode=self.human_input_mode, sender=sender, recipient=self))
2623
+
2624
+ return False, None
2625
+
2626
+ async def a_check_termination_and_human_reply(
2627
+ self,
2628
+ messages: Optional[list[dict[str, Any]]] = None,
2629
+ sender: Optional[Agent] = None,
2630
+ config: Optional[Any] = None,
2631
+ ) -> tuple[bool, Union[str, None]]:
2632
+ """(async) Check if the conversation should be terminated, and if human reply is provided.
2633
+
2634
+ This method checks for conditions that require the conversation to be terminated, such as reaching
2635
+ a maximum number of consecutive auto-replies or encountering a termination message. Additionally,
2636
+ it prompts for and processes human input based on the configured human input mode, which can be
2637
+ 'ALWAYS', 'NEVER', or 'TERMINATE'. The method also manages the consecutive auto-reply counter
2638
+ for the conversation and prints relevant messages based on the human input received.
2639
+
2640
+ Args:
2641
+ messages (Optional[List[Dict]]): A list of message dictionaries, representing the conversation history.
2642
+ sender (Optional[Agent]): The agent object representing the sender of the message.
2643
+ config (Optional[Any]): Configuration object, defaults to the current instance if not provided.
2644
+
2645
+ Returns:
2646
+ Tuple[bool, Union[str, Dict, None]]: A tuple containing a boolean indicating if the conversation
2647
+ should be terminated, and a human reply which can be a string, a dictionary, or None.
2648
+ """
2649
+ iostream = IOStream.get_default()
2650
+
2651
+ if config is None:
2652
+ config = self
2653
+ if messages is None:
2654
+ messages = self._oai_messages[sender] if sender else []
2655
+
2656
+ termination_reason = None
2657
+
2658
+ message = messages[-1] if messages else {}
2659
+ reply = ""
2660
+ no_human_input_msg = ""
2661
+ sender_name = "the sender" if sender is None else sender.name
2662
+ if self.human_input_mode == "ALWAYS":
2663
+ reply = await self.a_get_human_input(
2664
+ f"Replying as {self.name}. Provide feedback to {sender_name}. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: "
2665
+ )
2666
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
2667
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
2668
+ if not reply and self._is_termination_msg(message):
2669
+ termination_reason = f"Termination message condition on agent '{self.name}' met"
2670
+ elif reply == "exit":
2671
+ termination_reason = "User requested to end the conversation"
2672
+
2673
+ reply = reply if reply or not self._is_termination_msg(message) else "exit"
2674
+ else:
2675
+ if self._consecutive_auto_reply_counter[sender] >= self._max_consecutive_auto_reply_dict[sender]:
2676
+ if self.human_input_mode == "NEVER":
2677
+ termination_reason = "Maximum number of consecutive auto-replies reached"
2678
+ reply = "exit"
2679
+ else:
2680
+ # self.human_input_mode == "TERMINATE":
2681
+ terminate = self._is_termination_msg(message)
2682
+ reply = await self.a_get_human_input(
2683
+ f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "
2684
+ if terminate
2685
+ else f"Please give feedback to {sender_name}. Press enter to skip and use auto-reply, or type 'exit' to stop the conversation: "
2686
+ )
2687
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
2688
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
2689
+ if reply != "exit" and terminate:
2690
+ termination_reason = (
2691
+ f"Termination message condition on agent '{self.name}' met and no human input provided"
2692
+ )
2693
+ elif reply == "exit":
2694
+ termination_reason = "User requested to end the conversation"
2695
+
2696
+ reply = reply if reply or not terminate else "exit"
2697
+ elif self._is_termination_msg(message):
2698
+ if self.human_input_mode == "NEVER":
2699
+ termination_reason = f"Termination message condition on agent '{self.name}' met"
2700
+ reply = "exit"
2701
+ else:
2702
+ # self.human_input_mode == "TERMINATE":
2703
+ reply = await self.a_get_human_input(
2704
+ f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "
2705
+ )
2706
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
2707
+
2708
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
2709
+ if not reply or reply == "exit":
2710
+ termination_reason = (
2711
+ f"Termination message condition on agent '{self.name}' met and no human input provided"
2712
+ )
2713
+
2714
+ reply = reply or "exit"
2715
+
2716
+ # print the no_human_input_msg
2717
+ if no_human_input_msg:
2718
+ iostream.send(
2719
+ TerminationAndHumanReplyNoInputEvent(
2720
+ no_human_input_msg=no_human_input_msg, sender=sender, recipient=self
2721
+ )
2722
+ )
2723
+
2724
+ # stop the conversation
2725
+ if reply == "exit":
2726
+ # reset the consecutive_auto_reply_counter
2727
+ self._consecutive_auto_reply_counter[sender] = 0
2728
+
2729
+ if termination_reason:
2730
+ iostream.send(TerminationEvent(termination_reason=termination_reason))
2731
+
2732
+ return True, None
2733
+
2734
+ # send the human reply
2735
+ if reply or self._max_consecutive_auto_reply_dict[sender] == 0:
2736
+ # User provided a custom response, return function and tool results indicating user interruption
2737
+ # reset the consecutive_auto_reply_counter
2738
+ self._consecutive_auto_reply_counter[sender] = 0
2739
+ tool_returns = []
2740
+ if message.get("function_call", False):
2741
+ tool_returns.append({
2742
+ "role": "function",
2743
+ "name": message["function_call"].get("name", ""),
2744
+ "content": "USER INTERRUPTED",
2745
+ })
2746
+
2747
+ if message.get("tool_calls", False):
2748
+ tool_returns.extend([
2749
+ {"role": "tool", "tool_call_id": tool_call.get("id", ""), "content": "USER INTERRUPTED"}
2750
+ for tool_call in message["tool_calls"]
2751
+ ])
2752
+
2753
+ response = {"role": "user", "content": reply}
2754
+ if tool_returns:
2755
+ response["tool_responses"] = tool_returns
2756
+
2757
+ return True, response
2758
+
2759
+ # increment the consecutive_auto_reply_counter
2760
+ self._consecutive_auto_reply_counter[sender] += 1
2761
+ if self.human_input_mode != "NEVER":
2762
+ iostream.send(UsingAutoReplyEvent(human_input_mode=self.human_input_mode, sender=sender, recipient=self))
2763
+
2764
+ return False, None
2765
+
2766
+ def generate_reply(
2767
+ self,
2768
+ messages: Optional[list[dict[str, Any]]] = None,
2769
+ sender: Optional["Agent"] = None,
2770
+ **kwargs: Any,
2771
+ ) -> Optional[Union[str, dict[str, Any]]]:
2772
+ """Reply based on the conversation history and the sender.
2773
+
2774
+ Either messages or sender must be provided.
2775
+ Register a reply_func with `None` as one trigger for it to be activated when `messages` is non-empty and `sender` is `None`.
2776
+ Use registered auto reply functions to generate replies.
2777
+ By default, the following functions are checked in order:
2778
+ 1. check_termination_and_human_reply
2779
+ 2. generate_function_call_reply (deprecated in favor of tool_calls)
2780
+ 3. generate_tool_calls_reply
2781
+ 4. generate_code_execution_reply
2782
+ 5. generate_oai_reply
2783
+ Every function returns a tuple (final, reply).
2784
+ When a function returns final=False, the next function will be checked.
2785
+ So by default, termination and human reply will be checked first.
2786
+ If not terminating and human reply is skipped, execute function or code and return the result.
2787
+ AI replies are generated only when no code execution is performed.
2788
+
2789
+ Args:
2790
+ messages: a list of messages in the conversation history.
2791
+ sender: sender of an Agent instance.
2792
+ **kwargs (Any): Additional arguments to customize reply generation. Supported kwargs:
2793
+ - exclude (List[Callable[..., Any]]): A list of reply functions to exclude from
2794
+ the reply generation process. Functions in this list will be skipped even if
2795
+ they would normally be triggered.
2796
+
2797
+ Returns:
2798
+ str or dict or None: reply. None if no reply is generated.
2799
+ """
2800
+ if all((messages is None, sender is None)):
2801
+ error_msg = f"Either {messages=} or {sender=} must be provided."
2802
+ logger.error(error_msg)
2803
+ raise AssertionError(error_msg)
2804
+
2805
+ if messages is None:
2806
+ messages = self._oai_messages[sender]
2807
+
2808
+ # Call the hookable method that gives registered hooks a chance to update agent state, used for their context variables.
2809
+ self.update_agent_state_before_reply(messages)
2810
+
2811
+ # Call the hookable method that gives registered hooks a chance to process the last message.
2812
+ # Message modifications do not affect the incoming messages or self._oai_messages.
2813
+ messages = self.process_last_received_message(messages)
2814
+
2815
+ # Call the hookable method that gives registered hooks a chance to process all messages.
2816
+ # Message modifications do not affect the incoming messages or self._oai_messages.
2817
+ messages = self.process_all_messages_before_reply(messages)
2818
+
2819
+ for reply_func_tuple in self._reply_func_list:
2820
+ reply_func = reply_func_tuple["reply_func"]
2821
+ if "exclude" in kwargs and reply_func in kwargs["exclude"]:
2822
+ continue
2823
+ if inspect.iscoroutinefunction(reply_func):
2824
+ continue
2825
+ if self._match_trigger(reply_func_tuple["trigger"], sender):
2826
+ final, reply = reply_func(self, messages=messages, sender=sender, config=reply_func_tuple["config"])
2827
+ if logging_enabled():
2828
+ log_event(
2829
+ self,
2830
+ "reply_func_executed",
2831
+ reply_func_module=reply_func.__module__,
2832
+ reply_func_name=reply_func.__name__,
2833
+ final=final,
2834
+ reply=reply,
2835
+ )
2836
+ if final:
2837
+ return reply
2838
+ return self._default_auto_reply
2839
+
2840
+ async def a_generate_reply(
2841
+ self,
2842
+ messages: Optional[list[dict[str, Any]]] = None,
2843
+ sender: Optional["Agent"] = None,
2844
+ **kwargs: Any,
2845
+ ) -> Union[str, dict[str, Any], None]:
2846
+ """(async) Reply based on the conversation history and the sender.
2847
+
2848
+ Either messages or sender must be provided.
2849
+ Register a reply_func with `None` as one trigger for it to be activated when `messages` is non-empty and `sender` is `None`.
2850
+ Use registered auto reply functions to generate replies.
2851
+ By default, the following functions are checked in order:
2852
+ 1. check_termination_and_human_reply
2853
+ 2. generate_function_call_reply
2854
+ 3. generate_tool_calls_reply
2855
+ 4. generate_code_execution_reply
2856
+ 5. generate_oai_reply
2857
+ Every function returns a tuple (final, reply).
2858
+ When a function returns final=False, the next function will be checked.
2859
+ So by default, termination and human reply will be checked first.
2860
+ If not terminating and human reply is skipped, execute function or code and return the result.
2861
+ AI replies are generated only when no code execution is performed.
2862
+
2863
+ Args:
2864
+ messages: a list of messages in the conversation history.
2865
+ sender: sender of an Agent instance.
2866
+ **kwargs (Any): Additional arguments to customize reply generation. Supported kwargs:
2867
+ - exclude (List[Callable[..., Any]]): A list of reply functions to exclude from
2868
+ the reply generation process. Functions in this list will be skipped even if
2869
+ they would normally be triggered.
2870
+
2871
+ Returns:
2872
+ str or dict or None: reply. None if no reply is generated.
2873
+ """
2874
+ if all((messages is None, sender is None)):
2875
+ error_msg = f"Either {messages=} or {sender=} must be provided."
2876
+ logger.error(error_msg)
2877
+ raise AssertionError(error_msg)
2878
+
2879
+ if messages is None:
2880
+ messages = self._oai_messages[sender]
2881
+
2882
+ # Call the hookable method that gives registered hooks a chance to update agent state, used for their context variables.
2883
+ self.update_agent_state_before_reply(messages)
2884
+
2885
+ # Call the hookable method that gives registered hooks a chance to process the last message.
2886
+ # Message modifications do not affect the incoming messages or self._oai_messages.
2887
+ messages = self.process_last_received_message(messages)
2888
+
2889
+ # Call the hookable method that gives registered hooks a chance to process all messages.
2890
+ # Message modifications do not affect the incoming messages or self._oai_messages.
2891
+ messages = self.process_all_messages_before_reply(messages)
2892
+
2893
+ for reply_func_tuple in self._reply_func_list:
2894
+ reply_func = reply_func_tuple["reply_func"]
2895
+ if "exclude" in kwargs and reply_func in kwargs["exclude"]:
2896
+ continue
2897
+
2898
+ if self._match_trigger(reply_func_tuple["trigger"], sender):
2899
+ if inspect.iscoroutinefunction(reply_func):
2900
+ final, reply = await reply_func(
2901
+ self, messages=messages, sender=sender, config=reply_func_tuple["config"]
2902
+ )
2903
+ else:
2904
+ final, reply = reply_func(self, messages=messages, sender=sender, config=reply_func_tuple["config"])
2905
+ if final:
2906
+ return reply
2907
+ return self._default_auto_reply
2908
+
2909
+ def _match_trigger(self, trigger: Union[None, str, type, Agent, Callable, list], sender: Optional[Agent]) -> bool:
2910
+ """Check if the sender matches the trigger.
2911
+
2912
+ Args:
2913
+ trigger (Union[None, str, type, Agent, Callable, List]): The condition to match against the sender.
2914
+ Can be `None`, string, type, `Agent` instance, callable, or a list of these.
2915
+ sender (Agent): The sender object or type to be matched against the trigger.
2916
+
2917
+ Returns:
2918
+ `True` if the sender matches the trigger, otherwise `False`.
2919
+
2920
+ Raises:
2921
+ ValueError: If the trigger type is unsupported.
2922
+ """
2923
+ if trigger is None:
2924
+ return sender is None
2925
+ elif isinstance(trigger, str):
2926
+ if sender is None:
2927
+ raise SenderRequiredError()
2928
+ return trigger == sender.name
2929
+ elif isinstance(trigger, type):
2930
+ return isinstance(sender, trigger)
2931
+ elif isinstance(trigger, Agent):
2932
+ # return True if the sender is the same type (class) as the trigger
2933
+ return trigger == sender
2934
+ elif isinstance(trigger, Callable):
2935
+ rst = trigger(sender)
2936
+ assert isinstance(rst, bool), f"trigger {trigger} must return a boolean value."
2937
+ return rst
2938
+ elif isinstance(trigger, list):
2939
+ return any(self._match_trigger(t, sender) for t in trigger)
2940
+ else:
2941
+ raise ValueError(f"Unsupported trigger type: {type(trigger)}")
2942
+
2943
+ def get_human_input(self, prompt: str) -> str:
2944
+ """Get human input.
2945
+
2946
+ Override this method to customize the way to get human input.
2947
+
2948
+ Args:
2949
+ prompt (str): prompt for the human input.
2950
+
2951
+ Returns:
2952
+ str: human input.
2953
+ """
2954
+ iostream = IOStream.get_default()
2955
+
2956
+ reply = iostream.input(prompt)
2957
+ self._human_input.append(reply)
2958
+ return reply
2959
+
2960
+ async def a_get_human_input(self, prompt: str) -> str:
2961
+ """(Async) Get human input.
2962
+
2963
+ Override this method to customize the way to get human input.
2964
+
2965
+ Args:
2966
+ prompt (str): prompt for the human input.
2967
+
2968
+ Returns:
2969
+ str: human input.
2970
+ """
2971
+ iostream = IOStream.get_default()
2972
+
2973
+ reply = await iostream.input(prompt)
2974
+ self._human_input.append(reply)
2975
+ return reply
2976
+
2977
+ # def _get_human_input(
2978
+ # self, iostream: IOStream, prompt: str,
2979
+ # ) -> tuple[bool, Optional[Union[str, dict[str, Any]]]]:
2980
+ # with IOStream.set_default(iostream):
2981
+ # print("!"*100)
2982
+ # print("Getting human input...")
2983
+ # return self.get_human_input(prompt)
2984
+
2985
+ # return await asyncio.get_event_loop().run_in_executor(
2986
+ # None,
2987
+ # functools.partial(
2988
+ # _get_human_input, self=self, iostream=iostream, prompt=prompt,
2989
+ # ),
2990
+ # )
2991
+
2992
+ def run_code(self, code: str, **kwargs: Any) -> tuple[int, str, Optional[str]]:
2993
+ """Run the code and return the result.
2994
+
2995
+ Override this function to modify the way to run the code.
2996
+
2997
+ Args:
2998
+ code (str): the code to be executed.
2999
+ **kwargs: other keyword arguments.
3000
+
3001
+ Returns:
3002
+ A tuple of (exitcode, logs, image).
3003
+ exitcode (int): the exit code of the code execution.
3004
+ logs (str): the logs of the code execution.
3005
+ image (str or None): the docker image used for the code execution.
3006
+ """
3007
+ return execute_code(code, **kwargs)
3008
+
3009
+ def execute_code_blocks(self, code_blocks):
3010
+ """Execute the code blocks and return the result."""
3011
+ iostream = IOStream.get_default()
3012
+
3013
+ logs_all = ""
3014
+ for i, code_block in enumerate(code_blocks):
3015
+ lang, code = code_block
3016
+ if not lang:
3017
+ lang = infer_lang(code)
3018
+
3019
+ iostream.send(ExecuteCodeBlockEvent(code=code, language=lang, code_block_count=i, recipient=self))
3020
+
3021
+ if lang in ["bash", "shell", "sh"]:
3022
+ exitcode, logs, image = self.run_code(code, lang=lang, **self._code_execution_config)
3023
+ elif lang in PYTHON_VARIANTS:
3024
+ filename = code[11 : code.find("\n")].strip() if code.startswith("# filename: ") else None
3025
+ exitcode, logs, image = self.run_code(
3026
+ code,
3027
+ lang="python",
3028
+ filename=filename,
3029
+ **self._code_execution_config,
3030
+ )
3031
+ else:
3032
+ # In case the language is not supported, we return an error message.
3033
+ exitcode, logs, image = (
3034
+ 1,
3035
+ f"unknown language {lang}",
3036
+ None,
3037
+ )
3038
+ # raise NotImplementedError
3039
+ if image is not None:
3040
+ self._code_execution_config["use_docker"] = image
3041
+ logs_all += "\n" + logs
3042
+ if exitcode != 0:
3043
+ return exitcode, logs_all
3044
+ return exitcode, logs_all
3045
+
3046
+ @staticmethod
3047
+ def _format_json_str(jstr):
3048
+ """Remove newlines outside of quotes, and handle JSON escape sequences.
3049
+
3050
+ 1. this function removes the newline in the query outside of quotes otherwise json.loads(s) will fail.
3051
+ Ex 1:
3052
+ "{\n"tool": "python",\n"query": "print('hello')\nprint('world')"\n}" -> "{"tool": "python","query": "print('hello')\nprint('world')"}"
3053
+ Ex 2:
3054
+ "{\n \"location\": \"Boston, MA\"\n}" -> "{"location": "Boston, MA"}"
3055
+
3056
+ 2. this function also handles JSON escape sequences inside quotes.
3057
+ Ex 1:
3058
+ '{"args": "a\na\na\ta"}' -> '{"args": "a\\na\\na\\ta"}'
3059
+ """
3060
+ result = []
3061
+ inside_quotes = False
3062
+ last_char = " "
3063
+ for char in jstr:
3064
+ if last_char != "\\" and char == '"':
3065
+ inside_quotes = not inside_quotes
3066
+ last_char = char
3067
+ if not inside_quotes and char == "\n":
3068
+ continue
3069
+ if inside_quotes and char == "\n":
3070
+ char = "\\n"
3071
+ if inside_quotes and char == "\t":
3072
+ char = "\\t"
3073
+ result.append(char)
3074
+ return "".join(result)
3075
+
3076
+ def execute_function(
3077
+ self, func_call: dict[str, Any], call_id: Optional[str] = None, verbose: bool = False
3078
+ ) -> tuple[bool, dict[str, Any]]:
3079
+ """Execute a function call and return the result.
3080
+
3081
+ Override this function to modify the way to execute function and tool calls.
3082
+
3083
+ Args:
3084
+ func_call: a dictionary extracted from openai message at "function_call" or "tool_calls" with keys "name" and "arguments".
3085
+ call_id: a string to identify the tool call.
3086
+ verbose (bool): Whether to send messages about the execution details to the
3087
+ output stream. When True, both the function call arguments and the execution
3088
+ result will be displayed. Defaults to False.
3089
+
3090
+
3091
+ Returns:
3092
+ A tuple of (is_exec_success, result_dict).
3093
+ is_exec_success (boolean): whether the execution is successful.
3094
+ result_dict: a dictionary with keys "name", "role", and "content". Value of "role" is "function".
3095
+
3096
+ "function_call" deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)
3097
+ See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call
3098
+ """
3099
+ iostream = IOStream.get_default()
3100
+
3101
+ func_name = func_call.get("name", "")
3102
+ func = self._function_map.get(func_name, None)
3103
+
3104
+ is_exec_success = False
3105
+ if func is not None:
3106
+ # Extract arguments from a json-like string and put it into a dict.
3107
+ input_string = self._format_json_str(func_call.get("arguments", "{}"))
3108
+ try:
3109
+ arguments = json.loads(input_string)
3110
+ except json.JSONDecodeError as e:
3111
+ arguments = None
3112
+ content = f"Error: {e}\n The argument must be in JSON format."
3113
+
3114
+ # Try to execute the function
3115
+ if arguments is not None:
3116
+ iostream.send(
3117
+ ExecuteFunctionEvent(func_name=func_name, call_id=call_id, arguments=arguments, recipient=self)
3118
+ )
3119
+ try:
3120
+ content = func(**arguments)
3121
+ is_exec_success = True
3122
+ except Exception as e:
3123
+ content = f"Error: {e}"
3124
+ else:
3125
+ arguments = {}
3126
+ content = f"Error: Function {func_name} not found."
3127
+
3128
+ iostream.send(
3129
+ ExecutedFunctionEvent(
3130
+ func_name=func_name,
3131
+ call_id=call_id,
3132
+ arguments=arguments,
3133
+ content=content,
3134
+ recipient=self,
3135
+ is_exec_success=is_exec_success,
3136
+ )
3137
+ )
3138
+
3139
+ return is_exec_success, {
3140
+ "name": func_name,
3141
+ "role": "function",
3142
+ "content": content,
3143
+ }
3144
+
3145
+ async def a_execute_function(
3146
+ self, func_call: dict[str, Any], call_id: Optional[str] = None, verbose: bool = False
3147
+ ) -> tuple[bool, dict[str, Any]]:
3148
+ """Execute an async function call and return the result.
3149
+
3150
+ Override this function to modify the way async functions and tools are executed.
3151
+
3152
+ Args:
3153
+ func_call: a dictionary extracted from openai message at key "function_call" or "tool_calls" with keys "name" and "arguments".
3154
+ call_id: a string to identify the tool call.
3155
+ verbose (bool): Whether to send messages about the execution details to the
3156
+ output stream. When True, both the function call arguments and the execution
3157
+ result will be displayed. Defaults to False.
3158
+
3159
+ Returns:
3160
+ A tuple of (is_exec_success, result_dict).
3161
+ is_exec_success (boolean): whether the execution is successful.
3162
+ result_dict: a dictionary with keys "name", "role", and "content". Value of "role" is "function".
3163
+
3164
+ "function_call" deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)
3165
+ See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call
3166
+ """
3167
+ iostream = IOStream.get_default()
3168
+
3169
+ func_name = func_call.get("name", "")
3170
+ func = self._function_map.get(func_name, None)
3171
+
3172
+ is_exec_success = False
3173
+ if func is not None:
3174
+ # Extract arguments from a json-like string and put it into a dict.
3175
+ input_string = self._format_json_str(func_call.get("arguments", "{}"))
3176
+ try:
3177
+ arguments = json.loads(input_string)
3178
+ except json.JSONDecodeError as e:
3179
+ arguments = None
3180
+ content = f"Error: {e}\n The argument must be in JSON format."
3181
+
3182
+ # Try to execute the function
3183
+ if arguments is not None:
3184
+ iostream.send(
3185
+ ExecuteFunctionEvent(func_name=func_name, call_id=call_id, arguments=arguments, recipient=self)
3186
+ )
3187
+ try:
3188
+ if inspect.iscoroutinefunction(func):
3189
+ content = await func(**arguments)
3190
+ else:
3191
+ # Fallback to sync function if the function is not async
3192
+ content = func(**arguments)
3193
+ is_exec_success = True
3194
+ except Exception as e:
3195
+ content = f"Error: {e}"
3196
+ else:
3197
+ arguments = {}
3198
+ content = f"Error: Function {func_name} not found."
3199
+
3200
+ iostream.send(
3201
+ ExecutedFunctionEvent(
3202
+ func_name=func_name,
3203
+ call_id=call_id,
3204
+ arguments=arguments,
3205
+ content=content,
3206
+ recipient=self,
3207
+ is_exec_success=is_exec_success,
3208
+ )
3209
+ )
3210
+
3211
+ return is_exec_success, {
3212
+ "name": func_name,
3213
+ "role": "function",
3214
+ "content": content,
3215
+ }
3216
+
3217
+ def generate_init_message(
3218
+ self, message: Optional[Union[dict[str, Any], str]], **kwargs: Any
3219
+ ) -> Union[str, dict[str, Any]]:
3220
+ """Generate the initial message for the agent.
3221
+ If message is None, input() will be called to get the initial message.
3222
+
3223
+ Args:
3224
+ message (str or None): the message to be processed.
3225
+ **kwargs: any additional information. It has the following reserved fields:
3226
+ "carryover": a string or a list of string to specify the carryover information to be passed to this chat. It can be a string or a list of string.
3227
+ If provided, we will combine this carryover with the "message" content when generating the initial chat
3228
+ message.
3229
+
3230
+ Returns:
3231
+ str or dict: the processed message.
3232
+ """
3233
+ if message is None:
3234
+ message = self.get_human_input(">")
3235
+
3236
+ return self._handle_carryover(message, kwargs)
3237
+
3238
+ def _handle_carryover(self, message: Union[str, dict[str, Any]], kwargs: dict) -> Union[str, dict[str, Any]]:
3239
+ if not kwargs.get("carryover"):
3240
+ return message
3241
+
3242
+ if isinstance(message, str):
3243
+ return self._process_carryover(message, kwargs)
3244
+
3245
+ elif isinstance(message, dict):
3246
+ if isinstance(message.get("content"), str):
3247
+ # Makes sure the original message is not mutated
3248
+ message = message.copy()
3249
+ message["content"] = self._process_carryover(message["content"], kwargs)
3250
+ elif isinstance(message.get("content"), list):
3251
+ # Makes sure the original message is not mutated
3252
+ message = message.copy()
3253
+ message["content"] = self._process_multimodal_carryover(message["content"], kwargs)
3254
+ else:
3255
+ raise InvalidCarryOverTypeError("Carryover should be a string or a list of strings.")
3256
+
3257
+ return message
3258
+
3259
+ def _process_carryover(self, content: str, kwargs: dict) -> str:
3260
+ # Makes sure there's a carryover
3261
+ if not kwargs.get("carryover"):
3262
+ return content
3263
+
3264
+ # if carryover is string
3265
+ if isinstance(kwargs["carryover"], str):
3266
+ content += "\nContext: \n" + kwargs["carryover"]
3267
+ elif isinstance(kwargs["carryover"], list):
3268
+ content += "\nContext: \n" + ("\n").join([_post_process_carryover_item(t) for t in kwargs["carryover"]])
3269
+ else:
3270
+ raise InvalidCarryOverTypeError(
3271
+ "Carryover should be a string or a list of strings. Not adding carryover to the message."
3272
+ )
3273
+ return content
3274
+
3275
+ def _process_multimodal_carryover(self, content: list[dict[str, Any]], kwargs: dict) -> list[dict[str, Any]]:
3276
+ """Prepends the context to a multimodal message."""
3277
+ # Makes sure there's a carryover
3278
+ if not kwargs.get("carryover"):
3279
+ return content
3280
+
3281
+ return [{"type": "text", "text": self._process_carryover("", kwargs)}] + content
3282
+
3283
+ async def a_generate_init_message(
3284
+ self, message: Optional[Union[dict[str, Any], str]], **kwargs: Any
3285
+ ) -> Union[str, dict[str, Any]]:
3286
+ """Generate the initial message for the agent.
3287
+ If message is None, input() will be called to get the initial message.
3288
+
3289
+ Args:
3290
+ message (str or None): the message to be processed.
3291
+ **kwargs: any additional information. It has the following reserved fields:
3292
+ "carryover": a string or a list of string to specify the carryover information to be passed to this chat. It can be a string or a list of string.
3293
+ If provided, we will combine this carryover with the "message" content when generating the initial chat
3294
+ message.
3295
+
3296
+ Returns:
3297
+ str or dict: the processed message.
3298
+ """
3299
+ if message is None:
3300
+ message = await self.a_get_human_input(">")
3301
+
3302
+ return self._handle_carryover(message, kwargs)
3303
+
3304
+ @property
3305
+ def tools(self) -> list[Tool]:
3306
+ """Get the agent's tools (registered for LLM)
3307
+
3308
+ Note this is a copy of the tools list, use add_tool and remove_tool to modify the tools list.
3309
+ """
3310
+ return self._tools.copy()
3311
+
3312
+ def remove_tool_for_llm(self, tool: Tool) -> None:
3313
+ """Remove a tool (register for LLM tool)"""
3314
+ try:
3315
+ self._register_for_llm(tool=tool, api_style="tool", is_remove=True)
3316
+ self._tools.remove(tool)
3317
+ except ValueError:
3318
+ raise ValueError(f"Tool {tool} not found in collection")
3319
+
3320
+ def register_function(self, function_map: dict[str, Union[Callable[..., Any]]], silent_override: bool = False):
3321
+ """Register functions to the agent.
3322
+
3323
+ Args:
3324
+ function_map: a dictionary mapping function names to functions. if function_map[name] is None, the function will be removed from the function_map.
3325
+ silent_override: whether to print warnings when overriding functions.
3326
+ """
3327
+ for name, func in function_map.items():
3328
+ self._assert_valid_name(name)
3329
+ if func is None and name not in self._function_map:
3330
+ warnings.warn(f"The function {name} to remove doesn't exist", name)
3331
+ if not silent_override and name in self._function_map:
3332
+ warnings.warn(f"Function '{name}' is being overridden.", UserWarning)
3333
+ self._function_map.update(function_map)
3334
+ self._function_map = {k: v for k, v in self._function_map.items() if v is not None}
3335
+
3336
+ def update_function_signature(
3337
+ self, func_sig: Union[str, dict[str, Any]], is_remove: None, silent_override: bool = False
3338
+ ):
3339
+ """Update a function_signature in the LLM configuration for function_call.
3340
+
3341
+ Args:
3342
+ func_sig (str or dict): description/name of the function to update/remove to the model. See: https://platform.openai.com/docs/api-reference/chat/create#chat/create-functions
3343
+ is_remove: whether removing the function from llm_config with name 'func_sig'
3344
+ silent_override: whether to print warnings when overriding functions.
3345
+
3346
+ Deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)
3347
+ See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call
3348
+ """
3349
+ if not isinstance(self.llm_config, (dict, LLMConfig)):
3350
+ error_msg = "To update a function signature, agent must have an llm_config"
3351
+ logger.error(error_msg)
3352
+ raise AssertionError(error_msg)
3353
+
3354
+ if is_remove:
3355
+ if "functions" not in self.llm_config or len(self.llm_config["functions"]) == 0:
3356
+ error_msg = f"The agent config doesn't have function {func_sig}."
3357
+ logger.error(error_msg)
3358
+ raise AssertionError(error_msg)
3359
+ else:
3360
+ self.llm_config["functions"] = [
3361
+ func for func in self.llm_config["functions"] if func["name"] != func_sig
3362
+ ]
3363
+ else:
3364
+ if not isinstance(func_sig, dict):
3365
+ raise ValueError(
3366
+ f"The function signature must be of the type dict. Received function signature type {type(func_sig)}"
3367
+ )
3368
+ if "name" not in func_sig:
3369
+ raise ValueError(f"The function signature must have a 'name' key. Received: {func_sig}")
3370
+ self._assert_valid_name(func_sig["name"]), func_sig
3371
+ if "functions" in self.llm_config:
3372
+ if not silent_override and any(
3373
+ func["name"] == func_sig["name"] for func in self.llm_config["functions"]
3374
+ ):
3375
+ warnings.warn(f"Function '{func_sig['name']}' is being overridden.", UserWarning)
3376
+
3377
+ self.llm_config["functions"] = [
3378
+ func for func in self.llm_config["functions"] if func.get("name") != func_sig["name"]
3379
+ ] + [func_sig]
3380
+ else:
3381
+ self.llm_config["functions"] = [func_sig]
3382
+
3383
+ # Do this only if llm_config is a dict. If llm_config is LLMConfig, LLMConfig will handle this.
3384
+ if len(self.llm_config["functions"]) == 0 and isinstance(self.llm_config, dict):
3385
+ del self.llm_config["functions"]
3386
+
3387
+ self.client = OpenAIWrapper(**self.llm_config)
3388
+
3389
+ def update_tool_signature(
3390
+ self, tool_sig: Union[str, dict[str, Any]], is_remove: bool, silent_override: bool = False
3391
+ ):
3392
+ """Update a tool_signature in the LLM configuration for tool_call.
3393
+
3394
+ Args:
3395
+ tool_sig (str or dict): description/name of the tool to update/remove to the model. See: https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools
3396
+ is_remove: whether removing the tool from llm_config with name 'tool_sig'
3397
+ silent_override: whether to print warnings when overriding functions.
3398
+ """
3399
+ if not self.llm_config:
3400
+ error_msg = "To update a tool signature, agent must have an llm_config"
3401
+ logger.error(error_msg)
3402
+ raise AssertionError(error_msg)
3403
+
3404
+ if is_remove:
3405
+ if "tools" not in self.llm_config or len(self.llm_config["tools"]) == 0:
3406
+ error_msg = f"The agent config doesn't have tool {tool_sig}."
3407
+ logger.error(error_msg)
3408
+ raise AssertionError(error_msg)
3409
+ else:
3410
+ current_tools = self.llm_config["tools"]
3411
+ filtered_tools = []
3412
+
3413
+ # Loop through and rebuild tools list without the tool to remove
3414
+ for tool in current_tools:
3415
+ tool_name = tool["function"]["name"]
3416
+
3417
+ # Match by tool name, or by tool signature
3418
+ is_different = tool_name != tool_sig if isinstance(tool_sig, str) else tool != tool_sig
3419
+
3420
+ if is_different:
3421
+ filtered_tools.append(tool)
3422
+
3423
+ self.llm_config["tools"] = filtered_tools
3424
+ else:
3425
+ if not isinstance(tool_sig, dict):
3426
+ raise ValueError(
3427
+ f"The tool signature must be of the type dict. Received tool signature type {type(tool_sig)}"
3428
+ )
3429
+ self._assert_valid_name(tool_sig["function"]["name"])
3430
+ if "tools" in self.llm_config and len(self.llm_config["tools"]) > 0:
3431
+ if not silent_override and any(
3432
+ tool["function"]["name"] == tool_sig["function"]["name"] for tool in self.llm_config["tools"]
3433
+ ):
3434
+ warnings.warn(f"Function '{tool_sig['function']['name']}' is being overridden.", UserWarning)
3435
+ self.llm_config["tools"] = [
3436
+ tool
3437
+ for tool in self.llm_config["tools"]
3438
+ if tool.get("function", {}).get("name") != tool_sig["function"]["name"]
3439
+ ] + [tool_sig]
3440
+ else:
3441
+ self.llm_config["tools"] = [tool_sig]
3442
+
3443
+ # Do this only if llm_config is a dict. If llm_config is LLMConfig, LLMConfig will handle this.
3444
+ if len(self.llm_config["tools"]) == 0 and isinstance(self.llm_config, dict):
3445
+ del self.llm_config["tools"]
3446
+
3447
+ self.client = OpenAIWrapper(**self.llm_config)
3448
+
3449
+ def can_execute_function(self, name: Union[list[str], str]) -> bool:
3450
+ """Whether the agent can execute the function."""
3451
+ names = name if isinstance(name, list) else [name]
3452
+ return all([n in self._function_map for n in names])
3453
+
3454
+ @property
3455
+ def function_map(self) -> dict[str, Callable[..., Any]]:
3456
+ """Return the function map."""
3457
+ return self._function_map
3458
+
3459
+ def _wrap_function(self, func: F, inject_params: dict[str, Any] = {}, *, serialize: bool = True) -> F:
3460
+ """Wrap the function inject chat context parameters and to dump the return value to json.
3461
+
3462
+ Handles both sync and async functions.
3463
+
3464
+ Args:
3465
+ func: the function to be wrapped.
3466
+ inject_params: the chat context parameters which will be passed to the function.
3467
+ serialize: whether to serialize the return value
3468
+
3469
+ Returns:
3470
+ The wrapped function.
3471
+ """
3472
+
3473
+ @load_basemodels_if_needed
3474
+ @functools.wraps(func)
3475
+ def _wrapped_func(*args, **kwargs):
3476
+ retval = func(*args, **kwargs, **inject_params)
3477
+ if logging_enabled():
3478
+ log_function_use(self, func, kwargs, retval)
3479
+ return serialize_to_str(retval) if serialize else retval
3480
+
3481
+ @load_basemodels_if_needed
3482
+ @functools.wraps(func)
3483
+ async def _a_wrapped_func(*args, **kwargs):
3484
+ retval = await func(*args, **kwargs, **inject_params)
3485
+ if logging_enabled():
3486
+ log_function_use(self, func, kwargs, retval)
3487
+ return serialize_to_str(retval) if serialize else retval
3488
+
3489
+ wrapped_func = _a_wrapped_func if inspect.iscoroutinefunction(func) else _wrapped_func
3490
+
3491
+ # needed for testing
3492
+ wrapped_func._origin = func
3493
+
3494
+ return wrapped_func
3495
+
3496
+ @staticmethod
3497
+ def _create_tool_if_needed(
3498
+ func_or_tool: Union[F, Tool],
3499
+ name: Optional[str],
3500
+ description: Optional[str],
3501
+ ) -> Tool:
3502
+ if isinstance(func_or_tool, Tool):
3503
+ tool: Tool = func_or_tool
3504
+ # create new tool object if name or description is not None
3505
+ if name or description:
3506
+ tool = Tool(func_or_tool=tool, name=name, description=description)
3507
+ elif inspect.isfunction(func_or_tool):
3508
+ function: Callable[..., Any] = func_or_tool
3509
+ tool = Tool(func_or_tool=function, name=name, description=description)
3510
+ else:
3511
+ raise TypeError(f"'func_or_tool' must be a function or a Tool object, got '{type(func_or_tool)}' instead.")
3512
+ return tool
3513
+
3514
+ def register_for_llm(
3515
+ self,
3516
+ *,
3517
+ name: Optional[str] = None,
3518
+ description: Optional[str] = None,
3519
+ api_style: Literal["function", "tool"] = "tool",
3520
+ silent_override: bool = False,
3521
+ ) -> Callable[[Union[F, Tool]], Tool]:
3522
+ """Decorator factory for registering a function to be used by an agent.
3523
+
3524
+ It's return value is used to decorate a function to be registered to the agent. The function uses type hints to
3525
+ specify the arguments and return type. The function name is used as the default name for the function,
3526
+ but a custom name can be provided. The function description is used to describe the function in the
3527
+ agent's configuration.
3528
+
3529
+ Args:
3530
+ name (optional(str)): name of the function. If None, the function name will be used (default: None).
3531
+ description (optional(str)): description of the function (default: None). It is mandatory
3532
+ for the initial decorator, but the following ones can omit it.
3533
+ api_style: (literal): the API style for function call.
3534
+ For Azure OpenAI API, use version 2023-12-01-preview or later.
3535
+ `"function"` style will be deprecated. For earlier version use
3536
+ `"function"` if `"tool"` doesn't work.
3537
+ See [Azure OpenAI documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/function-calling?tabs=python) for details.
3538
+ silent_override (bool): whether to suppress any override warning messages.
3539
+
3540
+ Returns:
3541
+ The decorator for registering a function to be used by an agent.
3542
+
3543
+ Examples:
3544
+ ```
3545
+ @user_proxy.register_for_execution()
3546
+ @agent2.register_for_llm()
3547
+ @agent1.register_for_llm(description="This is a very useful function")
3548
+ def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14) -> str:
3549
+ return a + str(b * c)
3550
+ ```
3551
+
3552
+ For Azure OpenAI versions prior to 2023-12-01-preview, set `api_style`
3553
+ to `"function"` if `"tool"` doesn't work:
3554
+ ```
3555
+ @agent2.register_for_llm(api_style="function")
3556
+ def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14) -> str:
3557
+ return a + str(b * c)
3558
+ ```
3559
+
3560
+ """
3561
+
3562
+ def _decorator(
3563
+ func_or_tool: Union[F, Tool], name: Optional[str] = name, description: Optional[str] = description
3564
+ ) -> Tool:
3565
+ """Decorator for registering a function to be used by an agent.
3566
+
3567
+ Args:
3568
+ func_or_tool: The function or the tool to be registered.
3569
+ name: The name of the function or the tool.
3570
+ description: The description of the function or the tool.
3571
+
3572
+ Returns:
3573
+ The function to be registered, with the _description attribute set to the function description.
3574
+
3575
+ Raises:
3576
+ ValueError: if the function description is not provided and not propagated by a previous decorator.
3577
+ RuntimeError: if the LLM config is not set up before registering a function.
3578
+
3579
+ """
3580
+ tool = self._create_tool_if_needed(func_or_tool, name, description)
3581
+
3582
+ self._register_for_llm(tool, api_style, silent_override=silent_override)
3583
+ if tool not in self._tools:
3584
+ self._tools.append(tool)
3585
+
3586
+ return tool
3587
+
3588
+ return _decorator
3589
+
3590
+ def _register_for_llm(
3591
+ self, tool: Tool, api_style: Literal["tool", "function"], is_remove: bool = False, silent_override: bool = False
3592
+ ) -> None:
3593
+ """
3594
+ Register a tool for LLM.
3595
+
3596
+ Args:
3597
+ tool: the tool to be registered.
3598
+ api_style: the API style for function call ("tool" or "function").
3599
+ is_remove: whether to remove the function or tool.
3600
+ silent_override: whether to suppress any override warning messages.
3601
+
3602
+ Returns:
3603
+ None
3604
+ """
3605
+ # register the function to the agent if there is LLM config, raise an exception otherwise
3606
+ if self.llm_config is None:
3607
+ raise RuntimeError("LLM config must be setup before registering a function for LLM.")
3608
+
3609
+ if api_style == "function":
3610
+ self.update_function_signature(tool.function_schema, is_remove=is_remove, silent_override=silent_override)
3611
+ elif api_style == "tool":
3612
+ self.update_tool_signature(tool.tool_schema, is_remove=is_remove, silent_override=silent_override)
3613
+ else:
3614
+ raise ValueError(f"Unsupported API style: {api_style}")
3615
+
3616
+ def set_ui_tools(self, tools: list[Tool]) -> None:
3617
+ """Set the UI tools for the agent.
3618
+
3619
+ Args:
3620
+ tools: a list of tools to be set.
3621
+ """
3622
+ # Unset the previous UI tools
3623
+ self._unset_previous_ui_tools()
3624
+
3625
+ # Set the new UI tools
3626
+ for tool in tools:
3627
+ # Register the tool for LLM
3628
+ self._register_for_llm(tool, api_style="tool", silent_override=True)
3629
+ if tool not in self._tools:
3630
+ self._tools.append(tool)
3631
+
3632
+ # Register for execution
3633
+ self.register_for_execution(serialize=False, silent_override=True)(tool)
3634
+
3635
+ # Set the current UI tools
3636
+ self._ui_tools = tools
3637
+
3638
+ def unset_ui_tools(self, tools: list[Tool]) -> None:
3639
+ """Unset the UI tools for the agent.
3640
+
3641
+ Args:
3642
+ tools: a list of tools to be unset.
3643
+ """
3644
+ for tool in tools:
3645
+ self.remove_tool_for_llm(tool)
3646
+
3647
+ def _unset_previous_ui_tools(self) -> None:
3648
+ """Unset the previous UI tools for the agent.
3649
+
3650
+ This is used to remove UI tools that were previously registered for LLM.
3651
+ """
3652
+ self.unset_ui_tools(self._ui_tools)
3653
+ for tool in self._ui_tools:
3654
+ if tool in self._tools:
3655
+ self._tools.remove(tool)
3656
+
3657
+ # Unregister the function from the function map
3658
+ if tool.name in self._function_map:
3659
+ del self._function_map[tool.name]
3660
+
3661
+ self._ui_tools = []
3662
+
3663
+ def register_for_execution(
3664
+ self,
3665
+ name: Optional[str] = None,
3666
+ description: Optional[str] = None,
3667
+ *,
3668
+ serialize: bool = True,
3669
+ silent_override: bool = False,
3670
+ ) -> Callable[[Union[Tool, F]], Tool]:
3671
+ """Decorator factory for registering a function to be executed by an agent.
3672
+
3673
+ It's return value is used to decorate a function to be registered to the agent.
3674
+
3675
+ Args:
3676
+ name: name of the function. If None, the function name will be used (default: None).
3677
+ description: description of the function (default: None).
3678
+ serialize: whether to serialize the return value
3679
+ silent_override: whether to suppress any override warning messages
3680
+
3681
+ Returns:
3682
+ The decorator for registering a function to be used by an agent.
3683
+
3684
+ Examples:
3685
+ ```
3686
+ @user_proxy.register_for_execution()
3687
+ @agent2.register_for_llm()
3688
+ @agent1.register_for_llm(description="This is a very useful function")
3689
+ def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14):
3690
+ return a + str(b * c)
3691
+ ```
3692
+
3693
+ """
3694
+
3695
+ def _decorator(
3696
+ func_or_tool: Union[Tool, F], name: Optional[str] = name, description: Optional[str] = description
3697
+ ) -> Tool:
3698
+ """Decorator for registering a function to be used by an agent.
3699
+
3700
+ Args:
3701
+ func_or_tool: the function or the tool to be registered.
3702
+ name: the name of the function.
3703
+ description: the description of the function.
3704
+
3705
+ Returns:
3706
+ The tool to be registered.
3707
+
3708
+ """
3709
+
3710
+ tool = self._create_tool_if_needed(func_or_tool, name, description)
3711
+ chat_context = ChatContext(self)
3712
+ chat_context_params = {param: chat_context for param in tool._chat_context_param_names}
3713
+
3714
+ self.register_function(
3715
+ {tool.name: self._wrap_function(tool.func, chat_context_params, serialize=serialize)},
3716
+ silent_override=silent_override,
3717
+ )
3718
+
3719
+ return tool
3720
+
3721
+ return _decorator
3722
+
3723
+ def register_model_client(self, model_client_cls: ModelClient, **kwargs: Any):
3724
+ """Register a model client.
3725
+
3726
+ Args:
3727
+ model_client_cls: A custom client class that follows the Client interface
3728
+ **kwargs: The kwargs for the custom client class to be initialized with
3729
+ """
3730
+ self.client.register_model_client(model_client_cls, **kwargs)
3731
+
3732
+ def register_hook(self, hookable_method: str, hook: Callable):
3733
+ """Registers a hook to be called by a hookable method, in order to add a capability to the agent.
3734
+ Registered hooks are kept in lists (one per hookable method), and are called in their order of registration.
3735
+
3736
+ Args:
3737
+ hookable_method: A hookable method name implemented by ConversableAgent.
3738
+ hook: A method implemented by a subclass of AgentCapability.
3739
+ """
3740
+ assert hookable_method in self.hook_lists, f"{hookable_method} is not a hookable method."
3741
+ hook_list = self.hook_lists[hookable_method]
3742
+ assert hook not in hook_list, f"{hook} is already registered as a hook."
3743
+ hook_list.append(hook)
3744
+
3745
+ def update_agent_state_before_reply(self, messages: list[dict[str, Any]]) -> None:
3746
+ """Calls any registered capability hooks to update the agent's state.
3747
+ Primarily used to update context variables.
3748
+ Will, potentially, modify the messages.
3749
+ """
3750
+ hook_list = self.hook_lists["update_agent_state"]
3751
+
3752
+ # Call each hook (in order of registration) to process the messages.
3753
+ for hook in hook_list:
3754
+ hook(self, messages)
3755
+
3756
+ def process_all_messages_before_reply(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
3757
+ """Calls any registered capability hooks to process all messages, potentially modifying the messages."""
3758
+ hook_list = self.hook_lists["process_all_messages_before_reply"]
3759
+ # If no hooks are registered, or if there are no messages to process, return the original message list.
3760
+ if len(hook_list) == 0 or messages is None:
3761
+ return messages
3762
+
3763
+ # Call each hook (in order of registration) to process the messages.
3764
+ processed_messages = messages
3765
+ for hook in hook_list:
3766
+ processed_messages = hook(processed_messages)
3767
+ return processed_messages
3768
+
3769
+ def process_last_received_message(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
3770
+ """Calls any registered capability hooks to use and potentially modify the text of the last message,
3771
+ as long as the last message is not a function call or exit command.
3772
+ """
3773
+ # If any required condition is not met, return the original message list.
3774
+ hook_list = self.hook_lists["process_last_received_message"]
3775
+ if len(hook_list) == 0:
3776
+ return messages # No hooks registered.
3777
+ if messages is None:
3778
+ return None # No message to process.
3779
+ if len(messages) == 0:
3780
+ return messages # No message to process.
3781
+ last_message = messages[-1]
3782
+ if "function_call" in last_message:
3783
+ return messages # Last message is a function call.
3784
+ if "context" in last_message:
3785
+ return messages # Last message contains a context key.
3786
+ if "content" not in last_message:
3787
+ return messages # Last message has no content.
3788
+
3789
+ user_content = last_message["content"]
3790
+ if not isinstance(user_content, str) and not isinstance(user_content, list):
3791
+ # if the user_content is a string, it is for regular LLM
3792
+ # if the user_content is a list, it should follow the multimodal LMM format.
3793
+ return messages
3794
+ if user_content == "exit":
3795
+ return messages # Last message is an exit command.
3796
+
3797
+ # Call each hook (in order of registration) to process the user's message.
3798
+ processed_user_content = user_content
3799
+ for hook in hook_list:
3800
+ processed_user_content = hook(processed_user_content)
3801
+
3802
+ if processed_user_content == user_content:
3803
+ return messages # No hooks actually modified the user's message.
3804
+
3805
+ # Replace the last user message with the expanded one.
3806
+ messages = messages.copy()
3807
+ messages[-1]["content"] = processed_user_content
3808
+ return messages
3809
+
3810
+ def print_usage_summary(self, mode: Union[str, list[str]] = ["actual", "total"]) -> None:
3811
+ """Print the usage summary."""
3812
+ iostream = IOStream.get_default()
3813
+ if self.client is None:
3814
+ iostream.send(ConversableAgentUsageSummaryNoCostIncurredEvent(recipient=self))
3815
+ else:
3816
+ iostream.send(ConversableAgentUsageSummaryEvent(recipient=self))
3817
+
3818
+ if self.client is not None:
3819
+ self.client.print_usage_summary(mode)
3820
+
3821
+ def get_actual_usage(self) -> Union[None, dict[str, int]]:
3822
+ """Get the actual usage summary."""
3823
+ if self.client is None:
3824
+ return None
3825
+ else:
3826
+ return self.client.actual_usage_summary
3827
+
3828
+ def get_total_usage(self) -> Union[None, dict[str, int]]:
3829
+ """Get the total usage summary."""
3830
+ if self.client is None:
3831
+ return None
3832
+ else:
3833
+ return self.client.total_usage_summary
3834
+
3835
+ @contextmanager
3836
+ def _create_or_get_executor(
3837
+ self,
3838
+ executor_kwargs: Optional[dict[str, Any]] = None,
3839
+ tools: Optional[Union[Tool, Iterable[Tool]]] = None,
3840
+ agent_name: str = "executor",
3841
+ agent_human_input_mode: str = "NEVER",
3842
+ ) -> Generator["ConversableAgent", None, None]:
3843
+ """Creates a user proxy / tool executor agent.
3844
+
3845
+ Note: Code execution is not enabled by default. Pass the code execution config into executor_kwargs, if needed.
3846
+
3847
+ Args:
3848
+ executor_kwargs: agent's arguments.
3849
+ tools: tools to register for execution with the agent.
3850
+ agent_name: agent's name, defaults to 'executor'.
3851
+ agent_human_input_mode: agent's human input mode, defaults to 'NEVER'.
3852
+ """
3853
+ if executor_kwargs is None:
3854
+ executor_kwargs = {}
3855
+ if "is_termination_msg" not in executor_kwargs:
3856
+ executor_kwargs["is_termination_msg"] = lambda x: (x["content"] is not None) and "TERMINATE" in x["content"]
3857
+
3858
+ try:
3859
+ if not self.run_executor:
3860
+ self.run_executor = ConversableAgent(
3861
+ name=agent_name,
3862
+ human_input_mode=agent_human_input_mode,
3863
+ **executor_kwargs,
3864
+ )
3865
+
3866
+ tools = [] if tools is None else tools
3867
+ tools = [tools] if isinstance(tools, Tool) else tools
3868
+ for tool in tools:
3869
+ tool.register_for_execution(self.run_executor)
3870
+ tool.register_for_llm(self)
3871
+ yield self.run_executor
3872
+ finally:
3873
+ if tools is not None:
3874
+ for tool in tools:
3875
+ self.update_tool_signature(tool_sig=tool.tool_schema["function"]["name"], is_remove=True)
3876
+
3877
+ def _deprecated_run(
3878
+ self,
3879
+ message: str,
3880
+ *,
3881
+ tools: Optional[Union[Tool, Iterable[Tool]]] = None,
3882
+ executor_kwargs: Optional[dict[str, Any]] = None,
3883
+ max_turns: Optional[int] = None,
3884
+ msg_to: Literal["agent", "user"] = "agent",
3885
+ clear_history: bool = False,
3886
+ user_input: bool = True,
3887
+ summary_method: Optional[Union[str, Callable[..., Any]]] = DEFAULT_SUMMARY_METHOD,
3888
+ ) -> ChatResult:
3889
+ """Run a chat with the agent using the given message.
3890
+
3891
+ A second agent will be created to represent the user, this agent will by known by the name 'user'. This agent does not have code execution enabled by default, if needed pass the code execution config in with the executor_kwargs parameter.
3892
+
3893
+ The user can terminate the conversation when prompted or, if agent's reply contains 'TERMINATE', it will terminate.
3894
+
3895
+ Args:
3896
+ message: the message to be processed.
3897
+ tools: the tools to be used by the agent.
3898
+ executor_kwargs: the keyword arguments for the executor.
3899
+ max_turns: maximum number of turns (a turn is equivalent to both agents having replied), defaults no None which means unlimited. The original message is included.
3900
+ msg_to: which agent is receiving the message and will be the first to reply, defaults to the agent.
3901
+ clear_history: whether to clear the chat history.
3902
+ user_input: the user will be asked for input at their turn.
3903
+ summary_method: the method to summarize the chat.
3904
+ """
3905
+ with self._create_or_get_executor(
3906
+ executor_kwargs=executor_kwargs,
3907
+ tools=tools,
3908
+ agent_name="user",
3909
+ agent_human_input_mode="ALWAYS" if user_input else "NEVER",
3910
+ ) as executor:
3911
+ if msg_to == "agent":
3912
+ return executor.initiate_chat(
3913
+ self,
3914
+ message=message,
3915
+ clear_history=clear_history,
3916
+ max_turns=max_turns,
3917
+ summary_method=summary_method,
3918
+ )
3919
+ else:
3920
+ return self.initiate_chat(
3921
+ executor,
3922
+ message=message,
3923
+ clear_history=clear_history,
3924
+ max_turns=max_turns,
3925
+ summary_method=summary_method,
3926
+ )
3927
+
3928
+ async def _deprecated_a_run(
3929
+ self,
3930
+ message: str,
3931
+ *,
3932
+ tools: Optional[Union[Tool, Iterable[Tool]]] = None,
3933
+ executor_kwargs: Optional[dict[str, Any]] = None,
3934
+ max_turns: Optional[int] = None,
3935
+ msg_to: Literal["agent", "user"] = "agent",
3936
+ clear_history: bool = False,
3937
+ user_input: bool = True,
3938
+ summary_method: Optional[Union[str, Callable[..., Any]]] = DEFAULT_SUMMARY_METHOD,
3939
+ ) -> ChatResult:
3940
+ """Run a chat asynchronously with the agent using the given message.
3941
+
3942
+ A second agent will be created to represent the user, this agent will by known by the name 'user'.
3943
+
3944
+ The user can terminate the conversation when prompted or, if agent's reply contains 'TERMINATE', it will terminate.
3945
+
3946
+ Args:
3947
+ message: the message to be processed.
3948
+ tools: the tools to be used by the agent.
3949
+ executor_kwargs: the keyword arguments for the executor.
3950
+ max_turns: maximum number of turns (a turn is equivalent to both agents having replied), defaults no None which means unlimited. The original message is included.
3951
+ msg_to: which agent is receiving the message and will be the first to reply, defaults to the agent.
3952
+ clear_history: whether to clear the chat history.
3953
+ user_input: the user will be asked for input at their turn.
3954
+ summary_method: the method to summarize the chat.
3955
+ """
3956
+ with self._create_or_get_executor(
3957
+ executor_kwargs=executor_kwargs,
3958
+ tools=tools,
3959
+ agent_name="user",
3960
+ agent_human_input_mode="ALWAYS" if user_input else "NEVER",
3961
+ ) as executor:
3962
+ if msg_to == "agent":
3963
+ return await executor.a_initiate_chat(
3964
+ self,
3965
+ message=message,
3966
+ clear_history=clear_history,
3967
+ max_turns=max_turns,
3968
+ summary_method=summary_method,
3969
+ )
3970
+ else:
3971
+ return await self.a_initiate_chat(
3972
+ executor,
3973
+ message=message,
3974
+ clear_history=clear_history,
3975
+ max_turns=max_turns,
3976
+ summary_method=summary_method,
3977
+ )
3978
+
3979
+ def register_handoff(self, condition: Union["OnContextCondition", "OnCondition"]) -> None:
3980
+ """
3981
+ Register a single handoff condition (OnContextCondition or OnCondition).
3982
+
3983
+ Args:
3984
+ condition: The condition to add (OnContextCondition, OnCondition)
3985
+ """
3986
+ self.handoffs.add(condition)
3987
+
3988
+ def register_handoffs(self, conditions: list[Union["OnContextCondition", "OnCondition"]]) -> None:
3989
+ """
3990
+ Register multiple handoff conditions (OnContextCondition or OnCondition).
3991
+
3992
+ Args:
3993
+ conditions: List of conditions to add
3994
+ """
3995
+ self.handoffs.add_many(conditions)
3996
+
3997
+
3998
+ @export_module("autogen")
3999
+ def register_function(
4000
+ f: Callable[..., Any],
4001
+ *,
4002
+ caller: ConversableAgent,
4003
+ executor: ConversableAgent,
4004
+ name: Optional[str] = None,
4005
+ description: str,
4006
+ ) -> None:
4007
+ """Register a function to be proposed by an agent and executed for an executor.
4008
+
4009
+ This function can be used instead of function decorators `@ConversationAgent.register_for_llm` and
4010
+ `@ConversationAgent.register_for_execution`.
4011
+
4012
+ Args:
4013
+ f: the function to be registered.
4014
+ caller: the agent calling the function, typically an instance of ConversableAgent.
4015
+ executor: the agent executing the function, typically an instance of UserProxy.
4016
+ name: name of the function. If None, the function name will be used (default: None).
4017
+ description: description of the function. The description is used by LLM to decode whether the function
4018
+ is called. Make sure the description is properly describing what the function does or it might not be
4019
+ called by LLM when needed.
4020
+
4021
+ """
4022
+ f = caller.register_for_llm(name=name, description=description)(f)
4023
+ executor.register_for_execution(name=name)(f)