ag2 0.9.6__py3-none-any.whl → 0.9.8.post1__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 (236) hide show
  1. {ag2-0.9.6.dist-info → ag2-0.9.8.post1.dist-info}/METADATA +102 -75
  2. ag2-0.9.8.post1.dist-info/RECORD +387 -0
  3. autogen/__init__.py +1 -2
  4. autogen/_website/generate_api_references.py +4 -5
  5. autogen/_website/generate_mkdocs.py +9 -15
  6. autogen/_website/notebook_processor.py +13 -14
  7. autogen/_website/process_notebooks.py +10 -10
  8. autogen/_website/utils.py +5 -4
  9. autogen/agentchat/agent.py +13 -13
  10. autogen/agentchat/assistant_agent.py +7 -6
  11. autogen/agentchat/contrib/agent_eval/agent_eval.py +3 -3
  12. autogen/agentchat/contrib/agent_eval/critic_agent.py +3 -3
  13. autogen/agentchat/contrib/agent_eval/quantifier_agent.py +3 -3
  14. autogen/agentchat/contrib/agent_eval/subcritic_agent.py +3 -3
  15. autogen/agentchat/contrib/agent_optimizer.py +3 -3
  16. autogen/agentchat/contrib/capabilities/generate_images.py +11 -11
  17. autogen/agentchat/contrib/capabilities/teachability.py +15 -15
  18. autogen/agentchat/contrib/capabilities/transforms.py +17 -18
  19. autogen/agentchat/contrib/capabilities/transforms_util.py +5 -5
  20. autogen/agentchat/contrib/capabilities/vision_capability.py +4 -3
  21. autogen/agentchat/contrib/captainagent/agent_builder.py +30 -30
  22. autogen/agentchat/contrib/captainagent/captainagent.py +22 -21
  23. autogen/agentchat/contrib/captainagent/tool_retriever.py +2 -3
  24. autogen/agentchat/contrib/gpt_assistant_agent.py +9 -9
  25. autogen/agentchat/contrib/graph_rag/document.py +3 -3
  26. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +3 -3
  27. autogen/agentchat/contrib/graph_rag/falkor_graph_rag_capability.py +6 -6
  28. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +3 -3
  29. autogen/agentchat/contrib/graph_rag/neo4j_graph_query_engine.py +5 -11
  30. autogen/agentchat/contrib/graph_rag/neo4j_graph_rag_capability.py +6 -6
  31. autogen/agentchat/contrib/graph_rag/neo4j_native_graph_query_engine.py +7 -7
  32. autogen/agentchat/contrib/graph_rag/neo4j_native_graph_rag_capability.py +6 -6
  33. autogen/agentchat/contrib/img_utils.py +1 -1
  34. autogen/agentchat/contrib/llamaindex_conversable_agent.py +11 -11
  35. autogen/agentchat/contrib/llava_agent.py +18 -4
  36. autogen/agentchat/contrib/math_user_proxy_agent.py +11 -11
  37. autogen/agentchat/contrib/multimodal_conversable_agent.py +8 -8
  38. autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +6 -5
  39. autogen/agentchat/contrib/rag/chromadb_query_engine.py +22 -26
  40. autogen/agentchat/contrib/rag/llamaindex_query_engine.py +14 -17
  41. autogen/agentchat/contrib/rag/mongodb_query_engine.py +27 -37
  42. autogen/agentchat/contrib/rag/query_engine.py +7 -5
  43. autogen/agentchat/contrib/retrieve_assistant_agent.py +5 -5
  44. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +8 -7
  45. autogen/agentchat/contrib/society_of_mind_agent.py +15 -14
  46. autogen/agentchat/contrib/swarm_agent.py +76 -98
  47. autogen/agentchat/contrib/text_analyzer_agent.py +7 -7
  48. autogen/agentchat/contrib/vectordb/base.py +10 -18
  49. autogen/agentchat/contrib/vectordb/chromadb.py +2 -1
  50. autogen/agentchat/contrib/vectordb/couchbase.py +18 -20
  51. autogen/agentchat/contrib/vectordb/mongodb.py +6 -5
  52. autogen/agentchat/contrib/vectordb/pgvectordb.py +40 -41
  53. autogen/agentchat/contrib/vectordb/qdrant.py +5 -5
  54. autogen/agentchat/contrib/web_surfer.py +20 -19
  55. autogen/agentchat/conversable_agent.py +311 -295
  56. autogen/agentchat/group/context_str.py +1 -3
  57. autogen/agentchat/group/context_variables.py +15 -25
  58. autogen/agentchat/group/group_tool_executor.py +10 -10
  59. autogen/agentchat/group/group_utils.py +15 -15
  60. autogen/agentchat/group/guardrails.py +7 -7
  61. autogen/agentchat/group/handoffs.py +19 -36
  62. autogen/agentchat/group/multi_agent_chat.py +7 -7
  63. autogen/agentchat/group/on_condition.py +4 -7
  64. autogen/agentchat/group/on_context_condition.py +4 -7
  65. autogen/agentchat/group/patterns/auto.py +8 -7
  66. autogen/agentchat/group/patterns/manual.py +7 -6
  67. autogen/agentchat/group/patterns/pattern.py +13 -12
  68. autogen/agentchat/group/patterns/random.py +3 -3
  69. autogen/agentchat/group/patterns/round_robin.py +3 -3
  70. autogen/agentchat/group/reply_result.py +2 -4
  71. autogen/agentchat/group/speaker_selection_result.py +5 -5
  72. autogen/agentchat/group/targets/group_chat_target.py +7 -6
  73. autogen/agentchat/group/targets/group_manager_target.py +4 -4
  74. autogen/agentchat/group/targets/transition_target.py +2 -1
  75. autogen/agentchat/groupchat.py +58 -61
  76. autogen/agentchat/realtime/experimental/audio_adapters/twilio_audio_adapter.py +4 -4
  77. autogen/agentchat/realtime/experimental/audio_adapters/websocket_audio_adapter.py +4 -4
  78. autogen/agentchat/realtime/experimental/clients/gemini/client.py +7 -7
  79. autogen/agentchat/realtime/experimental/clients/oai/base_client.py +8 -8
  80. autogen/agentchat/realtime/experimental/clients/oai/rtc_client.py +6 -6
  81. autogen/agentchat/realtime/experimental/clients/realtime_client.py +10 -9
  82. autogen/agentchat/realtime/experimental/realtime_agent.py +10 -9
  83. autogen/agentchat/realtime/experimental/realtime_observer.py +3 -3
  84. autogen/agentchat/realtime/experimental/realtime_swarm.py +44 -44
  85. autogen/agentchat/user_proxy_agent.py +10 -9
  86. autogen/agentchat/utils.py +3 -3
  87. autogen/agents/contrib/time/time_reply_agent.py +6 -5
  88. autogen/agents/contrib/time/time_tool_agent.py +2 -1
  89. autogen/agents/experimental/deep_research/deep_research.py +3 -3
  90. autogen/agents/experimental/discord/discord.py +2 -2
  91. autogen/agents/experimental/document_agent/chroma_query_engine.py +29 -44
  92. autogen/agents/experimental/document_agent/docling_doc_ingest_agent.py +9 -14
  93. autogen/agents/experimental/document_agent/document_agent.py +15 -16
  94. autogen/agents/experimental/document_agent/document_conditions.py +3 -3
  95. autogen/agents/experimental/document_agent/document_utils.py +5 -9
  96. autogen/agents/experimental/document_agent/inmemory_query_engine.py +14 -20
  97. autogen/agents/experimental/document_agent/parser_utils.py +4 -4
  98. autogen/agents/experimental/document_agent/url_utils.py +14 -23
  99. autogen/agents/experimental/reasoning/reasoning_agent.py +33 -33
  100. autogen/agents/experimental/slack/slack.py +2 -2
  101. autogen/agents/experimental/telegram/telegram.py +2 -3
  102. autogen/agents/experimental/websurfer/websurfer.py +4 -4
  103. autogen/agents/experimental/wikipedia/wikipedia.py +5 -7
  104. autogen/browser_utils.py +8 -8
  105. autogen/cache/abstract_cache_base.py +5 -5
  106. autogen/cache/cache.py +12 -12
  107. autogen/cache/cache_factory.py +4 -4
  108. autogen/cache/cosmos_db_cache.py +9 -9
  109. autogen/cache/disk_cache.py +6 -6
  110. autogen/cache/in_memory_cache.py +4 -4
  111. autogen/cache/redis_cache.py +4 -4
  112. autogen/code_utils.py +18 -18
  113. autogen/coding/base.py +6 -6
  114. autogen/coding/docker_commandline_code_executor.py +9 -9
  115. autogen/coding/func_with_reqs.py +7 -6
  116. autogen/coding/jupyter/base.py +3 -3
  117. autogen/coding/jupyter/docker_jupyter_server.py +3 -4
  118. autogen/coding/jupyter/import_utils.py +3 -3
  119. autogen/coding/jupyter/jupyter_client.py +5 -5
  120. autogen/coding/jupyter/jupyter_code_executor.py +3 -4
  121. autogen/coding/jupyter/local_jupyter_server.py +2 -6
  122. autogen/coding/local_commandline_code_executor.py +8 -7
  123. autogen/coding/markdown_code_extractor.py +1 -2
  124. autogen/coding/utils.py +1 -2
  125. autogen/doc_utils.py +3 -2
  126. autogen/environments/docker_python_environment.py +19 -29
  127. autogen/environments/python_environment.py +8 -17
  128. autogen/environments/system_python_environment.py +3 -4
  129. autogen/environments/venv_python_environment.py +8 -12
  130. autogen/environments/working_directory.py +1 -2
  131. autogen/events/agent_events.py +106 -109
  132. autogen/events/base_event.py +6 -5
  133. autogen/events/client_events.py +15 -14
  134. autogen/events/helpers.py +1 -1
  135. autogen/events/print_event.py +4 -5
  136. autogen/fast_depends/_compat.py +10 -15
  137. autogen/fast_depends/core/build.py +17 -36
  138. autogen/fast_depends/core/model.py +64 -113
  139. autogen/fast_depends/dependencies/model.py +2 -1
  140. autogen/fast_depends/dependencies/provider.py +3 -2
  141. autogen/fast_depends/library/model.py +4 -4
  142. autogen/fast_depends/schema.py +7 -7
  143. autogen/fast_depends/use.py +17 -25
  144. autogen/fast_depends/utils.py +10 -30
  145. autogen/formatting_utils.py +6 -6
  146. autogen/graph_utils.py +1 -4
  147. autogen/import_utils.py +13 -13
  148. autogen/interop/crewai/crewai.py +2 -2
  149. autogen/interop/interoperable.py +2 -2
  150. autogen/interop/langchain/langchain_chat_model_factory.py +3 -2
  151. autogen/interop/langchain/langchain_tool.py +2 -6
  152. autogen/interop/litellm/litellm_config_factory.py +6 -7
  153. autogen/interop/pydantic_ai/pydantic_ai.py +4 -7
  154. autogen/interop/registry.py +2 -1
  155. autogen/io/base.py +5 -5
  156. autogen/io/run_response.py +33 -32
  157. autogen/io/websockets.py +6 -5
  158. autogen/json_utils.py +1 -2
  159. autogen/llm_config/__init__.py +11 -0
  160. autogen/llm_config/client.py +58 -0
  161. autogen/llm_config/config.py +384 -0
  162. autogen/llm_config/entry.py +154 -0
  163. autogen/logger/base_logger.py +4 -3
  164. autogen/logger/file_logger.py +2 -1
  165. autogen/logger/logger_factory.py +2 -2
  166. autogen/logger/logger_utils.py +2 -2
  167. autogen/logger/sqlite_logger.py +3 -2
  168. autogen/math_utils.py +4 -5
  169. autogen/mcp/__main__.py +6 -6
  170. autogen/mcp/helpers.py +4 -4
  171. autogen/mcp/mcp_client.py +170 -29
  172. autogen/mcp/mcp_proxy/fastapi_code_generator_helpers.py +3 -4
  173. autogen/mcp/mcp_proxy/mcp_proxy.py +23 -26
  174. autogen/mcp/mcp_proxy/operation_grouping.py +4 -5
  175. autogen/mcp/mcp_proxy/operation_renaming.py +6 -10
  176. autogen/mcp/mcp_proxy/security.py +2 -3
  177. autogen/messages/agent_messages.py +96 -98
  178. autogen/messages/base_message.py +6 -5
  179. autogen/messages/client_messages.py +15 -14
  180. autogen/messages/print_message.py +4 -5
  181. autogen/oai/__init__.py +1 -2
  182. autogen/oai/anthropic.py +42 -41
  183. autogen/oai/bedrock.py +68 -57
  184. autogen/oai/cerebras.py +26 -25
  185. autogen/oai/client.py +118 -138
  186. autogen/oai/client_utils.py +3 -3
  187. autogen/oai/cohere.py +34 -11
  188. autogen/oai/gemini.py +40 -17
  189. autogen/oai/gemini_types.py +11 -12
  190. autogen/oai/groq.py +22 -10
  191. autogen/oai/mistral.py +17 -11
  192. autogen/oai/oai_models/__init__.py +14 -2
  193. autogen/oai/oai_models/_models.py +2 -2
  194. autogen/oai/oai_models/chat_completion.py +13 -14
  195. autogen/oai/oai_models/chat_completion_message.py +11 -9
  196. autogen/oai/oai_models/chat_completion_message_tool_call.py +26 -3
  197. autogen/oai/oai_models/chat_completion_token_logprob.py +3 -4
  198. autogen/oai/oai_models/completion_usage.py +8 -9
  199. autogen/oai/ollama.py +22 -10
  200. autogen/oai/openai_responses.py +40 -17
  201. autogen/oai/openai_utils.py +159 -85
  202. autogen/oai/together.py +29 -14
  203. autogen/retrieve_utils.py +6 -7
  204. autogen/runtime_logging.py +5 -4
  205. autogen/token_count_utils.py +7 -4
  206. autogen/tools/contrib/time/time.py +0 -1
  207. autogen/tools/dependency_injection.py +5 -6
  208. autogen/tools/experimental/browser_use/browser_use.py +10 -10
  209. autogen/tools/experimental/code_execution/python_code_execution.py +5 -7
  210. autogen/tools/experimental/crawl4ai/crawl4ai.py +12 -15
  211. autogen/tools/experimental/deep_research/deep_research.py +9 -8
  212. autogen/tools/experimental/duckduckgo/duckduckgo_search.py +5 -11
  213. autogen/tools/experimental/firecrawl/firecrawl_tool.py +98 -115
  214. autogen/tools/experimental/google/authentication/credentials_local_provider.py +1 -1
  215. autogen/tools/experimental/google/drive/drive_functions.py +4 -4
  216. autogen/tools/experimental/google/drive/toolkit.py +5 -5
  217. autogen/tools/experimental/google_search/google_search.py +5 -5
  218. autogen/tools/experimental/google_search/youtube_search.py +5 -5
  219. autogen/tools/experimental/messageplatform/discord/discord.py +8 -12
  220. autogen/tools/experimental/messageplatform/slack/slack.py +14 -20
  221. autogen/tools/experimental/messageplatform/telegram/telegram.py +8 -12
  222. autogen/tools/experimental/perplexity/perplexity_search.py +18 -29
  223. autogen/tools/experimental/reliable/reliable.py +68 -74
  224. autogen/tools/experimental/searxng/searxng_search.py +20 -19
  225. autogen/tools/experimental/tavily/tavily_search.py +12 -19
  226. autogen/tools/experimental/web_search_preview/web_search_preview.py +13 -7
  227. autogen/tools/experimental/wikipedia/wikipedia.py +7 -10
  228. autogen/tools/function_utils.py +7 -7
  229. autogen/tools/tool.py +6 -5
  230. autogen/types.py +2 -2
  231. autogen/version.py +1 -1
  232. ag2-0.9.6.dist-info/RECORD +0 -421
  233. autogen/llm_config.py +0 -385
  234. {ag2-0.9.6.dist-info → ag2-0.9.8.post1.dist-info}/WHEEL +0 -0
  235. {ag2-0.9.6.dist-info → ag2-0.9.8.post1.dist-info}/licenses/LICENSE +0 -0
  236. {ag2-0.9.6.dist-info → ag2-0.9.8.post1.dist-info}/licenses/NOTICE.md +0 -0
