ag2 0.9.7__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.7.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 +292 -290
  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 +2 -1
  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 +113 -139
  186. autogen/oai/client_utils.py +3 -3
  187. autogen/oai/cohere.py +34 -11
  188. autogen/oai/gemini.py +39 -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 +19 -9
  200. autogen/oai/openai_responses.py +40 -17
  201. autogen/oai/openai_utils.py +48 -38
  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 +8 -6
  230. autogen/types.py +2 -2
  231. autogen/version.py +1 -1
  232. ag2-0.9.7.dist-info/RECORD +0 -421
  233. autogen/llm_config.py +0 -385
  234. {ag2-0.9.7.dist-info → ag2-0.9.8.post1.dist-info}/WHEEL +0 -0
  235. {ag2-0.9.7.dist-info → ag2-0.9.8.post1.dist-info}/licenses/LICENSE +0 -0
  236. {ag2-0.9.7.dist-info → ag2-0.9.8.post1.dist-info}/licenses/NOTICE.md +0 -0
@@ -4,7 +4,8 @@
4
4
 
5
5
 
6
6
  from abc import ABC
7
- from typing import Annotated, Any, Callable, Literal, Optional, Union
7
+ from collections.abc import Callable
8
+ from typing import Annotated, Any, Literal, Union
8
9
  from uuid import UUID, uuid4
9
10
 
10
11
  from pydantic import BaseModel, Field, create_model
