ag2 0.9.1a1__py3-none-any.whl → 0.9.1.post0__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 (357) hide show
  1. {ag2-0.9.1a1.dist-info → ag2-0.9.1.post0.dist-info}/METADATA +264 -73
  2. ag2-0.9.1.post0.dist-info/RECORD +392 -0
  3. {ag2-0.9.1a1.dist-info → ag2-0.9.1.post0.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 +4020 -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 +1010 -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 +113 -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 +379 -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/mcp_client.py +208 -0
  277. autogen/messages/__init__.py +7 -0
  278. autogen/messages/agent_messages.py +948 -0
  279. autogen/messages/base_message.py +107 -0
  280. autogen/messages/client_messages.py +171 -0
  281. autogen/messages/print_message.py +49 -0
  282. autogen/oai/__init__.py +53 -0
  283. autogen/oai/anthropic.py +714 -0
  284. autogen/oai/bedrock.py +628 -0
  285. autogen/oai/cerebras.py +299 -0
  286. autogen/oai/client.py +1435 -0
  287. autogen/oai/client_utils.py +169 -0
  288. autogen/oai/cohere.py +479 -0
  289. autogen/oai/gemini.py +990 -0
  290. autogen/oai/gemini_types.py +129 -0
  291. autogen/oai/groq.py +305 -0
  292. autogen/oai/mistral.py +303 -0
  293. autogen/oai/oai_models/__init__.py +11 -0
  294. autogen/oai/oai_models/_models.py +16 -0
  295. autogen/oai/oai_models/chat_completion.py +87 -0
  296. autogen/oai/oai_models/chat_completion_audio.py +32 -0
  297. autogen/oai/oai_models/chat_completion_message.py +86 -0
  298. autogen/oai/oai_models/chat_completion_message_tool_call.py +37 -0
  299. autogen/oai/oai_models/chat_completion_token_logprob.py +63 -0
  300. autogen/oai/oai_models/completion_usage.py +60 -0
  301. autogen/oai/ollama.py +643 -0
  302. autogen/oai/openai_utils.py +881 -0
  303. autogen/oai/together.py +370 -0
  304. autogen/retrieve_utils.py +491 -0
  305. autogen/runtime_logging.py +160 -0
  306. autogen/token_count_utils.py +267 -0
  307. autogen/tools/__init__.py +20 -0
  308. autogen/tools/contrib/__init__.py +9 -0
  309. autogen/tools/contrib/time/__init__.py +7 -0
  310. autogen/tools/contrib/time/time.py +41 -0
  311. autogen/tools/dependency_injection.py +254 -0
  312. autogen/tools/experimental/__init__.py +43 -0
  313. autogen/tools/experimental/browser_use/__init__.py +7 -0
  314. autogen/tools/experimental/browser_use/browser_use.py +161 -0
  315. autogen/tools/experimental/crawl4ai/__init__.py +7 -0
  316. autogen/tools/experimental/crawl4ai/crawl4ai.py +153 -0
  317. autogen/tools/experimental/deep_research/__init__.py +7 -0
  318. autogen/tools/experimental/deep_research/deep_research.py +328 -0
  319. autogen/tools/experimental/duckduckgo/__init__.py +7 -0
  320. autogen/tools/experimental/duckduckgo/duckduckgo_search.py +109 -0
  321. autogen/tools/experimental/google/__init__.py +14 -0
  322. autogen/tools/experimental/google/authentication/__init__.py +11 -0
  323. autogen/tools/experimental/google/authentication/credentials_hosted_provider.py +43 -0
  324. autogen/tools/experimental/google/authentication/credentials_local_provider.py +91 -0
  325. autogen/tools/experimental/google/authentication/credentials_provider.py +35 -0
  326. autogen/tools/experimental/google/drive/__init__.py +9 -0
  327. autogen/tools/experimental/google/drive/drive_functions.py +124 -0
  328. autogen/tools/experimental/google/drive/toolkit.py +88 -0
  329. autogen/tools/experimental/google/model.py +17 -0
  330. autogen/tools/experimental/google/toolkit_protocol.py +19 -0
  331. autogen/tools/experimental/google_search/__init__.py +8 -0
  332. autogen/tools/experimental/google_search/google_search.py +93 -0
  333. autogen/tools/experimental/google_search/youtube_search.py +181 -0
  334. autogen/tools/experimental/messageplatform/__init__.py +17 -0
  335. autogen/tools/experimental/messageplatform/discord/__init__.py +7 -0
  336. autogen/tools/experimental/messageplatform/discord/discord.py +288 -0
  337. autogen/tools/experimental/messageplatform/slack/__init__.py +7 -0
  338. autogen/tools/experimental/messageplatform/slack/slack.py +391 -0
  339. autogen/tools/experimental/messageplatform/telegram/__init__.py +7 -0
  340. autogen/tools/experimental/messageplatform/telegram/telegram.py +275 -0
  341. autogen/tools/experimental/perplexity/__init__.py +7 -0
  342. autogen/tools/experimental/perplexity/perplexity_search.py +260 -0
  343. autogen/tools/experimental/tavily/__init__.py +7 -0
  344. autogen/tools/experimental/tavily/tavily_search.py +183 -0
  345. autogen/tools/experimental/web_search_preview/__init__.py +7 -0
  346. autogen/tools/experimental/web_search_preview/web_search_preview.py +114 -0
  347. autogen/tools/experimental/wikipedia/__init__.py +7 -0
  348. autogen/tools/experimental/wikipedia/wikipedia.py +287 -0
  349. autogen/tools/function_utils.py +411 -0
  350. autogen/tools/tool.py +187 -0
  351. autogen/tools/toolkit.py +86 -0
  352. autogen/types.py +29 -0
  353. autogen/version.py +7 -0
  354. ag2-0.9.1a1.dist-info/RECORD +0 -6
  355. ag2-0.9.1a1.dist-info/top_level.txt +0 -1
  356. {ag2-0.9.1a1.dist-info → ag2-0.9.1.post0.dist-info/licenses}/LICENSE +0 -0
  357. {ag2-0.9.1a1.dist-info → ag2-0.9.1.post0.dist-info/licenses}/NOTICE.md +0 -0
@@ -0,0 +1,881 @@
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
+
8
+ import importlib
9
+ import importlib.metadata
10
+ import inspect
11
+ import json
12
+ import logging
13
+ import os
14
+ import re
15
+ import tempfile
16
+ import time
17
+ import warnings
18
+ from copy import deepcopy
19
+ from pathlib import Path
20
+ from typing import TYPE_CHECKING, Any, Optional, Union
21
+
22
+ from dotenv import find_dotenv, load_dotenv
23
+ from packaging.version import parse
24
+ from pydantic_core import to_jsonable_python
25
+
26
+ if TYPE_CHECKING:
27
+ from openai import OpenAI
28
+ from openai.types.beta.assistant import Assistant
29
+
30
+ from ..doc_utils import export_module
31
+ from ..llm_config import LLMConfig
32
+
33
+ NON_CACHE_KEY = [
34
+ "api_key",
35
+ "base_url",
36
+ "api_type",
37
+ "api_version",
38
+ "azure_ad_token",
39
+ "azure_ad_token_provider",
40
+ "credentials",
41
+ ]
42
+ DEFAULT_AZURE_API_VERSION = "2024-02-01"
43
+
44
+ # The below pricing is for 1K tokens. Whenever there is an update in the LLM's pricing,
45
+ # Please convert it to 1K tokens and update in the below dictionary in the format: (input_token_price, output_token_price).
46
+ OAI_PRICE1K = {
47
+ # https://openai.com/api/pricing/
48
+ # o1
49
+ "o1-preview-2024-09-12": (0.0015, 0.0060),
50
+ "o1-preview": (0.0015, 0.0060),
51
+ "o1-mini-2024-09-12": (0.0003, 0.0012),
52
+ "o1-mini": (0.0003, 0.0012),
53
+ "o1": (0.0015, 0.0060),
54
+ "o1-2024-12-17": (0.0015, 0.0060),
55
+ # o1 pro
56
+ "o1-pro": (0.15, 0.6), # $150 / $600!
57
+ "o1-pro-2025-03-19": (0.15, 0.6),
58
+ # o3
59
+ "o3": (0.0011, 0.0044),
60
+ "o3-mini-2025-01-31": (0.0011, 0.0044),
61
+ # gpt-4o
62
+ "gpt-4o": (0.005, 0.015),
63
+ "gpt-4o-2024-05-13": (0.005, 0.015),
64
+ "gpt-4o-2024-08-06": (0.0025, 0.01),
65
+ "gpt-4o-2024-11-20": (0.0025, 0.01),
66
+ # gpt-4o-mini
67
+ "gpt-4o-mini": (0.000150, 0.000600),
68
+ "gpt-4o-mini-2024-07-18": (0.000150, 0.000600),
69
+ # gpt-4-turbo
70
+ "gpt-4-turbo-2024-04-09": (0.01, 0.03),
71
+ # gpt-4
72
+ "gpt-4": (0.03, 0.06),
73
+ "gpt-4-32k": (0.06, 0.12),
74
+ # gpt-4.1
75
+ "gpt-4.1": (0.002, 0.008),
76
+ "gpt-4.1-2025-04-14": (0.002, 0.008),
77
+ # gpt-4.1 mini
78
+ "gpt-4.1-mini": (0.0004, 0.0016),
79
+ "gpt-4.1-mini-2025-04-14": (0.0004, 0.0016),
80
+ # gpt-4.1 nano
81
+ "gpt-4.1-nano": (0.0001, 0.0004),
82
+ "gpt-4.1-nano-2025-04-14": (0.0001, 0.0004),
83
+ # gpt-3.5 turbo
84
+ "gpt-3.5-turbo": (0.0005, 0.0015), # default is 0125
85
+ "gpt-3.5-turbo-0125": (0.0005, 0.0015), # 16k
86
+ "gpt-3.5-turbo-instruct": (0.0015, 0.002),
87
+ # base model
88
+ "davinci-002": 0.002,
89
+ "babbage-002": 0.0004,
90
+ # old model
91
+ "gpt-4-0125-preview": (0.01, 0.03),
92
+ "gpt-4-1106-preview": (0.01, 0.03),
93
+ "gpt-4-1106-vision-preview": (0.01, 0.03), # TODO: support vision pricing of images
94
+ "gpt-3.5-turbo-1106": (0.001, 0.002),
95
+ "gpt-3.5-turbo-0613": (0.0015, 0.002),
96
+ # "gpt-3.5-turbo-16k": (0.003, 0.004),
97
+ "gpt-3.5-turbo-16k-0613": (0.003, 0.004),
98
+ "gpt-3.5-turbo-0301": (0.0015, 0.002),
99
+ "text-ada-001": 0.0004,
100
+ "text-babbage-001": 0.0005,
101
+ "text-curie-001": 0.002,
102
+ "code-cushman-001": 0.024,
103
+ "code-davinci-002": 0.1,
104
+ "text-davinci-002": 0.02,
105
+ "text-davinci-003": 0.02,
106
+ "gpt-4-0314": (0.03, 0.06), # deprecate in Sep
107
+ "gpt-4-32k-0314": (0.06, 0.12), # deprecate in Sep
108
+ "gpt-4-0613": (0.03, 0.06),
109
+ "gpt-4-32k-0613": (0.06, 0.12),
110
+ "gpt-4-turbo-preview": (0.01, 0.03),
111
+ # https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/#pricing
112
+ "gpt-35-turbo": (0.0005, 0.0015), # what's the default? using 0125 here.
113
+ "gpt-35-turbo-0125": (0.0005, 0.0015),
114
+ "gpt-35-turbo-instruct": (0.0015, 0.002),
115
+ "gpt-35-turbo-1106": (0.001, 0.002),
116
+ "gpt-35-turbo-0613": (0.0015, 0.002),
117
+ "gpt-35-turbo-0301": (0.0015, 0.002),
118
+ "gpt-35-turbo-16k": (0.003, 0.004),
119
+ "gpt-35-turbo-16k-0613": (0.003, 0.004),
120
+ # deepseek
121
+ "deepseek-chat": (0.00027, 0.0011),
122
+ }
123
+
124
+
125
+ def get_key(config: dict[str, Any]) -> str:
126
+ """Get a unique identifier of a configuration.
127
+
128
+ Args:
129
+ config (dict or list): A configuration.
130
+
131
+ Returns:
132
+ tuple: A unique identifier which can be used as a key for a dict.
133
+ """
134
+ copied = False
135
+ for key in NON_CACHE_KEY:
136
+ if key in config:
137
+ config, copied = config.copy() if not copied else config, True
138
+ config.pop(key)
139
+ return to_jsonable_python(config) # type: ignore [no-any-return]
140
+
141
+
142
+ def is_valid_api_key(api_key: str) -> bool:
143
+ """Determine if input is valid OpenAI API key. As of 2024-09-24 there's no official definition of the key structure
144
+ so we will allow anything starting with "sk-" and having at least 48 alphanumeric (plus underscore and dash) characters.
145
+ Keys are known to start with "sk-", "sk-proj", "sk-None", and "sk-svcaat"
146
+
147
+ Args:
148
+ api_key (str): An input string to be validated.
149
+
150
+ Returns:
151
+ bool: A boolean that indicates if input is valid OpenAI API key.
152
+ """
153
+ api_key_re = re.compile(r"^sk-[A-Za-z0-9_-]{48,}$")
154
+ return bool(re.fullmatch(api_key_re, api_key))
155
+
156
+
157
+ @export_module("autogen")
158
+ def get_config_list(
159
+ api_keys: list[str],
160
+ base_urls: Optional[list[str]] = None,
161
+ api_type: Optional[str] = None,
162
+ api_version: Optional[str] = None,
163
+ ) -> list[dict[str, Any]]:
164
+ """Get a list of configs for OpenAI API client.
165
+
166
+ Args:
167
+ api_keys (list): The api keys for openai api calls.
168
+ base_urls (list, optional): The api bases for openai api calls. If provided, should match the length of api_keys.
169
+ api_type (str, optional): The api type for openai api calls.
170
+ api_version (str, optional): The api version for openai api calls.
171
+
172
+ Returns:
173
+ list: A list of configs for OepnAI API calls.
174
+
175
+ Example:
176
+ ```python
177
+ # Define a list of API keys
178
+ api_keys = ["key1", "key2", "key3"]
179
+
180
+ # Optionally, define a list of base URLs corresponding to each API key
181
+ base_urls = ["https://api.service1.com", "https://api.service2.com", "https://api.service3.com"]
182
+
183
+ # Optionally, define the API type and version if they are common for all keys
184
+ api_type = "azure"
185
+ api_version = "2024-02-01"
186
+
187
+ # Call the get_config_list function to get a list of configuration dictionaries
188
+ config_list = get_config_list(api_keys, base_urls, api_type, api_version)
189
+ ```
190
+
191
+ """
192
+ if base_urls is not None:
193
+ assert len(api_keys) == len(base_urls), "The length of api_keys must match the length of base_urls"
194
+ config_list = []
195
+ for i, api_key in enumerate(api_keys):
196
+ if not api_key.strip():
197
+ continue
198
+ config = {"api_key": api_key}
199
+ if base_urls:
200
+ config["base_url"] = base_urls[i]
201
+ if api_type:
202
+ config["api_type"] = api_type
203
+ if api_version:
204
+ config["api_version"] = api_version
205
+ config_list.append(config)
206
+ return config_list
207
+
208
+
209
+ @export_module("autogen")
210
+ def get_first_llm_config(
211
+ llm_config: Union[LLMConfig, dict[str, Any]],
212
+ ) -> dict[str, Any]:
213
+ """Get the first LLM config from the given LLM config.
214
+
215
+ Args:
216
+ llm_config (dict): The LLM config.
217
+
218
+ Returns:
219
+ dict: The first LLM config.
220
+
221
+ Raises:
222
+ ValueError: If the LLM config is invalid.
223
+ """
224
+ llm_config = deepcopy(llm_config)
225
+ if "config_list" not in llm_config:
226
+ if "model" in llm_config:
227
+ return llm_config # type: ignore [return-value]
228
+ raise ValueError("llm_config must be a valid config dictionary.")
229
+
230
+ if len(llm_config["config_list"]) == 0:
231
+ raise ValueError("Config list must contain at least one config.")
232
+
233
+ to_return = llm_config["config_list"][0]
234
+ return to_return if isinstance(to_return, dict) else to_return.model_dump() # type: ignore [no-any-return]
235
+
236
+
237
+ @export_module("autogen")
238
+ def config_list_openai_aoai(
239
+ key_file_path: Optional[str] = ".",
240
+ openai_api_key_file: Optional[str] = "key_openai.txt",
241
+ aoai_api_key_file: Optional[str] = "key_aoai.txt",
242
+ openai_api_base_file: Optional[str] = "base_openai.txt",
243
+ aoai_api_base_file: Optional[str] = "base_aoai.txt",
244
+ exclude: Optional[str] = None,
245
+ ) -> list[dict[str, Any]]:
246
+ """Get a list of configs for OpenAI API client (including Azure or local model deployments that support OpenAI's chat completion API).
247
+
248
+ This function constructs configurations by reading API keys and base URLs from environment variables or text files.
249
+ It supports configurations for both OpenAI and Azure OpenAI services, allowing for the exclusion of one or the other.
250
+ When text files are used, the environment variables will be overwritten.
251
+ To prevent text files from being used, set the corresponding file name to None.
252
+ Or set key_file_path to None to disallow reading from text files.
253
+
254
+ Args:
255
+ key_file_path (str, optional): The directory path where the API key files are located. Defaults to the current directory.
256
+ openai_api_key_file (str, optional): The filename containing the OpenAI API key. Defaults to 'key_openai.txt'.
257
+ aoai_api_key_file (str, optional): The filename containing the Azure OpenAI API key. Defaults to 'key_aoai.txt'.
258
+ openai_api_base_file (str, optional): The filename containing the OpenAI API base URL. Defaults to 'base_openai.txt'.
259
+ aoai_api_base_file (str, optional): The filename containing the Azure OpenAI API base URL. Defaults to 'base_aoai.txt'.
260
+ exclude (str, optional): The API type to exclude from the configuration list. Can be 'openai' or 'aoai'. Defaults to None.
261
+
262
+ Returns:
263
+ List[Dict]: A list of configuration dictionaries. Each dictionary contains keys for 'api_key',
264
+ and optionally 'base_url', 'api_type', and 'api_version'.
265
+
266
+ Raises:
267
+ FileNotFoundError: If the specified key files are not found and the corresponding API key is not set in the environment variables.
268
+
269
+ Example:
270
+ # To generate configurations excluding Azure OpenAI:
271
+ configs = config_list_openai_aoai(exclude='aoai')
272
+
273
+ File samples:
274
+ - key_aoai.txt
275
+
276
+ ```
277
+ aoai-12345abcdef67890ghijklmnopqr
278
+ aoai-09876zyxwvuts54321fedcba
279
+ ```
280
+
281
+ - base_aoai.txt
282
+
283
+ ```
284
+ https://api.azure.com/v1
285
+ https://api.azure2.com/v1
286
+ ```
287
+
288
+ Notes:
289
+ - The function checks for API keys and base URLs in the following environment variables: 'OPENAI_API_KEY', 'AZURE_OPENAI_API_KEY',
290
+ 'OPENAI_API_BASE' and 'AZURE_OPENAI_API_BASE'. If these are not found, it attempts to read from the specified files in the
291
+ 'key_file_path' directory.
292
+ - The API version for Azure configurations is set to DEFAULT_AZURE_API_VERSION by default.
293
+ - If 'exclude' is set to 'openai', only Azure OpenAI configurations are returned, and vice versa.
294
+ - The function assumes that the API keys and base URLs in the environment variables are separated by new lines if there are
295
+ multiple entries.
296
+ """
297
+ if exclude != "openai" and key_file_path is not None:
298
+ # skip if key_file_path is None
299
+ if openai_api_key_file is not None:
300
+ # skip if openai_api_key_file is None
301
+ try:
302
+ with open(f"{key_file_path}/{openai_api_key_file}") as key_file:
303
+ os.environ["OPENAI_API_KEY"] = key_file.read().strip()
304
+ except FileNotFoundError:
305
+ logging.info(
306
+ "OPENAI_API_KEY is not found in os.environ "
307
+ "and key_openai.txt is not found in the specified path. You can specify the api_key in the config_list."
308
+ )
309
+ if openai_api_base_file is not None:
310
+ # skip if openai_api_base_file is None
311
+ try:
312
+ with open(f"{key_file_path}/{openai_api_base_file}") as key_file:
313
+ os.environ["OPENAI_API_BASE"] = key_file.read().strip()
314
+ except FileNotFoundError:
315
+ logging.info(
316
+ "OPENAI_API_BASE is not found in os.environ "
317
+ "and base_openai.txt is not found in the specified path. You can specify the base_url in the config_list."
318
+ )
319
+ if exclude != "aoai" and key_file_path is not None:
320
+ # skip if key_file_path is None
321
+ if aoai_api_key_file is not None:
322
+ try:
323
+ with open(f"{key_file_path}/{aoai_api_key_file}") as key_file:
324
+ os.environ["AZURE_OPENAI_API_KEY"] = key_file.read().strip()
325
+ except FileNotFoundError:
326
+ logging.info(
327
+ "AZURE_OPENAI_API_KEY is not found in os.environ "
328
+ "and key_aoai.txt is not found in the specified path. You can specify the api_key in the config_list."
329
+ )
330
+ if aoai_api_base_file is not None:
331
+ try:
332
+ with open(f"{key_file_path}/{aoai_api_base_file}") as key_file:
333
+ os.environ["AZURE_OPENAI_API_BASE"] = key_file.read().strip()
334
+ except FileNotFoundError:
335
+ logging.info(
336
+ "AZURE_OPENAI_API_BASE is not found in os.environ "
337
+ "and base_aoai.txt is not found in the specified path. You can specify the base_url in the config_list."
338
+ )
339
+ aoai_config = (
340
+ get_config_list(
341
+ # Assuming Azure OpenAI api keys in os.environ["AZURE_OPENAI_API_KEY"], in separated lines
342
+ api_keys=os.environ.get("AZURE_OPENAI_API_KEY", "").split("\n"),
343
+ # Assuming Azure OpenAI api bases in os.environ["AZURE_OPENAI_API_BASE"], in separated lines
344
+ base_urls=os.environ.get("AZURE_OPENAI_API_BASE", "").split("\n"),
345
+ api_type="azure",
346
+ api_version=DEFAULT_AZURE_API_VERSION,
347
+ )
348
+ if exclude != "aoai"
349
+ else []
350
+ )
351
+ # process openai base urls
352
+ base_urls_env_var = os.environ.get("OPENAI_API_BASE", None)
353
+ base_urls = base_urls_env_var if base_urls_env_var is None else base_urls_env_var.split("\n")
354
+ openai_config = (
355
+ get_config_list(
356
+ # Assuming OpenAI API_KEY in os.environ["OPENAI_API_KEY"]
357
+ api_keys=os.environ.get("OPENAI_API_KEY", "").split("\n"),
358
+ base_urls=base_urls,
359
+ )
360
+ if exclude != "openai"
361
+ else []
362
+ )
363
+ config_list = openai_config + aoai_config
364
+ return config_list
365
+
366
+
367
+ @export_module("autogen")
368
+ def config_list_from_models(
369
+ key_file_path: Optional[str] = ".",
370
+ openai_api_key_file: Optional[str] = "key_openai.txt",
371
+ aoai_api_key_file: Optional[str] = "key_aoai.txt",
372
+ aoai_api_base_file: Optional[str] = "base_aoai.txt",
373
+ exclude: Optional[str] = None,
374
+ model_list: Optional[list[str]] = None,
375
+ ) -> list[dict[str, Any]]:
376
+ """Get a list of configs for API calls with models specified in the model list.
377
+
378
+ This function extends `config_list_openai_aoai` by allowing to clone its' out for each of the models provided.
379
+ Each configuration will have a 'model' key with the model name as its value. This is particularly useful when
380
+ all endpoints have same set of models.
381
+
382
+ Args:
383
+ key_file_path (str, optional): The path to the key files.
384
+ openai_api_key_file (str, optional): The file name of the OpenAI API key.
385
+ aoai_api_key_file (str, optional): The file name of the Azure OpenAI API key.
386
+ aoai_api_base_file (str, optional): The file name of the Azure OpenAI API base.
387
+ exclude (str, optional): The API type to exclude, "openai" or "aoai".
388
+ model_list (list, optional): The list of model names to include in the configs.
389
+
390
+ Returns:
391
+ list: A list of configs for OpenAI API calls, each including model information.
392
+
393
+ Example:
394
+ ```python
395
+ # Define the path where the API key files are located
396
+ key_file_path = "/path/to/key/files"
397
+
398
+ # Define the file names for the OpenAI and Azure OpenAI API keys and bases
399
+ openai_api_key_file = "key_openai.txt"
400
+ aoai_api_key_file = "key_aoai.txt"
401
+ aoai_api_base_file = "base_aoai.txt"
402
+
403
+ # Define the list of models for which to create configurations
404
+ model_list = ["gpt-4", "gpt-3.5-turbo"]
405
+
406
+ # Call the function to get a list of configuration dictionaries
407
+ config_list = config_list_from_models(
408
+ key_file_path=key_file_path,
409
+ openai_api_key_file=openai_api_key_file,
410
+ aoai_api_key_file=aoai_api_key_file,
411
+ aoai_api_base_file=aoai_api_base_file,
412
+ model_list=model_list,
413
+ )
414
+
415
+ # The `config_list` will contain configurations for the specified models, for example:
416
+ # [
417
+ # {'api_key': '...', 'base_url': 'https://api.openai.com', 'model': 'gpt-4'},
418
+ # {'api_key': '...', 'base_url': 'https://api.openai.com', 'model': 'gpt-3.5-turbo'}
419
+ # ]
420
+ ```
421
+ """
422
+ config_list = config_list_openai_aoai(
423
+ key_file_path=key_file_path,
424
+ openai_api_key_file=openai_api_key_file,
425
+ aoai_api_key_file=aoai_api_key_file,
426
+ aoai_api_base_file=aoai_api_base_file,
427
+ exclude=exclude,
428
+ )
429
+ if model_list:
430
+ config_list = [{**config, "model": model} for model in model_list for config in config_list]
431
+ return config_list
432
+
433
+
434
+ @export_module("autogen")
435
+ def config_list_gpt4_gpt35(
436
+ key_file_path: Optional[str] = ".",
437
+ openai_api_key_file: Optional[str] = "key_openai.txt",
438
+ aoai_api_key_file: Optional[str] = "key_aoai.txt",
439
+ aoai_api_base_file: Optional[str] = "base_aoai.txt",
440
+ exclude: Optional[str] = None,
441
+ ) -> list[dict[str, Any]]:
442
+ """Get a list of configs for 'gpt-4' followed by 'gpt-3.5-turbo' API calls.
443
+
444
+ Args:
445
+ key_file_path (str, optional): The path to the key files.
446
+ openai_api_key_file (str, optional): The file name of the openai api key.
447
+ aoai_api_key_file (str, optional): The file name of the azure openai api key.
448
+ aoai_api_base_file (str, optional): The file name of the azure openai api base.
449
+ exclude (str, optional): The api type to exclude, "openai" or "aoai".
450
+
451
+ Returns:
452
+ list: A list of configs for openai api calls.
453
+ """
454
+ return config_list_from_models(
455
+ key_file_path,
456
+ openai_api_key_file,
457
+ aoai_api_key_file,
458
+ aoai_api_base_file,
459
+ exclude,
460
+ model_list=["gpt-4", "gpt-3.5-turbo"],
461
+ )
462
+
463
+
464
+ @export_module("autogen")
465
+ def filter_config(
466
+ config_list: list[dict[str, Any]],
467
+ filter_dict: Optional[dict[str, Union[list[Union[str, None]], set[Union[str, None]]]]],
468
+ exclude: bool = False,
469
+ ) -> list[dict[str, Any]]:
470
+ """This function filters `config_list` by checking each configuration dictionary against the criteria specified in
471
+ `filter_dict`. A configuration dictionary is retained if for every key in `filter_dict`, see example below.
472
+
473
+ Args:
474
+ config_list (list of dict): A list of configuration dictionaries to be filtered.
475
+ filter_dict (dict): A dictionary representing the filter criteria, where each key is a
476
+ field name to check within the configuration dictionaries, and the
477
+ corresponding value is a list of acceptable values for that field.
478
+ If the configuration's field's value is not a list, then a match occurs
479
+ when it is found in the list of acceptable values. If the configuration's
480
+ field's value is a list, then a match occurs if there is a non-empty
481
+ intersection with the acceptable values.
482
+ exclude (bool): If False (the default value), configs that match the filter will be included in the returned
483
+ list. If True, configs that match the filter will be excluded in the returned list.
484
+
485
+ Returns:
486
+ list of dict: A list of configuration dictionaries that meet all the criteria specified
487
+ in `filter_dict`.
488
+
489
+ Example:
490
+ ```python
491
+ # Example configuration list with various models and API types
492
+ configs = [
493
+ {"model": "gpt-3.5-turbo"},
494
+ {"model": "gpt-4"},
495
+ {"model": "gpt-3.5-turbo", "api_type": "azure"},
496
+ {"model": "gpt-3.5-turbo", "tags": ["gpt35_turbo", "gpt-35-turbo"]},
497
+ ]
498
+ # Define filter criteria to select configurations for the 'gpt-3.5-turbo' model
499
+ # that are also using the 'azure' API type
500
+ filter_criteria = {
501
+ "model": ["gpt-3.5-turbo"], # Only accept configurations for 'gpt-3.5-turbo'
502
+ "api_type": ["azure"], # Only accept configurations for 'azure' API type
503
+ }
504
+ # Apply the filter to the configuration list
505
+ filtered_configs = filter_config(configs, filter_criteria)
506
+ # The resulting `filtered_configs` will be:
507
+ # [{'model': 'gpt-3.5-turbo', 'api_type': 'azure', ...}]
508
+ # Define a filter to select a given tag
509
+ filter_criteria = {
510
+ "tags": ["gpt35_turbo"],
511
+ }
512
+ # Apply the filter to the configuration list
513
+ filtered_configs = filter_config(configs, filter_criteria)
514
+ # The resulting `filtered_configs` will be:
515
+ # [{'model': 'gpt-3.5-turbo', 'tags': ['gpt35_turbo', 'gpt-35-turbo']}]
516
+ ```
517
+ Note:
518
+ - If `filter_dict` is empty or None, no filtering is applied and `config_list` is returned as is.
519
+ - If a configuration dictionary in `config_list` does not contain a key specified in `filter_dict`,
520
+ it is considered a non-match and is excluded from the result.
521
+ - If the list of acceptable values for a key in `filter_dict` includes None, then configuration
522
+ dictionaries that do not have that key will also be considered a match.
523
+
524
+ """
525
+ if inspect.stack()[1].function != "where":
526
+ warnings.warn(
527
+ "filter_config is deprecated and will be removed in a future release. "
528
+ 'Please use the "autogen.LLMConfig.from_json(path="OAI_CONFIG_LIST").where(model="gpt-4o")" method instead.',
529
+ DeprecationWarning,
530
+ )
531
+
532
+ if filter_dict:
533
+ return [
534
+ item
535
+ for item in config_list
536
+ if all(_satisfies_criteria(item.get(key), values) != exclude for key, values in filter_dict.items())
537
+ ]
538
+ return config_list
539
+
540
+
541
+ def _satisfies_criteria(value: Any, criteria_values: Any) -> bool:
542
+ if value is None:
543
+ return False
544
+
545
+ if isinstance(value, list):
546
+ return bool(set(value) & set(criteria_values)) # Non-empty intersection
547
+ else:
548
+ # In filter_dict, filter could be either a list of values or a single value.
549
+ # For example, filter_dict = {"model": ["gpt-3.5-turbo"]} or {"model": "gpt-3.5-turbo"}
550
+ if isinstance(criteria_values, list):
551
+ return value in criteria_values
552
+ return bool(value == criteria_values)
553
+
554
+
555
+ @export_module("autogen")
556
+ def config_list_from_json(
557
+ env_or_file: str,
558
+ file_location: Optional[str] = "",
559
+ filter_dict: Optional[dict[str, Union[list[Union[str, None]], set[Union[str, None]]]]] = None,
560
+ ) -> list[dict[str, Any]]:
561
+ """Retrieves a list of API configurations from a JSON stored in an environment variable or a file.
562
+
563
+ This function attempts to parse JSON data from the given `env_or_file` parameter. If `env_or_file` is an
564
+ environment variable containing JSON data, it will be used directly. Otherwise, it is assumed to be a filename,
565
+ and the function will attempt to read the file from the specified `file_location`.
566
+
567
+ The `filter_dict` parameter allows for filtering the configurations based on specified criteria. Each key in the
568
+ `filter_dict` corresponds to a field in the configuration dictionaries, and the associated value is a list or set
569
+ of acceptable values for that field. If a field is missing in a configuration and `None` is included in the list
570
+ of acceptable values for that field, the configuration will still be considered a match.
571
+
572
+ Args:
573
+ env_or_file (str): The name of the environment variable, the filename, or the environment variable of the filename
574
+ that containing the JSON data.
575
+ file_location (str, optional): The directory path where the file is located, if `env_or_file` is a filename.
576
+ filter_dict (dict, optional): A dictionary specifying the filtering criteria for the configurations, with
577
+ keys representing field names and values being lists or sets of acceptable values for those fields.
578
+
579
+ Example:
580
+ ```python
581
+ # Suppose we have an environment variable 'CONFIG_JSON' with the following content:
582
+ # '[{"model": "gpt-3.5-turbo", "api_type": "azure"}, {"model": "gpt-4"}]'
583
+
584
+ # We can retrieve a filtered list of configurations like this:
585
+ filter_criteria = {"model": ["gpt-3.5-turbo"]}
586
+ configs = config_list_from_json("CONFIG_JSON", filter_dict=filter_criteria)
587
+ # The 'configs' variable will now contain only the configurations that match the filter criteria.
588
+ ```
589
+
590
+ Returns:
591
+ List[Dict]: A list of configuration dictionaries that match the filtering criteria specified in `filter_dict`.
592
+
593
+ Raises:
594
+ FileNotFoundError: if env_or_file is neither found as an environment variable nor a file
595
+ """
596
+ if inspect.stack()[1].function != "from_json":
597
+ warnings.warn(
598
+ "config_list_from_json is deprecated and will be removed in a future release. "
599
+ 'Please use the "autogen.LLMConfig.from_json(path="OAI_CONFIG_LIST")" method instead.',
600
+ DeprecationWarning,
601
+ )
602
+
603
+ env_str = os.environ.get(env_or_file)
604
+
605
+ if env_str:
606
+ # The environment variable exists. We should use information from it.
607
+ if os.path.exists(env_str):
608
+ # It is a file location, and we need to load the json from the file.
609
+ with open(env_str) as file:
610
+ json_str = file.read()
611
+ else:
612
+ # Else, it should be a JSON string by itself.
613
+ json_str = env_str
614
+ config_list = json.loads(json_str)
615
+ else:
616
+ # The environment variable does not exist.
617
+ # So, `env_or_file` is a filename. We should use the file location.
618
+ config_list_path = os.path.join(file_location, env_or_file) if file_location is not None else env_or_file
619
+
620
+ with open(config_list_path) as json_file:
621
+ config_list = json.load(json_file)
622
+
623
+ config_list = filter_config(config_list, filter_dict)
624
+
625
+ return filter_config(config_list, filter_dict)
626
+
627
+
628
+ def get_config(
629
+ api_key: Optional[str],
630
+ base_url: Optional[str] = None,
631
+ api_type: Optional[str] = None,
632
+ api_version: Optional[str] = None,
633
+ ) -> dict[str, Any]:
634
+ """Constructs a configuration dictionary for a single model with the provided API configurations.
635
+
636
+ Example:
637
+ ```python
638
+ config = get_config(api_key="sk-abcdef1234567890", base_url="https://api.openai.com", api_version="v1")
639
+ # The 'config' variable will now contain:
640
+ # {
641
+ # "api_key": "sk-abcdef1234567890",
642
+ # "base_url": "https://api.openai.com",
643
+ # "api_version": "v1"
644
+ # }
645
+ ```
646
+
647
+ Args:
648
+ api_key (str): The API key for authenticating API requests.
649
+ base_url (Optional[str]): The base URL of the API. If not provided, defaults to None.
650
+ api_type (Optional[str]): The type of API. If not provided, defaults to None.
651
+ api_version (Optional[str]): The version of the API. If not provided, defaults to None.
652
+
653
+ Returns:
654
+ Dict: A dictionary containing the provided API configurations.
655
+ """
656
+ config = {"api_key": api_key}
657
+ if base_url:
658
+ config["base_url"] = os.getenv(base_url, default=base_url)
659
+ if api_type:
660
+ config["api_type"] = os.getenv(api_type, default=api_type)
661
+ if api_version:
662
+ config["api_version"] = os.getenv(api_version, default=api_version)
663
+ return config
664
+
665
+
666
+ @export_module("autogen")
667
+ def config_list_from_dotenv(
668
+ dotenv_file_path: Optional[str] = None,
669
+ model_api_key_map: Optional[dict[str, Any]] = None,
670
+ filter_dict: Optional[dict[str, Union[list[Union[str, None]], set[Union[str, None]]]]] = None,
671
+ ) -> list[dict[str, Union[str, set[str]]]]:
672
+ """Load API configurations from a specified .env file or environment variables and construct a list of configurations.
673
+
674
+ This function will:
675
+ - Load API keys from a provided .env file or from existing environment variables.
676
+ - Create a configuration dictionary for each model using the API keys and additional configurations.
677
+ - Filter and return the configurations based on provided filters.
678
+
679
+ model_api_key_map will default to `{"gpt-4": "OPENAI_API_KEY", "gpt-3.5-turbo": "OPENAI_API_KEY"}` if none
680
+
681
+ Args:
682
+ dotenv_file_path (str, optional): The path to the .env file. Defaults to None.
683
+ model_api_key_map (str/dict, optional): A dictionary mapping models to their API key configurations.
684
+ If a string is provided as configuration, it is considered as an environment
685
+ variable name storing the API key.
686
+ If a dict is provided, it should contain at least 'api_key_env_var' key,
687
+ and optionally other API configurations like 'base_url', 'api_type', and 'api_version'.
688
+ Defaults to a basic map with 'gpt-4' and 'gpt-3.5-turbo' mapped to 'OPENAI_API_KEY'.
689
+ filter_dict (dict, optional): A dictionary containing the models to be loaded.
690
+ Containing a 'model' key mapped to a set of model names to be loaded.
691
+ Defaults to None, which loads all found configurations.
692
+
693
+ Returns:
694
+ List[Dict[str, Union[str, Set[str]]]]: A list of configuration dictionaries for each model.
695
+
696
+ Raises:
697
+ FileNotFoundError: If the specified .env file does not exist.
698
+ TypeError: If an unsupported type of configuration is provided in model_api_key_map.
699
+ """
700
+ if dotenv_file_path:
701
+ dotenv_path = Path(dotenv_file_path)
702
+ if dotenv_path.exists():
703
+ load_dotenv(dotenv_path)
704
+ else:
705
+ logging.warning(f"The specified .env file {dotenv_path} does not exist.")
706
+ else:
707
+ dotenv_path_str = find_dotenv()
708
+ if not dotenv_path_str:
709
+ logging.warning("No .env file found. Loading configurations from environment variables.")
710
+ dotenv_path = Path(dotenv_path_str)
711
+ load_dotenv(dotenv_path)
712
+
713
+ # Ensure the model_api_key_map is not None to prevent TypeErrors during key assignment.
714
+ model_api_key_map = model_api_key_map or {}
715
+
716
+ # Ensure default models are always considered
717
+ default_models = ["gpt-4", "gpt-3.5-turbo"]
718
+
719
+ for model in default_models:
720
+ # Only assign default API key if the model is not present in the map.
721
+ # If model is present but set to invalid/empty, do not overwrite.
722
+ if model not in model_api_key_map:
723
+ model_api_key_map[model] = "OPENAI_API_KEY"
724
+
725
+ env_var = []
726
+ # Loop over the models and create configuration dictionaries
727
+ for model, config in model_api_key_map.items():
728
+ if isinstance(config, str):
729
+ api_key_env_var = config
730
+ config_dict = get_config(api_key=os.getenv(api_key_env_var))
731
+ elif isinstance(config, dict):
732
+ api_key = os.getenv(config.get("api_key_env_var", "OPENAI_API_KEY"))
733
+ config_without_key_var = {k: v for k, v in config.items() if k != "api_key_env_var"}
734
+ config_dict = get_config(api_key=api_key, **config_without_key_var)
735
+ else:
736
+ logging.warning(f"Unsupported type {type(config)} for model {model} configuration")
737
+
738
+ if not config_dict["api_key"] or config_dict["api_key"].strip() == "":
739
+ logging.warning(
740
+ f"API key not found or empty for model {model}. Please ensure path to .env file is correct."
741
+ )
742
+ continue # Skip this configuration and continue with the next
743
+
744
+ # Add model to the configuration and append to the list
745
+ config_dict["model"] = model
746
+ env_var.append(config_dict)
747
+
748
+ fd, temp_name = tempfile.mkstemp()
749
+ try:
750
+ with os.fdopen(fd, "w+") as temp:
751
+ env_var_str = json.dumps(env_var)
752
+ temp.write(env_var_str)
753
+ temp.flush()
754
+
755
+ # Assuming config_list_from_json is a valid function from your code
756
+ config_list = config_list_from_json(env_or_file=temp_name, filter_dict=filter_dict)
757
+ finally:
758
+ # The file is deleted after using its name (to prevent windows build from breaking)
759
+ os.remove(temp_name)
760
+
761
+ if len(config_list) == 0:
762
+ logging.error("No configurations loaded.")
763
+ return []
764
+
765
+ logging.info(f"Models available: {[config['model'] for config in config_list]}")
766
+ return config_list
767
+
768
+
769
+ def retrieve_assistants_by_name(client: "OpenAI", name: str) -> list["Assistant"]:
770
+ """Return the assistants with the given name from OAI assistant API"""
771
+ assistants = client.beta.assistants.list()
772
+ candidate_assistants = []
773
+ for assistant in assistants.data:
774
+ if assistant.name == name:
775
+ candidate_assistants.append(assistant)
776
+ return candidate_assistants
777
+
778
+
779
+ def detect_gpt_assistant_api_version() -> str:
780
+ """Detect the openai assistant API version"""
781
+ oai_version = importlib.metadata.version("openai")
782
+ return "v1" if parse(oai_version) < parse("1.21") else "v2"
783
+
784
+
785
+ def create_gpt_vector_store(client: "OpenAI", name: str, fild_ids: list[str]) -> Any:
786
+ """Create a openai vector store for gpt assistant"""
787
+ try:
788
+ vector_store = client.vector_stores.create(name=name)
789
+ except Exception as e:
790
+ raise AttributeError(f"Failed to create vector store, please install the latest OpenAI python package: {e}")
791
+
792
+ # poll the status of the file batch for completion.
793
+ batch = client.vector_stores.file_batches.create_and_poll(vector_store_id=vector_store.id, file_ids=fild_ids)
794
+
795
+ if batch.status == "in_progress":
796
+ time.sleep(1)
797
+ logging.debug(f"file batch status: {batch.file_counts}")
798
+ batch = client.vector_stores.file_batches.poll(vector_store_id=vector_store.id, batch_id=batch.id)
799
+
800
+ if batch.status == "completed":
801
+ return vector_store
802
+
803
+ raise ValueError(f"Failed to upload files to vector store {vector_store.id}:{batch.status}")
804
+
805
+
806
+ def create_gpt_assistant(
807
+ client: "OpenAI", name: str, instructions: str, model: str, assistant_config: dict[str, Any]
808
+ ) -> "Assistant":
809
+ """Create a openai gpt assistant"""
810
+ assistant_create_kwargs = {}
811
+ gpt_assistant_api_version = detect_gpt_assistant_api_version()
812
+ tools = assistant_config.get("tools", [])
813
+
814
+ if gpt_assistant_api_version == "v2":
815
+ tool_resources = assistant_config.get("tool_resources", {})
816
+ file_ids = assistant_config.get("file_ids")
817
+ if tool_resources.get("file_search") is not None and file_ids is not None:
818
+ raise ValueError(
819
+ "Cannot specify both `tool_resources['file_search']` tool and `file_ids` in the assistant config."
820
+ )
821
+
822
+ # Designed for backwards compatibility for the V1 API
823
+ # Instead of V1 AssistantFile, files are attached to Assistants using the tool_resources object.
824
+ for tool in tools:
825
+ if tool["type"] == "retrieval":
826
+ tool["type"] = "file_search"
827
+ if file_ids is not None:
828
+ # create a vector store for the file search tool
829
+ vs = create_gpt_vector_store(client, f"{name}-vectorestore", file_ids)
830
+ tool_resources["file_search"] = {
831
+ "vector_store_ids": [vs.id],
832
+ }
833
+ elif tool["type"] == "code_interpreter" and file_ids is not None:
834
+ tool_resources["code_interpreter"] = {
835
+ "file_ids": file_ids,
836
+ }
837
+
838
+ assistant_create_kwargs["tools"] = tools
839
+ if len(tool_resources) > 0:
840
+ assistant_create_kwargs["tool_resources"] = tool_resources
841
+ else:
842
+ # not support forwards compatibility
843
+ if "tool_resources" in assistant_config:
844
+ raise ValueError("`tool_resources` argument are not supported in the openai assistant V1 API.")
845
+ if any(tool["type"] == "file_search" for tool in tools):
846
+ raise ValueError(
847
+ "`file_search` tool are not supported in the openai assistant V1 API, please use `retrieval`."
848
+ )
849
+ assistant_create_kwargs["tools"] = tools
850
+ assistant_create_kwargs["file_ids"] = assistant_config.get("file_ids", [])
851
+
852
+ logging.info(f"Creating assistant with config: {assistant_create_kwargs}")
853
+ return client.beta.assistants.create(name=name, instructions=instructions, model=model, **assistant_create_kwargs)
854
+
855
+
856
+ def update_gpt_assistant(client: "OpenAI", assistant_id: str, assistant_config: dict[str, Any]) -> "Assistant":
857
+ """Update openai gpt assistant"""
858
+ gpt_assistant_api_version = detect_gpt_assistant_api_version()
859
+ assistant_update_kwargs = {}
860
+
861
+ if assistant_config.get("tools") is not None:
862
+ assistant_update_kwargs["tools"] = assistant_config["tools"]
863
+
864
+ if assistant_config.get("instructions") is not None:
865
+ assistant_update_kwargs["instructions"] = assistant_config["instructions"]
866
+
867
+ if gpt_assistant_api_version == "v2":
868
+ if assistant_config.get("tool_resources") is not None:
869
+ assistant_update_kwargs["tool_resources"] = assistant_config["tool_resources"]
870
+ else:
871
+ if assistant_config.get("file_ids") is not None:
872
+ assistant_update_kwargs["file_ids"] = assistant_config["file_ids"]
873
+
874
+ return client.beta.assistants.update(assistant_id=assistant_id, **assistant_update_kwargs)
875
+
876
+
877
+ def _satisfies(config_value: Any, acceptable_values: Any) -> bool:
878
+ if isinstance(config_value, list):
879
+ return bool(set(config_value) & set(acceptable_values)) # Non-empty intersection
880
+ else:
881
+ return config_value in acceptable_values