@@ -5,7 +5,7 @@
5
5
  import base64
6
6
  import json
7
7
  from logging import Logger
8
- from typing import TYPE_CHECKING, Optional
8
+ from typing import TYPE_CHECKING
9
9
 
10
10
  from .....doc_utils import export_module
11
11
  from ..realtime_events import AudioDelta, RealtimeEvent, SpeechStarted
@@ -32,7 +32,7 @@ SHOW_TIMING_MATH = False
32
32
  class TwilioAudioAdapter(RealtimeObserver):
33
33
  """Adapter for streaming audio from Twilio to OpenAI Realtime API and vice versa."""
34
34
 
35
- def __init__(self, websocket: "WebSocket", *, logger: Optional[Logger] = None):
35
+ def __init__(self, websocket: "WebSocket", *, logger: Logger | None = None):
36
36
  """Adapter for streaming audio from Twilio to OpenAI Realtime API and vice versa.
37
37
 
38
38
  Args:
@@ -45,9 +45,9 @@ class TwilioAudioAdapter(RealtimeObserver):
45
45
  # Connection specific state
46
46
  self.stream_sid = None
47
47
  self.latest_media_timestamp = 0
48
- self.last_assistant_item: Optional[str] = None
48
+ self.last_assistant_item: str | None = None
49
49
  self.mark_queue: list[str] = []
50
- self.response_start_timestamp_twilio: Optional[int] = None
50
+ self.response_start_timestamp_twilio: int | None = None
51
51
 
52
52
  async def on_event(self, event: RealtimeEvent) -> None:
53
53
  """Receive events from the OpenAI Realtime API, send audio back to Twilio."""
@@ -5,7 +5,7 @@
5
5
  import base64
6
6
  import json
7
7
  from logging import Logger
8
- from typing import TYPE_CHECKING, Optional
8
+ from typing import TYPE_CHECKING
9
9
 
10
10
  from .....doc_utils import export_module
11
11
  from ..realtime_events import AudioDelta, RealtimeEvent, SpeechStarted
@@ -29,7 +29,7 @@ SHOW_TIMING_MATH = False
29
29
 
30
30
  @export_module("autogen.agentchat.realtime.experimental")
31
31
  class WebSocketAudioAdapter(RealtimeObserver):
32
- def __init__(self, websocket: "WebSocket", *, logger: Optional[Logger] = None) -> None:
32
+ def __init__(self, websocket: "WebSocket", *, logger: Logger | None = None) -> None:
33
33
  """Observer for handling function calls from the OpenAI Realtime API.