@@ -18,11 +19,11 @@ __all__ = ["BaseEvent", "get_annotated_type_for_event_classes", "get_event_class
18
19
  class BaseEvent(BaseModel, ABC):
19
20
  uuid: UUID
20
21
 
21
- def __init__(self, uuid: Optional[UUID] = None, **kwargs: Any) -> None:
22
+ def __init__(self, uuid: UUID | None = None, **kwargs: Any) -> None:
22
23
  uuid = uuid or uuid4()
23
24
  super().__init__(uuid=uuid, **kwargs)
24
25
 
25
- def print(self, f: Optional[Callable[..., Any]] = None) -> None:
26
+ def print(self, f: Callable[..., Any] | None = None) -> None:
26
27
  """Print event
27
28
 
28
29
  Args:
@@ -70,7 +71,7 @@ def wrap_event(event_cls: type[BaseEvent]) -> type[BaseModel]:
70
71
  else:
71
72
  super().__init__(content=event_cls(*args, **data), **data)
72
73
 
73
- def print(self, f: Optional[Callable[..., Any]] = None) -> None:
74
+ def print(self, f: Callable[..., Any] | None = None) -> None:
74
75
  self.content.print(f) # type: ignore[attr-defined]
75
76
 
76
77
  wrapper_cls = create_model(event_cls.__name__, __base__=WrapperBase)
@@ -91,7 +92,7 @@ def wrap_event(event_cls: type[BaseEvent]) -> type[BaseModel]:
91
92
  @export_module("autogen.events")
92
93
  def get_annotated_type_for_event_classes() -> type[Any]:
93
94
  # this is a dynamic type so we need to disable the type checker
94
- union_type = Union[tuple(_event_classes.values())] # type: ignore[valid-type]
95
+ union_type = Union[tuple(_event_classes.values())] # type: ignore[valid-type] # noqa: UP007
95
96
  return Annotated[union_type, Field(discriminator="type")] # type: ignore[return-value]
96
97
 
97
98
 
@@ -2,7 +2,8 @@
2
2
  #
3
3
  # SPDX-License-Identifier: Apache-2.0
4
4
 
5
- from typing import Any, Callable, Literal, Optional, Union
5
+ from collections.abc import Callable
6
+ from typing import Any, Literal
6
7
  from uuid import UUID
7
8
 
8
9
  from pydantic import BaseModel
@@ -30,18 +31,18 @@ class ModelUsageSummary(BaseModel):
30
31
  class ActualUsageSummary(BaseModel):
31
32
  """Actual usage summary."""
32
33
 
33
- usages: Optional[list[ModelUsageSummary]] = None
34
+ usages: list[ModelUsageSummary] | None = None
34
35
  """List of model usage summaries."""
35
- total_cost: Optional[float] = None
36
+ total_cost: float | None = None
36
37
  """Total cost."""
37
38
 
38
39
 
39
40
  class TotalUsageSummary(BaseModel):
40
41
  """Total usage summary."""
41
42
 
42
- usages: Optional[list[ModelUsageSummary]] = None
43
+ usages: list[ModelUsageSummary] | None = None
43
44
  """List of model usage summaries."""
44
- total_cost: Optional[float] = None
45
+ total_cost: float | None = None
45
46
  """Total cost."""
46
47
 
47
48
 
@@ -49,7 +50,7 @@ Mode = Literal["both", "total", "actual"]
49
50
 
50
51
 
51
52
  def _change_usage_summary_format(
52
- actual_usage_summary: Optional[dict[str, Any]] = None, total_usage_summary: Optional[dict[str, Any]] = None
53
+ actual_usage_summary: dict[str, Any] | None = None, total_usage_summary: dict[str, Any] | None = None
53
54
  ) -> dict[str, dict[str, Any]]:
54
55
  summary: dict[str, Any] = {}
55
56
 
@@ -85,9 +86,9 @@ class UsageSummaryEvent(BaseEvent):
85
86
  def __init__(
86
87
  self,
87
88
  *,
88
- uuid: Optional[UUID] = None,
89
- actual_usage_summary: Optional[dict[str, Any]] = None,
90
- total_usage_summary: Optional[dict[str, Any]] = None,
89
+ uuid: UUID | None = None,
90
+ actual_usage_summary: dict[str, Any] | None = None,
91
+ total_usage_summary: dict[str, Any] | None = None,
91
92
  mode: Mode = "both",
92
93
  ):
93
94
  # print(f"{actual_usage_summary=}")
@@ -99,9 +100,9 @@ class UsageSummaryEvent(BaseEvent):
99
100
 
100
101
  def _print_usage(
101
102
  self,
102
- usage_summary: Union[ActualUsageSummary, TotalUsageSummary],
103
+ usage_summary: ActualUsageSummary | TotalUsageSummary,
103
104
  usage_type: str = "total",
104
- f: Optional[Callable[..., Any]] = None,
105
+ f: Callable[..., Any] | None = None,
105
106
  ) -> None:
106
107
  f = f or print
107
108
  word_from_type = "including" if usage_type == "total" else "excluding"
@@ -118,7 +119,7 @@ class UsageSummaryEvent(BaseEvent):
118
119
  flush=True,
119
120
  )
120
121
 
121
- def print(self, f: Optional[Callable[..., Any]] = None) -> None:
122
+ def print(self, f: Callable[..., Any] | None = None) -> None:
122
123
  f = f or print
123
124
 
124
125
  if self.total.usages is None:
@@ -152,10 +153,10 @@ class StreamEvent(BaseEvent):
152
153
  content: str
153
154
  """Content of the event."""
154
155
 
155
- def __init__(self, *, uuid: Optional[UUID] = None, content: str) -> None:
156
+ def __init__(self, *, uuid: UUID | None = None, content: str) -> None:
156
157
  super().__init__(uuid=uuid, content=content)
157
158
 
158
- def print(self, f: Optional[Callable[..., Any]] = None) -> None:
159
+ def print(self, f: Callable[..., Any] | None = None) -> None:
159
160
  f = f or print
160
161
 
161
162
  # Set the terminal text color to green
autogen/events/helpers.py CHANGED
@@ -2,8 +2,8 @@
2
2
  #
3
3
  # SPDX-License-Identifier: Apache-2.0
4
4
  import logging
5
+ from collections.abc import Callable
5
6
  from functools import wraps
6
- from typing import Callable
7
7
 
8
8
  from pydantic import BaseModel
9
9
 
@@ -4,7 +4,8 @@
4
4
 
5
5
 
6
6
  import json
7
- from typing import Any, Callable, Optional
7
+ from collections.abc import Callable
8
+ from typing import Any
8
9
  from uuid import UUID
9
10
 
10
11
  from .base_event import BaseEvent, wrap_event
@@ -21,9 +22,7 @@ class PrintEvent(BaseEvent):
21
22
  end: str
22
23
  """End of the print"""
23
24
 
24
- def __init__(
25
- self, *objects: Any, sep: str = " ", end: str = "\n", flush: bool = False, uuid: Optional[UUID] = None
26
- ):
25
+ def __init__(self, *objects: Any, sep: str = " ", end: str = "\n", flush: bool = False, uuid: UUID | None = None):
27
26
  objects_as_string = [self._to_json(x) for x in objects]
28
27
 
29
28
  super().__init__(uuid=uuid, objects=objects_as_string, sep=sep, end=end)
@@ -40,7 +39,7 @@ class PrintEvent(BaseEvent):
40
39
  return str(obj)
41
40
  # return repr(obj)
42
41
 
43
- def print(self, f: Optional[Callable[..., Any]] = None) -> None:
42
+ def print(self, f: Callable[..., Any] | None = None) -> None:
44
43
  f = f or print
45
44
 
46
45
  f(*self.objects, sep=self.sep, end=self.end, flush=True)
@@ -6,8 +6,7 @@
6
6
  # SPDX-License-Identifier: MIT
7
7
 
8
8
  import sys
9
- from importlib.metadata import version as get_version
10
- from typing import Any, Dict, Optional, Tuple, Type
9
+ from typing import Any
11
10
 
12
11
  from pydantic import BaseModel, create_model
13
12
  from pydantic.version import VERSION as PYDANTIC_VERSION
@@ -35,13 +34,13 @@ if PYDANTIC_V2:
35
34
  eval_type_lenient as evaluate_forwardref,
36
35
  )
37
36
 
38
- def model_schema(model: Type[BaseModel]) -> Dict[str, Any]:
37
+ def model_schema(model: type[BaseModel]) -> dict[str, Any]:
39
38
  return model.model_json_schema()
40
39
 
41
- def get_config_base(config_data: Optional[ConfigDict] = None) -> ConfigDict:
40
+ def get_config_base(config_data: ConfigDict | None = None) -> ConfigDict:
42
41
  return config_data or ConfigDict(**default_pydantic_config) # type: ignore[typeddict-item]
43
42
 
44
- def get_aliases(model: Type[BaseModel]) -> Tuple[str, ...]:
43
+ def get_aliases(model: type[BaseModel]) -> tuple[str, ...]:
45
44
  return tuple(f.alias or name for name, f in model.model_fields.items())
46
45
 
47
46
  class CreateBaseModel(BaseModel):
@@ -53,13 +52,13 @@ else:
53
52
  from pydantic.typing import evaluate_forwardref as evaluate_forwardref # type: ignore[no-redef]
54
53
  from pydantic.config import get_config, ConfigDict, BaseConfig
55
54
 
56
- def get_config_base(config_data: Optional[ConfigDict] = None) -> Type[BaseConfig]: # type: ignore[misc,no-any-unimported]
55
+ def get_config_base(config_data: ConfigDict | None = None) -> type[BaseConfig]: # type: ignore[misc,no-any-unimported]
57
56
  return get_config(config_data or ConfigDict(**default_pydantic_config)) # type: ignore[typeddict-item,no-any-unimported,no-any-return]
58
57
 
59
- def model_schema(model: Type[BaseModel]) -> Dict[str, Any]:
58
+ def model_schema(model: type[BaseModel]) -> dict[str, Any]:
60
59
  return model.schema()
61
60
 
62
- def get_aliases(model: Type[BaseModel]) -> Tuple[str, ...]:
61
+ def get_aliases(model: type[BaseModel]) -> tuple[str, ...]:
63
62
  return tuple(f.alias or name for name, f in model.__fields__.items()) # type: ignore[attr-defined]
64
63
 
65
64
  class CreateBaseModel(BaseModel): # type: ignore[no-redef]
@@ -69,12 +68,8 @@ else:
69
68
  arbitrary_types_allowed = True
70
69
 
71
70
 
72
- ANYIO_V3 = get_version("anyio").startswith("3.")
71
+ if sys.version_info < (3, 11):
72
+ from exceptiongroup import ExceptionGroup as ExceptionGroup
73
73
 
74
- if ANYIO_V3:
75
- from anyio import ExceptionGroup as ExceptionGroup # type: ignore[attr-defined]
76
74
  else:
77
- if sys.version_info < (3, 11):
78
- from exceptiongroup import ExceptionGroup as ExceptionGroup
79
- else:
80
- ExceptionGroup = ExceptionGroup
75
+ ExceptionGroup = ExceptionGroup
@@ -6,27 +6,11 @@
6
6
  # SPDX-License-Identifier: MIT
7
7
 
8
8
  import inspect
9
+ from collections.abc import Awaitable, Callable, Sequence
9
10
  from copy import deepcopy
10
- from typing import (
11
- Any,
12
- Awaitable,
13
- Callable,
14
- Dict,
15
- List,
16
- Optional,
17
- Sequence,
18
- Tuple,
19
- Type,
20
- TypeVar,
21
- Union,
22
- )
11
+ from typing import Annotated, Any, TypeVar, get_args, get_origin
23
12
 
24
- from typing_extensions import (
25
- Annotated,
26
- ParamSpec,
27
- get_args,
28
- get_origin,
29
- )
13
+ from typing_extensions import ParamSpec
30
14
 
31
15
  from .._compat import ConfigDict, create_model, get_config_base
32
16
  from ..dependencies import Depends
@@ -47,16 +31,13 @@ T = TypeVar("T")
47
31
 
48
32
 
49
33
  def build_call_model(
50
- call: Union[
51
- Callable[P, T],
52
- Callable[P, Awaitable[T]],
53
- ],
34
+ call: Callable[P, T] | Callable[P, Awaitable[T]],
54
35
  *,
55
36
  cast: bool = True,
56
37
  use_cache: bool = True,
57
- is_sync: Optional[bool] = None,
38
+ is_sync: bool | None = None,
58
39
  extra_dependencies: Sequence[Depends] = (),
59
- pydantic_config: Optional[ConfigDict] = None,
40
+ pydantic_config: ConfigDict | None = None,
60
41
  ) -> CallModel[P, T]:
61
42
  name = getattr(call, "__name__", type(call).__name__)
62
43
 
@@ -72,17 +53,17 @@ def build_call_model(
72
53
  ):
73
54
  return_annotation = return_args[0]
74
55
 
75
- class_fields: Dict[str, Tuple[Any, Any]] = {}
76
- dependencies: Dict[str, CallModel[..., Any]] = {}
77
- custom_fields: Dict[str, CustomField] = {}
78
- positional_args: List[str] = []
79
- keyword_args: List[str] = []
80
- var_positional_arg: Optional[str] = None
81
- var_keyword_arg: Optional[str] = None
56
+ class_fields: dict[str, tuple[Any, Any]] = {}
57
+ dependencies: dict[str, CallModel[..., Any]] = {}
58
+ custom_fields: dict[str, CustomField] = {}
59
+ positional_args: list[str] = []
60
+ keyword_args: list[str] = []
61
+ var_positional_arg: str | None = None
62
+ var_keyword_arg: str | None = None
82
63
 
83
64
  for param_name, param in typed_params.parameters.items():
84
- dep: Optional[Depends] = None
85
- custom: Optional[CustomField] = None
65
+ dep: Depends | None = None
66
+ custom: CustomField | None = None
86
67
 
87
68
  if param.annotation is inspect.Parameter.empty:
88
69
  annotation = Any
@@ -173,7 +154,7 @@ def build_call_model(
173
154
  class_fields[param_name] = (annotation, default)
174
155
 
175
156
  else:
176
- class_fields[param_name] = class_fields.get(param_name, (Optional[annotation], None))
157
+ class_fields[param_name] = class_fields.get(param_name, (annotation | None, None))
177
158
 
178
159
  keyword_args.append(param_name)
179
160
 
@@ -189,7 +170,7 @@ def build_call_model(
189
170
  **class_fields,
190
171
  )
191
172
 
192
- response_model: Optional[Type[ResponseModel[T]]] = None
173
+ response_model: type[ResponseModel[T]] | None = None
193
174
  if cast and return_annotation and return_annotation is not inspect.Parameter.empty:
194
175
  response_model = create_model( # type: ignore[call-overload,assignment]
195
176
  "ResponseModel",
@@ -6,25 +6,15 @@
6
6
  # SPDX-License-Identifier: MIT
7
7
 
8
8
  from collections import namedtuple
9
+ from collections.abc import Awaitable, Callable, Generator, Iterable, Sequence
9
10
  from contextlib import AsyncExitStack, ExitStack
10
11
  from functools import partial
11
12
  from inspect import Parameter, unwrap
12
13
  from itertools import chain
13
14
  from typing import (
14
15
  Any,
15
- Awaitable,
16
- Callable,
17
- Dict,
18
- Generator,
19
16
  Generic,
20
- Iterable,
21
- List,
22
- Optional,
23
- Sequence,
24
- Tuple,
25
- Type,
26
17
  TypeVar,
27
- Union,
28
18
  )
29
19
 
30
20
  import anyio
@@ -54,26 +44,23 @@ class ResponseModel(BaseModel, Generic[T]):
54
44
 
55
45
 
56
46
  class CallModel(Generic[P, T]):
57
- call: Union[
58
- Callable[P, T],
59
- Callable[P, Awaitable[T]],
60
- ]
47
+ call: Callable[P, T] | Callable[P, Awaitable[T]]
61
48
  is_async: bool
62
49
  is_generator: bool
63
- model: Optional[Type[BaseModel]]
64
- response_model: Optional[Type[ResponseModel[T]]]
50
+ model: type[BaseModel] | None
51
+ response_model: type[ResponseModel[T]] | None
65
52
 
66
- params: Dict[str, Tuple[Any, Any]]
67
- alias_arguments: Tuple[str, ...]
53
+ params: dict[str, tuple[Any, Any]]
54
+ alias_arguments: tuple[str, ...]
68
55
 
69
- dependencies: Dict[str, "CallModel[..., Any]"]
56
+ dependencies: dict[str, "CallModel[..., Any]"]
70
57
  extra_dependencies: Iterable["CallModel[..., Any]"]
71
- sorted_dependencies: Tuple[Tuple["CallModel[..., Any]", int], ...]
72
- custom_fields: Dict[str, CustomField]
73
- keyword_args: Tuple[str, ...]
74
- positional_args: Tuple[str, ...]
75
- var_positional_arg: Optional[str]
76
- var_keyword_arg: Optional[str]
58
+ sorted_dependencies: tuple[tuple["CallModel[..., Any]", int], ...]
59
+ custom_fields: dict[str, CustomField]
60
+ keyword_args: tuple[str, ...]
61
+ positional_args: tuple[str, ...]
62
+ var_positional_arg: str | None
63
+ var_keyword_arg: str | None
77
64
 
78
65
  # Dependencies and custom fields
79
66
  use_cache: bool
@@ -105,7 +92,7 @@ class CallModel(Generic[P, T]):
105
92
  return getattr(call, "__name__", type(call).__name__)
106
93
 
107
94
  @property
108
- def flat_params(self) -> Dict[str, Tuple[Any, Any]]:
95
+ def flat_params(self) -> dict[str, tuple[Any, Any]]:
109
96
  params = self.params
110
97
  for d in (*self.dependencies.values(), *self.extra_dependencies):
111
98
  params.update(d.flat_params)
@@ -114,18 +101,18 @@ class CallModel(Generic[P, T]):
114
101
  @property
115
102
  def flat_dependencies(
116
103
  self,
117
- ) -> Dict[
104
+ ) -> dict[
118
105
  Callable[..., Any],
119
- Tuple[
106
+ tuple[
120
107
  "CallModel[..., Any]",
121
- Tuple[Callable[..., Any], ...],
108
+ tuple[Callable[..., Any], ...],
122
109
  ],
123
110
  ]:
124
- flat: Dict[
111
+ flat: dict[
125
112
  Callable[..., Any],
126
- Tuple[
113
+ tuple[
127
114
  CallModel[..., Any],
128
- Tuple[Callable[..., Any], ...],
115
+ tuple[Callable[..., Any], ...],
129
116
  ],
130
117
  ] = {}
131
118
 
@@ -144,24 +131,21 @@ class CallModel(Generic[P, T]):
144
131
  def __init__(
145
132
  self,
146
133
  /,
147
- call: Union[
148
- Callable[P, T],
149
- Callable[P, Awaitable[T]],
150
- ],
151
- model: Optional[Type[BaseModel]],
152
- params: Dict[str, Tuple[Any, Any]],
153
- response_model: Optional[Type[ResponseModel[T]]] = None,
134
+ call: Callable[P, T] | Callable[P, Awaitable[T]],
135
+ model: type[BaseModel] | None,
136
+ params: dict[str, tuple[Any, Any]],
137
+ response_model: type[ResponseModel[T]] | None = None,
154
138
  use_cache: bool = True,
155
139
  cast: bool = True,
156
140
  is_async: bool = False,
157
141
  is_generator: bool = False,
158
- dependencies: Optional[Dict[str, "CallModel[..., Any]"]] = None,
159
- extra_dependencies: Optional[Iterable["CallModel[..., Any]"]] = None,
160
- keyword_args: Optional[List[str]] = None,
161
- positional_args: Optional[List[str]] = None,
162
- var_positional_arg: Optional[str] = None,
163
- var_keyword_arg: Optional[str] = None,
164
- custom_fields: Optional[Dict[str, CustomField]] = None,
142
+ dependencies: dict[str, "CallModel[..., Any]"] | None = None,
143
+ extra_dependencies: Iterable["CallModel[..., Any]"] | None = None,
144
+ keyword_args: list[str] | None = None,
145
+ positional_args: list[str] | None = None,
146
+ var_positional_arg: str | None = None,
147
+ var_keyword_arg: str | None = None,
148
+ custom_fields: dict[str, CustomField] | None = None,
165
149
  ):
166
150
  self.call = call
167
151
  self.model = model
@@ -185,7 +169,7 @@ class CallModel(Generic[P, T]):
185
169
  self.extra_dependencies = extra_dependencies or ()
186
170
  self.custom_fields = custom_fields or {}
187
171
 
188
- sorted_dep: List[CallModel[..., Any]] = []
172
+ sorted_dep: list[CallModel[..., Any]] = []
189
173
  flat = self.flat_dependencies
190
174
  for calls in flat.values():
191
175
  _sort_dep(sorted_dep, calls, flat)
@@ -198,31 +182,20 @@ class CallModel(Generic[P, T]):
198
182
  def _solve(
199
183
  self,
200
184
  /,
201
- *args: Tuple[Any, ...],
202
- cache_dependencies: Dict[
203
- Union[
204
- Callable[P, T],
205
- Callable[P, Awaitable[T]],
206
- ],
185
+ *args: tuple[Any, ...],
186
+ cache_dependencies: dict[
187
+ Callable[P, T] | Callable[P, Awaitable[T]],
207
188
  T,
208
189
  ],
209
- dependency_overrides: Optional[
210
- Dict[
211
- Union[
212
- Callable[P, T],
213
- Callable[P, Awaitable[T]],
214
- ],
215
- Union[
216
- Callable[P, T],
217
- Callable[P, Awaitable[T]],
218
- ],
219
- ]
220
- ] = None,
221
- **kwargs: Dict[str, Any],
190
+ dependency_overrides: dict[
191
+ Callable[P, T] | Callable[P, Awaitable[T]], Callable[P, T] | Callable[P, Awaitable[T]]
192
+ ]
193
+ | None = None,
194
+ **kwargs: dict[str, Any],
222
195
  ) -> Generator[
223
- Tuple[
196
+ tuple[
224
197
  Sequence[Any],
225
- Dict[str, Any],
198
+ dict[str, Any],
226
199
  Callable[..., Any],
227
200
  ],
228
201
  Any,
@@ -240,7 +213,7 @@ class CallModel(Generic[P, T]):
240
213
  if self.use_cache and call in cache_dependencies:
241
214
  return cache_dependencies[call]
242
215
 
243
- kw: Dict[str, Any] = {}
216
+ kw: dict[str, Any] = {}
244
217
 
245
218
  for arg in self.keyword_args:
246
219
  if (v := kwargs.pop(arg, Parameter.empty)) is not Parameter.empty:
@@ -274,7 +247,7 @@ class CallModel(Generic[P, T]):
274
247
  if arg not in self.dependencies:
275
248
  kw[arg], args = args[0], args[1:]
276
249
 
277
- solved_kw: Dict[str, Any]
250
+ solved_kw: dict[str, Any]
278
251
  solved_kw = yield args, kw, call
279
252
 
280
253
  args_: Sequence[Any]
@@ -319,25 +292,14 @@ class CallModel(Generic[P, T]):
319
292
  /,
320
293
  *args: Any,
321
294
  stack: ExitStack,
322
- cache_dependencies: Dict[
323
- Union[
324
- Callable[P, T],
325
- Callable[P, Awaitable[T]],
326
- ],
295
+ cache_dependencies: dict[
296
+ Callable[P, T] | Callable[P, Awaitable[T]],
327
297
  T,
328
298
  ],
329
- dependency_overrides: Optional[
330
- Dict[
331
- Union[
332
- Callable[P, T],
333
- Callable[P, Awaitable[T]],
334
- ],
335
- Union[
336
- Callable[P, T],
337
- Callable[P, Awaitable[T]],
338
- ],
339
- ]
340
- ] = None,
299
+ dependency_overrides: dict[
300
+ Callable[P, T] | Callable[P, Awaitable[T]], Callable[P, T] | Callable[P, Awaitable[T]]
301
+ ]
302
+ | None = None,
341
303
  nested: bool = False,
342
304
  **kwargs: Any,
343
305
  ) -> T:
@@ -421,25 +383,14 @@ class CallModel(Generic[P, T]):
421
383
  /,
422
384
  *args: Any,
423
385
  stack: AsyncExitStack,
424
- cache_dependencies: Dict[
425
- Union[
426
- Callable[P, T],
427
- Callable[P, Awaitable[T]],
428
- ],
386
+ cache_dependencies: dict[
387
+ Callable[P, T] | Callable[P, Awaitable[T]],
429
388
  T,
430
389
  ],
431
- dependency_overrides: Optional[
432
- Dict[
433
- Union[
434
- Callable[P, T],
435
- Callable[P, Awaitable[T]],
436
- ],
437
- Union[
438
- Callable[P, T],
439
- Callable[P, Awaitable[T]],
440
- ],
441
- ]
442
- ] = None,
390
+ dependency_overrides: dict[
391
+ Callable[P, T] | Callable[P, Awaitable[T]], Callable[P, T] | Callable[P, Awaitable[T]]
392
+ ]
393
+ | None = None,
443
394
  nested: bool = False,
444
395
  **kwargs: Any,
445
396
  ) -> T:
@@ -456,7 +407,7 @@ class CallModel(Generic[P, T]):
456
407
  return cached_value
457
408
 
458
409
  # Heat cache and solve extra dependencies
459
- dep_to_solve: List[Callable[..., Awaitable[Any]]] = []
410
+ dep_to_solve: list[Callable[..., Awaitable[Any]]] = []
460
411
  try:
461
412
  async with anyio.create_task_group() as tg:
462
413
  for dep, subdep in self.sorted_dependencies:
@@ -500,7 +451,7 @@ class CallModel(Generic[P, T]):
500
451
  **kwargs,
501
452
  )
502
453
 
503
- custom_to_solve: List[CustomField] = []
454
+ custom_to_solve: list[CustomField] = []
504
455
 
505
456
  try:
506
457
  async with anyio.create_task_group() as tg:
@@ -544,16 +495,16 @@ class CallModel(Generic[P, T]):
544
495
 
545
496
 
546
497
  def _sort_dep(
547
- collector: List["CallModel[..., Any]"],
548
- items: Tuple[
498
+ collector: list["CallModel[..., Any]"],
499
+ items: tuple[
549
500
  "CallModel[..., Any]",
550
- Tuple[Callable[..., Any], ...],
501
+ tuple[Callable[..., Any], ...],
551
502
  ],
552
- flat: Dict[
503
+ flat: dict[
553
504
  Callable[..., Any],
554
- Tuple[
505
+ tuple[
555
506
  "CallModel[..., Any]",
556
- Tuple[Callable[..., Any], ...],
507
+ tuple[Callable[..., Any], ...],
557
508
  ],
558
509
  ],
559
510
  ) -> None:
@@ -5,7 +5,8 @@
5
5
  # Portions derived from https://github.com/https://github.com/Lancetnik/FastDepends are under the MIT License.
6
6
  # SPDX-License-Identifier: MIT
7
7
 
8
- from typing import Any, Callable
8
+ from collections.abc import Callable
9
+ from typing import Any
9
10
 
10
11
 
11
12
  class Depends:
@@ -5,12 +5,13 @@
5
5
  # Portions derived from https://github.com/https://github.com/Lancetnik/FastDepends are under the MIT License.
6
6
  # SPDX-License-Identifier: MIT
7
7
 
8
+ from collections.abc import Callable, Iterator
8
9
  from contextlib import contextmanager
9
- from typing import Any, Callable, Dict, Iterator
10
+ from typing import Any
10
11
 
11
12
 
12
13
  class Provider:
13
- dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]]
14
+ dependency_overrides: dict[Callable[..., Any], Callable[..., Any]]
14
15
 
15
16
  def __init__(self) -> None:
16
17
  self.dependency_overrides = {}