34
34
 
35
35
  Args:
@@ -42,9 +42,9 @@ class WebSocketAudioAdapter(RealtimeObserver):
42
42
  # Connection specific state
43
43
  self.stream_sid = None
44
44
  self.latest_media_timestamp = 0
45
- self.last_assistant_item: Optional[str] = None
45
+ self.last_assistant_item: str | None = None
46
46
  self.mark_queue: list[str] = []
47
- self.response_start_timestamp_socket: Optional[int] = None
47
+ self.response_start_timestamp_socket: int | None = None
48
48
 
49
49
  async def on_event(self, event: RealtimeEvent) -> None:
50
50
  """Receive events from the OpenAI Realtime API, send audio back to websocket."""
@@ -3,10 +3,10 @@
3
3
  # SPDX-License-Identifier: Apache-2.0
4
4
 
5
5
  import json
6
- from collections.abc import AsyncGenerator
6
+ from collections.abc import AsyncGenerator, Callable
7
7
  from contextlib import asynccontextmanager
8
8
  from logging import Logger, getLogger
9
- from typing import TYPE_CHECKING, Any, Callable, Optional, Union
9
+ from typing import TYPE_CHECKING, Any
10
10
 
11
11
  from ......doc_utils import export_module
12
12
  from ......import_utils import optional_import_block, require_optional_import
@@ -41,8 +41,8 @@ class GeminiRealtimeClient(RealtimeClientBase):
41
41
  def __init__(
42
42
  self,
43
43
  *,
44
- llm_config: Union[LLMConfig, dict[str, Any]],
45
- logger: Optional[Logger] = None,
44
+ llm_config: LLMConfig | dict[str, Any],
45
+ logger: Logger | None = None,
46
46
  ) -> None:
47
47
  """(Experimental) Client for Gemini Realtime API.
48
48
 
@@ -54,7 +54,7 @@ class GeminiRealtimeClient(RealtimeClientBase):
54
54
  self._llm_config = llm_config
55
55
  self._logger = logger
56
56
 
57
- self._connection: Optional["ClientConnection"] = None
57
+ self._connection: ClientConnection | None = None
58
58
  config = llm_config["config_list"][0]
59
59
 
60
60
  self._model: str = config["model"]
@@ -252,8 +252,8 @@ class GeminiRealtimeClient(RealtimeClientBase):
252
252
 
253
253
  @classmethod
254
254
  def get_factory(
255
- cls, llm_config: Union[LLMConfig, dict[str, Any]], logger: Logger, **kwargs: Any
256
- ) -> Optional[Callable[[], "RealtimeClientProtocol"]]:
255
+ cls, llm_config: LLMConfig | dict[str, Any], logger: Logger, **kwargs: Any
256
+ ) -> Callable[[], "RealtimeClientProtocol"] | None:
257
257
  """Create a Realtime API client.
258
258
 
259
259
  Args:
@@ -2,10 +2,10 @@
2
2
  #
3
3
  # SPDX-License-Identifier: Apache-2.0
4
4
 
5
- from collections.abc import AsyncGenerator
5
+ from collections.abc import AsyncGenerator, Callable
6
6
  from contextlib import asynccontextmanager
7
7
  from logging import Logger, getLogger
8
- from typing import TYPE_CHECKING, Any, Callable, Optional, Union
8
+ from typing import TYPE_CHECKING, Any
9
9
 
10
10
  from ......doc_utils import export_module
11
11
  from ......import_utils import optional_import_block, require_optional_import
@@ -36,8 +36,8 @@ class OpenAIRealtimeClient(RealtimeClientBase):
36
36
  def __init__(
37
37
  self,
38
38
  *,
39
- llm_config: Union[LLMConfig, dict[str, Any]],
40
- logger: Optional[Logger] = None,
39
+ llm_config: LLMConfig | dict[str, Any],
40
+ logger: Logger | None = None,
41
41
  ) -> None:
42
42
  """(Experimental) Client for OpenAI Realtime API.
43
43
 
@@ -49,7 +49,7 @@ class OpenAIRealtimeClient(RealtimeClientBase):
49
49
  self._llm_config = llm_config
50
50
  self._logger = logger
51
51
 
52
- self._connection: Optional["AsyncRealtimeConnection"] = None
52
+ self._connection: AsyncRealtimeConnection | None = None
53
53
 
54
54
  self.config = llm_config["config_list"][0]
55
55
  # model is passed to self._client.beta.realtime.connect function later
@@ -57,7 +57,7 @@ class OpenAIRealtimeClient(RealtimeClientBase):
57
57
  self._voice: str = self.config.get("voice", "alloy")
58
58
  self._temperature: float = llm_config.get("temperature", 0.8) # type: ignore[union-attr]
59
59
 
60
- self._client: Optional["AsyncOpenAI"] = None
60
+ self._client: AsyncOpenAI | None = None
61
61
 
62
62
  @property
63
63
  def logger(self) -> Logger:
@@ -198,8 +198,8 @@ class OpenAIRealtimeClient(RealtimeClientBase):
198
198
 
199
199
  @classmethod
200
200
  def get_factory(
201
- cls, llm_config: Union[LLMConfig, dict[str, Any]], logger: Logger, **kwargs: Any
202
- ) -> Optional[Callable[[], "RealtimeClientProtocol"]]:
201
+ cls, llm_config: LLMConfig | dict[str, Any], logger: Logger, **kwargs: Any
202
+ ) -> Callable[[], "RealtimeClientProtocol"] | None:
203
203
  """Create a Realtime API client.
204
204
 
205
205
  Args:
@@ -3,10 +3,10 @@
3
3
  # SPDX-License-Identifier: Apache-2.0
4
4
 
5
5
  import json
6
- from collections.abc import AsyncGenerator
6
+ from collections.abc import AsyncGenerator, Callable
7
7
  from contextlib import asynccontextmanager
8
8
  from logging import Logger, getLogger
9
- from typing import TYPE_CHECKING, Any, Callable, Optional, Union
9
+ from typing import TYPE_CHECKING, Any
10
10
 
11
11
  from autogen.import_utils import optional_import_block, require_optional_import
12
12
 
@@ -37,9 +37,9 @@ class OpenAIRealtimeWebRTCClient(RealtimeClientBase):
37
37
  def __init__(
38
38
  self,
39
39
  *,
40
- llm_config: Union[LLMConfig, dict[str, Any]],
40
+ llm_config: LLMConfig | dict[str, Any],
41
41
  websocket: "WebSocket",
42
- logger: Optional[Logger] = None,
42
+ logger: Logger | None = None,
43
43
  ) -> None:
44
44
  """(Experimental) Client for OpenAI Realtime API.
45
45
 
@@ -218,8 +218,8 @@ class OpenAIRealtimeWebRTCClient(RealtimeClientBase):
218
218
 
219
219
  @classmethod
220
220
  def get_factory(
221
- cls, llm_config: Union[LLMConfig, dict[str, Any]], logger: Logger, **kwargs: Any
222
- ) -> Optional[Callable[[], "RealtimeClientProtocol"]]:
221
+ cls, llm_config: LLMConfig | dict[str, Any], logger: Logger, **kwargs: Any
222
+ ) -> Callable[[], "RealtimeClientProtocol"] | None:
223
223
  """Create a Realtime API client.
224
224
 
225
225
  Args:
@@ -3,9 +3,10 @@
3
3
  # SPDX-License-Identifier: Apache-2.0
4
4
 
5
5
  import asyncio
6
- from collections.abc import AsyncGenerator
6
+ from collections.abc import AsyncGenerator, Callable
7
+ from contextlib import AbstractAsyncContextManager
7
8
  from logging import Logger
8
- from typing import Any, AsyncContextManager, Callable, Literal, Optional, Protocol, TypeVar, Union, runtime_checkable
9
+ from typing import Any, Literal, Protocol, TypeVar, runtime_checkable
9
10
 
10
11
  from asyncer import create_task_group
11
12
 
@@ -66,7 +67,7 @@ class RealtimeClientProtocol(Protocol):
66
67
  """
67
68
  ...
68
69
 
69
- def connect(self) -> AsyncContextManager[None]: ...
70
+ def connect(self) -> AbstractAsyncContextManager[None]: ...
70
71
 
71
72
  def read_events(self) -> AsyncGenerator[RealtimeEvent, None]:
72
73
  """Read events from a Realtime Client."""
@@ -89,8 +90,8 @@ class RealtimeClientProtocol(Protocol):
89
90
 
90
91
  @classmethod
91
92
  def get_factory(
92
- cls, llm_config: Union[LLMConfig, dict[str, Any]], logger: Logger, **kwargs: Any
93
- ) -> Optional[Callable[[], "RealtimeClientProtocol"]]:
93
+ cls, llm_config: LLMConfig | dict[str, Any], logger: Logger, **kwargs: Any
94
+ ) -> Callable[[], "RealtimeClientProtocol"] | None:
94
95
  """Create a Realtime API client.
95
96
 
96
97
  Args:
@@ -108,10 +109,10 @@ class RealtimeClientBase:
108
109
  def __init__(self):
109
110
  self._eventQueue = asyncio.Queue()
110
111
 
111
- async def add_event(self, event: Optional[RealtimeEvent]):
112
+ async def add_event(self, event: RealtimeEvent | None):
112
113
  await self._eventQueue.put(event)
113
114
 
114
- async def get_event(self) -> Optional[RealtimeEvent]:
115
+ async def get_event(self) -> RealtimeEvent | None:
115
116
  return await self._eventQueue.get()
116
117
 
117
118
  async def _read_from_connection_task(self):
@@ -134,7 +135,7 @@ class RealtimeClientBase:
134
135
  break
135
136
 
136
137
  async def queue_input_audio_buffer_delta(self, audio: str) -> None:
137
- """queue InputAudioBufferDelta.
138
+ """Queue InputAudioBufferDelta.
138
139
 
139
140
  Args:
140
141
  audio (str): The audio.
@@ -170,7 +171,7 @@ def register_realtime_client() -> Callable[[type[T]], type[T]]:
170
171
 
171
172
 
172
173
  @export_module("autogen.agentchat.realtime.experimental.clients")
173
- def get_client(llm_config: Union[LLMConfig, dict[str, Any]], logger: Logger, **kwargs: Any) -> "RealtimeClientProtocol":
174
+ def get_client(llm_config: LLMConfig | dict[str, Any], logger: Logger, **kwargs: Any) -> "RealtimeClientProtocol":
174
175
  """Get a registered Realtime API client.
175
176
 
176
177
  Args:
@@ -2,9 +2,10 @@
2
2
  #
3
3
  # SPDX-License-Identifier: Apache-2.0
4
4
 
5
+ from collections.abc import Callable
5
6
  from dataclasses import dataclass
6
7
  from logging import Logger, getLogger
7
- from typing import Any, Callable, Optional, TypeVar, Union
8
+ from typing import Any, TypeVar
8
9
 
9
10
  from anyio import lowlevel
10
11
  from asyncer import create_task_group
@@ -35,11 +36,11 @@ class RealtimeAgent:
35
36
  self,
36
37
  *,
37
38
  name: str,
38
- audio_adapter: Optional[RealtimeObserver] = None,
39
+ audio_adapter: RealtimeObserver | None = None,
39
40
  system_message: str = "You are a helpful AI Assistant.",
40
- llm_config: Optional[Union[LLMConfig, dict[str, Any]]] = None,
41
- logger: Optional[Logger] = None,
42
- observers: Optional[list[RealtimeObserver]] = None,
41
+ llm_config: LLMConfig | dict[str, Any] | None = None,
42
+ logger: Logger | None = None,
43
+ observers: list[RealtimeObserver] | None = None,
43
44
  **client_kwargs: Any,
44
45
  ):
45
46
  """(Experimental) Agent for interacting with the Realtime Clients.
@@ -127,9 +128,9 @@ class RealtimeAgent:
127
128
  def register_realtime_function(
128
129
  self,
129
130
  *,
130
- name: Optional[str] = None,
131
- description: Optional[str] = None,
132
- ) -> Callable[[Union[F, Tool]], Tool]:
131
+ name: str | None = None,
132
+ description: str | None = None,
133
+ ) -> Callable[[F | Tool], Tool]:
133
134
  """Decorator for registering a function to be used by an agent.
134
135
 
135
136
  Args:
@@ -140,7 +141,7 @@ class RealtimeAgent:
140
141
  Callable[[Union[F, Tool]], Tool]: The decorator for registering a function.
141
142
  """
142
143
 
143
- def _decorator(func_or_tool: Union[F, Tool]) -> Tool:
144
+ def _decorator(func_or_tool: F | Tool) -> Tool:
144
145
  """Decorator for registering a function to be used by an agent.
145
146
 
146
147
  Args:
@@ -4,7 +4,7 @@
4
4
 
5
5
  from abc import ABC, abstractmethod
6
6
  from logging import Logger, getLogger
7
- from typing import TYPE_CHECKING, Optional
7
+ from typing import TYPE_CHECKING
8
8
 
9
9
  from anyio import Event
10
10
 
@@ -24,14 +24,14 @@ global_logger = getLogger(__name__)
24
24
  class RealtimeObserver(ABC):
25
25
  """Observer for the OpenAI Realtime API."""
26
26
 
27
- def __init__(self, *, logger: Optional[Logger] = None) -> None:
27
+ def __init__(self, *, logger: Logger | None = None) -> None:
28
28
  """Observer for the OpenAI Realtime API.
29
29
 
30
30
  Args:
31
31
  logger (Logger): The logger for the observer.
32
32
  """
33
33
  self._ready_event = Event()
34
- self._agent: Optional[RealtimeAgent] = None
34
+ self._agent: RealtimeAgent | None = None
35
35
  self._logger = logger
36
36
 
37
37
  @property
@@ -5,7 +5,8 @@
5
5
  import logging
6
6
  import warnings
7
7
  from collections import defaultdict
8
- from typing import TYPE_CHECKING, Any, Callable, Optional, TypeVar, Union
8
+ from collections.abc import Callable
9
+ from typing import TYPE_CHECKING, Any, Optional, TypeVar
9
10
 
10
11
  import anyio
11
12
  from asyncer import asyncify, create_task_group, syncify
@@ -42,7 +43,7 @@ logger = logging.getLogger(__name__)
42
43
  F = TypeVar("F", bound=Callable[..., Any])
43
44
 
44
45
 
45
- def message_to_dict(message: Union[dict[str, Any], str]) -> dict[str, Any]:
46
+ def message_to_dict(message: dict[str, Any] | str) -> dict[str, Any]:
46
47
  if isinstance(message, str):
47
48
  return {"content": message}
48
49
  elif isinstance(message, dict):
@@ -51,9 +52,8 @@ def message_to_dict(message: Union[dict[str, Any], str]) -> dict[str, Any]:
51
52
  return dict(message)
52
53
 
53
54
 
54
- def parse_oai_message(message: Union[dict[str, Any], str], role: str, adressee: Agent) -> dict[str, Any]:
55
- """
56
- Parse a message into an OpenAI-compatible message format.
55
+ def parse_oai_message(message: dict[str, Any] | str, role: str, adressee: Agent) -> dict[str, Any]:
56
+ """Parse a message into an OpenAI-compatible message format.
57
57
 
58
58
  Args:
59
59
  message: The message to parse.
@@ -111,9 +111,9 @@ class SwarmableAgent(Agent):
111
111
  self,
112
112
  name: str,
113
113
  system_message: str = "You are a helpful AI Assistant.",
114
- is_termination_msg: Optional[Callable[..., bool]] = None,
115
- description: Optional[str] = None,
116
- silent: Optional[bool] = None,
114
+ is_termination_msg: Callable[..., bool] | None = None,
115
+ description: str | None = None,
116
+ silent: bool | None = None,
117
117
  ):
118
118
  self._oai_messages: dict[Agent, Any] = defaultdict(list)
119
119
 
@@ -156,20 +156,20 @@ class SwarmableAgent(Agent):
156
156
 
157
157
  def send(
158
158
  self,
159
- message: Union[dict[str, Any], str],
159
+ message: dict[str, Any] | str,
160
160
  recipient: Agent,
161
- request_reply: Optional[bool] = None,
162
- silent: Optional[bool] = False,
161
+ request_reply: bool | None = None,
162
+ silent: bool | None = False,
163
163
  ) -> None:
164
164
  self._oai_messages[recipient].append(parse_oai_message(message, "assistant", recipient))
165
165
  recipient.receive(message, self, request_reply)
166
166
 
167
167
  def receive(
168
168
  self,
169
- message: Union[dict[str, Any], str],
169
+ message: dict[str, Any] | str,
170
170
  sender: Agent,
171
- request_reply: Optional[bool] = None,
172
- silent: Optional[bool] = False,
171
+ request_reply: bool | None = None,
172
+ silent: bool | None = False,
173
173
  ) -> None:
174
174
  self._oai_messages[sender].append(parse_oai_message(message, "user", self))
175
175
  if request_reply is False or (request_reply is None and self.reply_at_receive[sender] is False):
@@ -180,10 +180,10 @@ class SwarmableAgent(Agent):
180
180
 
181
181
  def generate_reply(
182
182
  self,
183
- messages: Optional[list[dict[str, Any]]] = None,
183
+ messages: list[dict[str, Any]] | None = None,
184
184
  sender: Optional["Agent"] = None,
185
185
  **kwargs: Any,
186
- ) -> Union[str, dict[str, Any], None]:
186
+ ) -> str | dict[str, Any] | None:
187
187
  if messages is None:
188
188
  if sender is None:
189
189
  raise ValueError("Either messages or sender must be provided.")
@@ -195,20 +195,20 @@ class SwarmableAgent(Agent):
195
195
 
196
196
  def check_termination_and_human_reply(
197
197
  self,
198
- messages: Optional[list[dict[str, Any]]] = None,
199
- sender: Optional[Agent] = None,
200
- config: Optional[Any] = None,
201
- ) -> tuple[bool, Union[str, None]]:
198
+ messages: list[dict[str, Any]] | None = None,
199
+ sender: Agent | None = None,
200
+ config: Any | None = None,
201
+ ) -> tuple[bool, str | None]:
202
202
  raise NotImplementedError
203
203
 
204
204
  def initiate_chat(
205
205
  self,
206
206
  recipient: ConversableAgent,
207
- message: Union[dict[str, Any], str],
207
+ message: dict[str, Any] | str,
208
208
  clear_history: bool = True,
209
- silent: Optional[bool] = False,
210
- cache: Optional[AbstractCache] = None,
211
- summary_args: Optional[dict[str, Any]] = {},
209
+ silent: bool | None = False,
210
+ cache: AbstractCache | None = None,
211
+ summary_args: dict[str, Any] | None = {},
212
212
  **kwargs: dict[str, Any],
213
213
  ) -> ChatResult:
214
214
  _chat_info = locals().copy()
@@ -235,25 +235,25 @@ class SwarmableAgent(Agent):
235
235
 
236
236
  async def a_generate_reply(
237
237
  self,
238
- messages: Optional[list[dict[str, Any]]] = None,
238
+ messages: list[dict[str, Any]] | None = None,
239
239
  sender: Optional["Agent"] = None,
240
240
  **kwargs: Any,
241
- ) -> Union[str, dict[str, Any], None]:
241
+ ) -> str | dict[str, Any] | None:
242
242
  return self.generate_reply(messages=messages, sender=sender, **kwargs)
243
243
 
244
244
  async def a_receive(
245
245
  self,
246
- message: Union[dict[str, Any], str],
246
+ message: dict[str, Any] | str,
247
247
  sender: "Agent",
248
- request_reply: Optional[bool] = None,
248
+ request_reply: bool | None = None,
249
249
  ) -> None:
250
250
  self.receive(message, sender, request_reply)
251
251
 
252
252
  async def a_send(
253
253
  self,
254
- message: Union[dict[str, Any], str],
254
+ message: dict[str, Any] | str,
255
255
  recipient: "Agent",
256
- request_reply: Optional[bool] = None,
256
+ request_reply: bool | None = None,
257
257
  ) -> None:
258
258
  self.send(message, recipient, request_reply)
259
259
 
@@ -262,7 +262,7 @@ class SwarmableAgent(Agent):
262
262
  """A dictionary of conversations from agent to list of messages."""
263
263
  return self._oai_messages
264
264
 
265
- def last_message(self, agent: Optional[Agent] = None) -> Optional[dict[str, Any]]:
265
+ def last_message(self, agent: Agent | None = None) -> dict[str, Any] | None:
266
266
  if agent is None:
267
267
  n_conversations = len(self._oai_messages)
268
268
  if n_conversations == 0:
@@ -293,7 +293,7 @@ class SwarmableAgent(Agent):
293
293
  def _raise_exception_on_async_reply_functions(self) -> None:
294
294
  pass
295
295
 
296
- def set_ui_tools(self, tools: Optional[list] = None) -> None:
296
+ def set_ui_tools(self, tools: list | None = None) -> None:
297
297
  """Set UI tools for the agent."""
298
298
  pass
299
299
 
@@ -302,7 +302,7 @@ class SwarmableAgent(Agent):
302
302
  pass
303
303
 
304
304
  @staticmethod
305
- def _last_msg_as_summary(sender: Agent, recipient: Agent, summary_args: Optional[dict[str, Any]]) -> str:
305
+ def _last_msg_as_summary(sender: Agent, recipient: Agent, summary_args: dict[str, Any] | None) -> str:
306
306
  """Get a chat summary from the last message of the recipient."""
307
307
  summary = ""
308
308
  try:
@@ -324,9 +324,9 @@ if TYPE_CHECKING:
324
324
  def _create_swarmable_agent(
325
325
  name: str,
326
326
  system_message: str,
327
- is_termination_msg: Optional[Callable[..., bool]],
328
- description: Optional[str],
329
- silent: Optional[bool],
327
+ is_termination_msg: Callable[..., bool] | None,
328
+ description: str | None,
329
+ silent: bool | None,
330
330
  ) -> LLMAgent:
331
331
  return SwarmableAgent(
332
332
  name=name,
@@ -343,7 +343,7 @@ class SwarmableRealtimeAgent(SwarmableAgent):
343
343
  realtime_agent: "RealtimeAgent",
344
344
  initial_agent: ConversableAgent,
345
345
  agents: list[ConversableAgent],
346
- question_message: Optional[str] = None,
346
+ question_message: str | None = None,
347
347
  ) -> None:
348
348
  self._initial_agent = initial_agent
349
349
  self._agents = agents
@@ -401,10 +401,10 @@ class SwarmableRealtimeAgent(SwarmableAgent):
401
401
 
402
402
  def check_termination_and_human_reply(
403
403
  self,
404
- messages: Optional[list[dict[str, Any]]] = None,
405
- sender: Optional[Agent] = None,
406
- config: Optional[Any] = None,
407
- ) -> tuple[bool, Optional[str]]:
404
+ messages: list[dict[str, Any]] | None = None,
405
+ sender: Agent | None = None,
406
+ config: Any | None = None,
407
+ ) -> tuple[bool, str | None]:
408
408
  """Check if the conversation should be terminated and if the agent should reply.
409
409
 
410
410
  Called when its agents turn in the chat conversation.
@@ -431,7 +431,7 @@ class SwarmableRealtimeAgent(SwarmableAgent):
431
431
  def start_chat(self) -> None:
432
432
  raise NotImplementedError
433
433
 
434
- def configure_realtime_agent(self, system_message: Optional[str]) -> None:
434
+ def configure_realtime_agent(self, system_message: str | None) -> None:
435
435
  realtime_agent = self._realtime_agent
436
436
 
437
437
  logger = realtime_agent.logger
@@ -466,8 +466,8 @@ def register_swarm(
466
466
  realtime_agent: "RealtimeAgent",
467
467
  initial_agent: ConversableAgent,
468
468
  agents: list[ConversableAgent],
469
- system_message: Optional[str] = None,
470
- question_message: Optional[str] = None,
469
+ system_message: str | None = None,
470
+ question_message: str | None = None,
471
471
  ) -> None:
472
472
  """Create a SwarmableRealtimeAgent.
473
473
 
@@ -4,7 +4,8 @@
4
4
  #
5
5
  # Portions derived from https://github.com/microsoft/autogen are under the MIT License.
6
6
  # SPDX-License-Identifier: MIT
7
- from typing import Any, Callable, Literal, Optional, Union
7
+ from collections.abc import Callable
8
+ from typing import Any, Literal
8
9
 
9
10
  from ..doc_utils import export_module
10
11
  from ..llm_config import LLMConfig
@@ -35,15 +36,15 @@ class UserProxyAgent(ConversableAgent):
35
36
  def __init__(
36
37
  self,
37
38
  name: str,
38
- is_termination_msg: Optional[Callable[[dict[str, Any]], bool]] = None,
39
- max_consecutive_auto_reply: Optional[int] = None,
39
+ is_termination_msg: Callable[[dict[str, Any]], bool] | None = None,
40
+ max_consecutive_auto_reply: int | None = None,
40
41
  human_input_mode: Literal["ALWAYS", "TERMINATE", "NEVER"] = "ALWAYS",
41
- function_map: Optional[dict[str, Callable[..., Any]]] = None,
42
- code_execution_config: Union[dict[str, Any], Literal[False]] = {},
43
- default_auto_reply: Optional[Union[str, dict[str, Any]]] = "",
44
- llm_config: Optional[Union[LLMConfig, dict[str, Any], Literal[False]]] = False,
45
- system_message: Optional[Union[str, list[str]]] = "",
46
- description: Optional[str] = None,
42
+ function_map: dict[str, Callable[..., Any]] | None = None,
43
+ code_execution_config: dict[str, Any] | Literal[False] = {},
44
+ default_auto_reply: str | dict[str, Any] | None = "",
45
+ llm_config: LLMConfig | dict[str, Any] | Literal[False] | None = False,
46
+ system_message: str | list[str] | None = "",
47
+ description: str | None = None,
47
48
  **kwargs: Any,
48
49
  ):
49
50
  """Args:
@@ -5,14 +5,14 @@
5
5
  # Portions derived from https://github.com/microsoft/autogen are under the MIT License.
6
6
  # SPDX-License-Identifier: MIT
7
7
  import re
8
- from typing import Any, Optional, Union
8
+ from typing import Any
9
9
 
10
10
  from ..doc_utils import export_module
11
11
  from .agent import Agent
12
12
 
13
13
 
14
14
  def consolidate_chat_info(
15
- chat_info: Union[dict[str, Any], list[dict[str, Any]]], uniform_sender: Optional[Agent] = None
15
+ chat_info: dict[str, Any] | list[dict[str, Any]], uniform_sender: Agent | None = None
16
16
  ) -> None:
17
17
  if isinstance(chat_info, dict):
18
18
  chat_info = [chat_info]
@@ -101,7 +101,7 @@ def gather_usage_summary(agents: list[Agent]) -> dict[str, dict[str, Any]]:
101
101
  }
102
102
 
103
103
 
104
- def parse_tags_from_content(tag: str, content: Union[str, list[dict[str, Any]]]) -> list[dict[str, Any]]:
104
+ def parse_tags_from_content(tag: str, content: str | list[dict[str, Any]]) -> list[dict[str, Any]]:
105
105
  """Parses HTML style tags from message contents.
106
106
 
107
107
  The parsing is done by looking for patterns in the text that match the format of HTML tags. The tag to be parsed is
@@ -2,7 +2,7 @@
2
2
  #
3
3
  # SPDX-License-Identifier: Apache-2.0
4
4
 
5
- from typing import Any, Optional
5
+ from typing import Any
6
6
 
7
7
  from .... import Agent, ConversableAgent, OpenAIWrapper
8
8
  from ....doc_utils import export_module
@@ -16,7 +16,8 @@ class TimeReplyAgent(ConversableAgent):
16
16
 
17
17
  Use it is as a reference for creating new agents with a reply-based approach (as opposed to tool-based).
18
18
 
19
- This agent will return the date and time whenever it needs to reply."""
19
+ This agent will return the date and time whenever it needs to reply.
20
+ """
20
21
 
21
22
  DEFAULT_SYSTEM_MESSAGE = "You are a calendar agent that just returns the date and time."
22
23
 
@@ -51,9 +52,9 @@ class TimeReplyAgent(ConversableAgent):
51
52
  # may even contain another AG2 workflow inside it
52
53
  def get_date_time_reply(
53
54
  agent: ConversableAgent,
54
- messages: Optional[list[dict[str, Any]]] = None,
55
- sender: Optional[Agent] = None,
56
- config: Optional[OpenAIWrapper] = None,
55
+ messages: list[dict[str, Any]] | None = None,
56
+ sender: Agent | None = None,
57
+ config: OpenAIWrapper | None = None,
57
58
  ) -> tuple[bool, dict[str, Any]]:
58
59
  from datetime import datetime
59
60
 
@@ -17,7 +17,8 @@ class TimeToolAgent(ConversableAgent):
17
17
 
18
18
  Use it is as a reference for creating new agents with a tool-based approach (as opposed to reply-based).
19
19
 
20
- This agent will call the TimeTool and return the date and time whenever it needs to reply."""
20
+ This agent will call the TimeTool and return the date and time whenever it needs to reply.
21
+ """
21
22
 
22
23
  DEFAULT_SYSTEM_MESSAGE = (
23
24
  "You are a calendar agent that uses tools to return the date and time. "