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
@@ -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
@@ -32,18 +33,18 @@ class ModelUsageSummary(BaseModel):
32
33
  class ActualUsageSummary(BaseModel):
33
34
  """Actual usage summary."""
34
35
 
35
- usages: Optional[list[ModelUsageSummary]] = None
36
+ usages: list[ModelUsageSummary] | None = None
36
37
  """List of model usage summaries."""
37
- total_cost: Optional[float] = None
38
+ total_cost: float | None = None
38
39
  """Total cost."""
39
40
 
40
41
 
41
42
  class TotalUsageSummary(BaseModel):
42
43
  """Total usage summary."""
43
44
 
44
- usages: Optional[list[ModelUsageSummary]] = None
45
+ usages: list[ModelUsageSummary] | None = None
45
46
  """List of model usage summaries."""
46
- total_cost: Optional[float] = None
47
+ total_cost: float | None = None
47
48
  """Total cost."""
48
49
 
49
50
 
@@ -51,7 +52,7 @@ Mode = Literal["both", "total", "actual"]
51
52
 
52
53
 
53
54
  def _change_usage_summary_format(
54
- actual_usage_summary: Optional[dict[str, Any]] = None, total_usage_summary: Optional[dict[str, Any]] = None
55
+ actual_usage_summary: dict[str, Any] | None = None, total_usage_summary: dict[str, Any] | None = None
55
56
  ) -> dict[str, dict[str, Any]]:
56
57
  summary: dict[str, Any] = {}
57
58
 
@@ -88,9 +89,9 @@ class UsageSummaryMessage(BaseMessage):
88
89
  def __init__(
89
90
  self,
90
91
  *,
91
- uuid: Optional[UUID] = None,
92
- actual_usage_summary: Optional[dict[str, Any]] = None,
93
- total_usage_summary: Optional[dict[str, Any]] = None,
92
+ uuid: UUID | None = None,
93
+ actual_usage_summary: dict[str, Any] | None = None,
94
+ total_usage_summary: dict[str, Any] | None = None,
94
95
  mode: Mode = "both",
95
96
  ):
96
97
  # print(f"{actual_usage_summary=}")
@@ -102,9 +103,9 @@ class UsageSummaryMessage(BaseMessage):
102
103
 
103
104
  def _print_usage(
104
105
  self,
105
- usage_summary: Union[ActualUsageSummary, TotalUsageSummary],
106
+ usage_summary: ActualUsageSummary | TotalUsageSummary,
106
107
  usage_type: str = "total",
107
- f: Optional[Callable[..., Any]] = None,
108
+ f: Callable[..., Any] | None = None,
108
109
  ) -> None:
109
110
  f = f or print
110
111
  word_from_type = "including" if usage_type == "total" else "excluding"
@@ -121,7 +122,7 @@ class UsageSummaryMessage(BaseMessage):
121
122
  flush=True,
122
123
  )
123
124
 
124
- def print(self, f: Optional[Callable[..., Any]] = None) -> None:
125
+ def print(self, f: Callable[..., Any] | None = None) -> None:
125
126
  f = f or print
126
127
 
127
128
  if self.total.usages is None:
@@ -156,10 +157,10 @@ class StreamMessage(BaseMessage):
156
157
  content: str
157
158
  """Content of the message."""
158
159
 
159
- def __init__(self, *, uuid: Optional[UUID] = None, content: str) -> None:
160
+ def __init__(self, *, uuid: UUID | None = None, content: str) -> None:
160
161
  super().__init__(uuid=uuid, content=content)
161
162
 
162
- def print(self, f: Optional[Callable[..., Any]] = None) -> None:
163
+ def print(self, f: Callable[..., Any] | None = None) -> None:
163
164
  f = f or print
164
165
 
165
166
  # Set the terminal text color to green
@@ -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 ..events import deprecated_by
@@ -24,9 +25,7 @@ class PrintMessage(BaseMessage):
24
25
  end: str
25
26
  """End of the print"""
26
27
 
27
- def __init__(
28
- self, *objects: Any, sep: str = " ", end: str = "\n", flush: bool = False, uuid: Optional[UUID] = None
29
- ):
28
+ def __init__(self, *objects: Any, sep: str = " ", end: str = "\n", flush: bool = False, uuid: UUID | None = None):
30
29
  objects_as_string = [self._to_json(x) for x in objects]
31
30
 
32
31
  super().__init__(uuid=uuid, objects=objects_as_string, sep=sep, end=end)
@@ -43,7 +42,7 @@ class PrintMessage(BaseMessage):
43
42
  return str(obj)
44
43
  # return repr(obj)
45
44
 
46
- def print(self, f: Optional[Callable[..., Any]] = None) -> None:
45
+ def print(self, f: Callable[..., Any] | None = None) -> None:
47
46
  f = f or print
48
47
 
49
48
  f(*self.objects, sep=self.sep, end=self.end, flush=True)
autogen/oai/__init__.py CHANGED
@@ -8,7 +8,7 @@ from ..cache.cache import Cache
8
8
  from .anthropic import AnthropicLLMConfigEntry
9
9
  from .bedrock import BedrockLLMConfigEntry
10
10
  from .cerebras import CerebrasLLMConfigEntry
11
- from .client import AzureOpenAILLMConfigEntry, DeepSeekLLMConfigEntry, ModelClient, OpenAILLMConfigEntry, OpenAIWrapper
11
+ from .client import AzureOpenAILLMConfigEntry, DeepSeekLLMConfigEntry, OpenAILLMConfigEntry, OpenAIWrapper
12
12
  from .cohere import CohereLLMConfigEntry
13
13
  from .gemini import GeminiLLMConfigEntry
14
14
  from .groq import GroqLLMConfigEntry
@@ -37,7 +37,6 @@ __all__ = [
37
37
  "GeminiLLMConfigEntry",
38
38
  "GroqLLMConfigEntry",
39
39
  "MistralLLMConfigEntry",
40
- "ModelClient",
41
40
  "OllamaLLMConfigEntry",
42
41
  "OpenAILLMConfigEntry",
43
42
  "OpenAIWrapper",
autogen/oai/anthropic.py CHANGED
@@ -76,12 +76,13 @@ import os
76
76
  import re
77
77
  import time
78
78
  import warnings
79
- from typing import Any, Literal, Optional, Union
79
+ from typing import Any, Literal
80
80
 
81
81
  from pydantic import BaseModel, Field
82
+ from typing_extensions import Unpack
82
83
 
83
84
  from ..import_utils import optional_import_block, require_optional_import
84
- from ..llm_config import LLMConfigEntry, register_llm_config
85
+ from ..llm_config.entry import LLMConfigEntry, LLMConfigEntryDict
85
86
  from .client_utils import FormatterProtocol, validate_parameter
86
87
  from .oai_models import ChatCompletion, ChatCompletionMessage, ChatCompletionMessageToolCall, Choice, CompletionUsage
87
88
 
@@ -109,23 +110,39 @@ ANTHROPIC_PRICING_1k = {
109
110
  }
110
111
 
111
112
 
112
- @register_llm_config
113
+ class AnthropicEntryDict(LLMConfigEntryDict, total=False):
114
+ api_type: Literal["anthropic"]
115
+ timeout: int | None
116
+ stop_sequences: list[str] | None
117
+ stream: bool
118
+ price: list[float] | None
119
+ tool_choice: dict | None
120
+ thinking: dict | None
121
+ gcp_project_id: str | None
122
+ gcp_region: str | None
123
+ gcp_auth_token: str | None
124
+
125
+
113
126
  class AnthropicLLMConfigEntry(LLMConfigEntry):
114
127
  api_type: Literal["anthropic"] = "anthropic"
115
- timeout: Optional[int] = Field(default=None, ge=1)
116
- temperature: float = Field(default=1.0, ge=0.0, le=1.0)
117
- top_k: Optional[int] = Field(default=None, ge=1)
118
- top_p: Optional[float] = Field(default=None, ge=0.0, le=1.0)
119
- stop_sequences: Optional[list[str]] = None
120
- stream: bool = False
128
+
129
+ # Basic options
121
130
  max_tokens: int = Field(default=4096, ge=1)
122
- price: Optional[list[float]] = Field(default=None, min_length=2, max_length=2)
123
- tool_choice: Optional[dict] = None
124
- thinking: Optional[dict] = None
131
+ temperature: float | None = Field(default=None, ge=0.0, le=1.0)
132
+ top_p: float | None = Field(default=None, ge=0.0, le=1.0)
133
+
134
+ # Anthropic-specific options
135
+ timeout: int | None = Field(default=None, ge=1)
136
+ top_k: int | None = Field(default=None, ge=1)
137
+ stop_sequences: list[str] | None = None
138
+ stream: bool = False
139
+ price: list[float] | None = Field(default=None, min_length=2, max_length=2)
140
+ tool_choice: dict | None = None
141
+ thinking: dict | None = None
125
142
 
126
- gcp_project_id: Optional[str] = None
127
- gcp_region: Optional[str] = None
128
- gcp_auth_token: Optional[str] = None
143
+ gcp_project_id: str | None = None
144
+ gcp_region: str | None = None
145
+ gcp_auth_token: str | None = None
129
146
 
130
147
  def create_client(self):
131
148
  raise NotImplementedError("AnthropicLLMConfigEntry.create_client is not implemented.")
@@ -133,37 +150,22 @@ class AnthropicLLMConfigEntry(LLMConfigEntry):
133
150
 
134
151
  @require_optional_import("anthropic", "anthropic")
135
152
  class AnthropicClient:
136
- def __init__(self, **kwargs: Any):
153
+ def __init__(self, **kwargs: Unpack[AnthropicEntryDict]):
137
154
  """Initialize the Anthropic API client.
138
155
 
139
156
  Args:
140
157
  **kwargs: The configuration parameters for the client.
141
158
  """
142
- self._api_key = kwargs.get("api_key")
143
- self._aws_access_key = kwargs.get("aws_access_key")
144
- self._aws_secret_key = kwargs.get("aws_secret_key")
159
+ self._api_key = kwargs.get("api_key") or os.getenv("ANTHROPIC_API_KEY")
160
+ self._aws_access_key = kwargs.get("aws_access_key") or os.getenv("AWS_ACCESS_KEY")
161
+ self._aws_secret_key = kwargs.get("aws_secret_key") or os.getenv("AWS_SECRET_KEY")
145
162
  self._aws_session_token = kwargs.get("aws_session_token")
146
- self._aws_region = kwargs.get("aws_region")
163
+ self._aws_region = kwargs.get("aws_region") or os.getenv("AWS_REGION")
147
164
  self._gcp_project_id = kwargs.get("gcp_project_id")
148
- self._gcp_region = kwargs.get("gcp_region")
165
+ self._gcp_region = kwargs.get("gcp_region") or os.getenv("GCP_REGION")
149
166
  self._gcp_auth_token = kwargs.get("gcp_auth_token")
150
167
  self._base_url = kwargs.get("base_url")
151
168
 
152
- if not self._api_key:
153
- self._api_key = os.getenv("ANTHROPIC_API_KEY")
154
-
155
- if not self._aws_access_key:
156
- self._aws_access_key = os.getenv("AWS_ACCESS_KEY")
157
-
158
- if not self._aws_secret_key:
159
- self._aws_secret_key = os.getenv("AWS_SECRET_KEY")
160
-
161
- if not self._aws_region:
162
- self._aws_region = os.getenv("AWS_REGION")
163
-
164
- if not self._gcp_region:
165
- self._gcp_region = os.getenv("GCP_REGION")
166
-
167
169
  if self._api_key is None:
168
170
  if self._aws_region:
169
171
  if self._aws_access_key is None or self._aws_secret_key is None:
@@ -181,7 +183,7 @@ class AnthropicClient:
181
183
  self._client = Anthropic(**client_kwargs)
182
184
  elif self._gcp_region is not None:
183
185
  kw = {}
184
- for i, p in enumerate(inspect.signature(AnthropicVertex).parameters):
186
+ for p in inspect.signature(AnthropicVertex).parameters:
185
187
  if hasattr(self, f"_gcp_{p}"):
186
188
  kw[p] = getattr(self, f"_gcp_{p}")
187
189
  if self._base_url:
@@ -201,7 +203,7 @@ class AnthropicClient:
201
203
  self._last_tooluse_status = {}
202
204
 
203
205
  # Store the response format, if provided (for structured outputs)
204
- self._response_format: Optional[type[BaseModel]] = None
206
+ self._response_format: type[BaseModel] | None = None
205
207
 
206
208
  def load_config(self, params: dict[str, Any]):
207
209
  """Load the configuration for the Anthropic API client."""
@@ -406,8 +408,7 @@ class AnthropicClient:
406
408
 
407
409
  @staticmethod
408
410
  def convert_tools_to_functions(tools: list) -> list:
409
- """
410
- Convert tool definitions into Anthropic-compatible functions,
411
+ """Convert tool definitions into Anthropic-compatible functions,
411
412
  updating nested $ref paths in property schemas.
412
413
 
413
414
  Args:
@@ -550,7 +551,7 @@ def process_image_content(content_item: dict[str, Any]) -> dict[str, Any]:
550
551
  return content_item
551
552
 
552
553
 
553
- def process_message_content(message: dict[str, Any]) -> Union[str, list[dict[str, Any]]]:
554
+ def process_message_content(message: dict[str, Any]) -> str | list[dict[str, Any]]:
554
555
  """Process message content, handling both string and list formats with images."""
555
556
  content = message.get("content", "")
556
557
 
autogen/oai/bedrock.py CHANGED
@@ -36,13 +36,14 @@ import os
36
36
  import re
37
37
  import time
38
38
  import warnings
39
- from typing import Any, Literal, Optional
39
+ from typing import Any, Literal
40
40
 
41
41
  import requests
42
42
  from pydantic import Field, SecretStr, field_serializer
43
+ from typing_extensions import Required, Unpack
43
44
 
44
45
  from ..import_utils import optional_import_block, require_optional_import
45
- from ..llm_config import LLMConfigEntry, register_llm_config
46
+ from ..llm_config.entry import LLMConfigEntry, LLMConfigEntryDict
46
47
  from .client_utils import validate_parameter
47
48
  from .oai_models import ChatCompletion, ChatCompletionMessage, ChatCompletionMessageToolCall, Choice, CompletionUsage
48
49
 
@@ -51,26 +52,38 @@ with optional_import_block():
51
52
  from botocore.config import Config
52
53
 
53
54
 
54
- @register_llm_config
55
+ class BedrockEntryDict(LLMConfigEntryDict, total=False):
56
+ api_type: Literal["bedrock"]
57
+ aws_region: Required[str]
58
+ aws_access_key: SecretStr | None
59
+ aws_secret_key: SecretStr | None
60
+ aws_session_token: SecretStr | None
61
+ aws_profile_name: str | None
62
+ top_k: int | None
63
+ k: int | None
64
+ seed: int | None
65
+ cache_seed: int | None
66
+ supports_system_prompts: bool
67
+ price: list[float] | None
68
+ timeout: int | None
69
+
70
+
55
71
  class BedrockLLMConfigEntry(LLMConfigEntry):
56
72
  api_type: Literal["bedrock"] = "bedrock"
73
+
74
+ # Bedrock-specific options
57
75
  aws_region: str
58
- aws_access_key: Optional[SecretStr] = None
59
- aws_secret_key: Optional[SecretStr] = None
60
- aws_session_token: Optional[SecretStr] = None
61
- aws_profile_name: Optional[str] = None
62
- temperature: Optional[float] = None
63
- topP: Optional[float] = None # noqa: N815
64
- maxTokens: Optional[int] = None # noqa: N815
65
- top_p: Optional[float] = None
66
- top_k: Optional[int] = None
67
- k: Optional[int] = None
68
- seed: Optional[int] = None
69
- cache_seed: Optional[int] = None
76
+ aws_access_key: SecretStr | None = None
77
+ aws_secret_key: SecretStr | None = None
78
+ aws_session_token: SecretStr | None = None
79
+ aws_profile_name: str | None = None
80
+ top_k: int | None = None
81
+ k: int | None = None
82
+ seed: int | None = None
83
+ cache_seed: int | None = None
70
84
  supports_system_prompts: bool = True
71
- stream: bool = False
72
- price: Optional[list[float]] = Field(default=None, min_length=2, max_length=2)
73
- timeout: Optional[int] = None
85
+ price: list[float] | None = Field(default=None, min_length=2, max_length=2)
86
+ timeout: int | None = None
74
87
 
75
88
  @field_serializer("aws_access_key", "aws_secret_key", "aws_session_token", when_used="unless-none")
76
89
  def serialize_aws_secrets(self, v: SecretStr) -> str:
@@ -86,27 +99,15 @@ class BedrockClient:
86
99
 
87
100
  _retries = 5
88
101
 
89
- def __init__(self, **kwargs: Any):
102
+ def __init__(self, **kwargs: Unpack[BedrockEntryDict]):
90
103
  """Initialises BedrockClient for Amazon's Bedrock Converse API"""
91
- self._aws_access_key = kwargs.get("aws_access_key")
92
- self._aws_secret_key = kwargs.get("aws_secret_key")
93
- self._aws_session_token = kwargs.get("aws_session_token")
94
- self._aws_region = kwargs.get("aws_region")
104
+ self._aws_access_key = kwargs.get("aws_access_key") or os.getenv("AWS_ACCESS_KEY")
105
+ self._aws_secret_key = kwargs.get("aws_secret_key") or os.getenv("AWS_SECRET_KEY")
106
+ self._aws_session_token = kwargs.get("aws_session_token") or os.getenv("AWS_SESSION_TOKEN")
107
+ self._aws_region = kwargs.get("aws_region") or os.getenv("AWS_REGION")
95
108
  self._aws_profile_name = kwargs.get("aws_profile_name")
96
109
  self._timeout = kwargs.get("timeout")
97
110
 
98
- if not self._aws_access_key:
99
- self._aws_access_key = os.getenv("AWS_ACCESS_KEY")
100
-
101
- if not self._aws_secret_key:
102
- self._aws_secret_key = os.getenv("AWS_SECRET_KEY")
103
-
104
- if not self._aws_session_token:
105
- self._aws_session_token = os.getenv("AWS_SESSION_TOKEN")
106
-
107
- if not self._aws_region:
108
- self._aws_region = os.getenv("AWS_REGION")
109
-
110
111
  if self._aws_region is None:
111
112
  raise ValueError("Region is required to use the Amazon Bedrock API.")
112
113
 
@@ -159,13 +160,10 @@ class BedrockClient:
159
160
  # This is required because not all models support a system prompt (e.g. Mistral Instruct).
160
161
  self._supports_system_prompts = params.get("supports_system_prompts", True)
161
162
 
162
- def parse_params(self, params: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
163
+ def parse_params(self, params: BedrockEntryDict | dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:
163
164
  """Loads the valid parameters required to invoke Bedrock Converse
164
165
  Returns a tuple of (base_params, additional_params)
165
166
  """
166
- base_params = {}
167
- additional_params = {}
168
-
169
167
  # Amazon Bedrock base model IDs are here:
170
168
  # https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html
171
169
  self._model_id = params.get("model")
@@ -190,38 +188,51 @@ class BedrockClient:
190
188
  # https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-mistral-chat-completion.html
191
189
 
192
190
  # Here are the possible "base" parameters and their suitable types
193
- base_parameters = [["temperature", (float, int)], ["topP", (float, int)], ["maxTokens", (int)]]
191
+ base_params = {}
194
192
 
195
- for param_name, suitable_types in base_parameters:
196
- if param_name in params:
197
- base_params[param_name] = validate_parameter(
198
- params, param_name, suitable_types, False, None, None, None
199
- )
193
+ if "temperature" in params:
194
+ base_params["temperature"] = validate_parameter(
195
+ params, "temperature", (float, int), False, None, None, None
196
+ )
197
+
198
+ if "top_p" in params:
199
+ base_params["topP"] = validate_parameter(params, "top_p", (float, int), False, None, None, None)
200
+
201
+ if "topP" in params:
202
+ warnings.warn(
203
+ ("topP is deprecated, use top_p instead. Scheduled for removal in 0.10.0 version."), DeprecationWarning
204
+ )
205
+ base_params["topP"] = validate_parameter(params, "topP", (float, int), False, None, None, None)
206
+
207
+ if "max_tokens" in params:
208
+ base_params["maxTokens"] = validate_parameter(params, "max_tokens", (int,), False, None, None, None)
209
+
210
+ if "maxTokens" in params:
211
+ warnings.warn(
212
+ ("maxTokens is deprecated, use max_tokens instead. Scheduled for removal in 0.10.0 version."),
213
+ DeprecationWarning,
214
+ )
215
+ base_params["maxTokens"] = validate_parameter(params, "maxTokens", (int,), False, None, None, None)
200
216
 
201
217
  # Here are the possible "model-specific" parameters and their suitable types, known as additional parameters
202
- additional_parameters = [
203
- ["top_p", (float, int)],
204
- ["top_k", (int)],
205
- ["k", (int)],
206
- ["seed", (int)],
207
- ]
218
+ additional_params = {}
208
219
 
209
- for param_name, suitable_types in additional_parameters:
220
+ for param_name, suitable_types in (
221
+ ("top_k", (int,)),
222
+ ("k", (int,)),
223
+ ("seed", (int,)),
224
+ ):
210
225
  if param_name in params:
211
226
  additional_params[param_name] = validate_parameter(
212
227
  params, param_name, suitable_types, False, None, None, None
213
228
  )
214
229
 
215
- # Streaming
216
- self._streaming = params.get("stream", False)
217
-
218
230
  # For this release we will not support streaming as many models do not support streaming with tool use
219
- if self._streaming:
231
+ if params.get("stream", False):
220
232
  warnings.warn(
221
233
  "Streaming is not currently supported, streaming will be disabled.",
222
234
  UserWarning,
223
235
  )
224
- self._streaming = False
225
236
 
226
237
  return base_params, additional_params
227
238
 
autogen/oai/cerebras.py CHANGED
@@ -28,12 +28,13 @@ import math
28
28
  import os
29
29
  import time
30
30
  import warnings
31
- from typing import Any, Literal, Optional
31
+ from typing import Any, Literal
32
32
 
33
- from pydantic import Field, ValidationInfo, field_validator
33
+ from pydantic import Field
34
+ from typing_extensions import Unpack
34
35
 
35
36
  from ..import_utils import optional_import_block, require_optional_import
36
- from ..llm_config import LLMConfigEntry, register_llm_config
37
+ from ..llm_config.entry import LLMConfigEntry, LLMConfigEntryDict
37
38
  from .client_utils import should_hide_tools, validate_parameter
38
39
  from .oai_models import ChatCompletion, ChatCompletionMessage, ChatCompletionMessageToolCall, Choice, CompletionUsage
39
40
 
@@ -47,23 +48,25 @@ CEREBRAS_PRICING_1K = {
47
48
  }
48
49
 
49
50
 
50
- @register_llm_config
51
+ class CerebrasEntryDict(LLMConfigEntryDict, total=False):
52
+ api_type: Literal["cerebras"]
53
+
54
+ seed: int | None
55
+ stream: bool
56
+ hide_tools: Literal["if_all_run", "if_any_run", "never"]
57
+ tool_choice: Literal["none", "auto", "required"] | None
58
+
59
+
51
60
  class CerebrasLLMConfigEntry(LLMConfigEntry):
52
61
  api_type: Literal["cerebras"] = "cerebras"
53
- max_tokens: Optional[int] = None
54
- seed: Optional[int] = None
62
+
63
+ temperature: float | None = Field(default=None, ge=0.0, le=1.5)
64
+
65
+ seed: int | None = None
55
66
  stream: bool = False
56
- temperature: float = Field(default=1.0, ge=0.0, le=1.5)
57
- top_p: Optional[float] = None
58
67
  hide_tools: Literal["if_all_run", "if_any_run", "never"] = "never"
59
- tool_choice: Optional[Literal["none", "auto", "required"]] = None
60
-
61
- @field_validator("top_p", mode="before")
62
- @classmethod
63
- def check_top_p(cls, v: Any, info: ValidationInfo) -> Any:
64
- if v is not None and info.data.get("temperature") is not None:
65
- raise ValueError("temperature and top_p cannot be set at the same time.")
66
- return v
68
+ tool_choice: Literal["none", "auto", "required"] | None = None
69
+ reasoning_effort: str | None = None
67
70
 
68
71
  def create_client(self):
69
72
  raise NotImplementedError("CerebrasLLMConfigEntry.create_client is not implemented.")
@@ -72,7 +75,7 @@ class CerebrasLLMConfigEntry(LLMConfigEntry):
72
75
  class CerebrasClient:
73
76
  """Client for Cerebras's API."""
74
77
 
75
- def __init__(self, api_key=None, **kwargs):
78
+ def __init__(self, api_key=None, **kwargs: Unpack[CerebrasEntryDict]):
76
79
  """Requires api_key or environment variable to be set
77
80
 
78
81
  Args:
@@ -80,16 +83,14 @@ class CerebrasClient:
80
83
  **kwargs: Additional keyword arguments to pass to the Cerebras client
81
84
  """
82
85
  # Ensure we have the api_key upon instantiation
83
- self.api_key = api_key
84
- if not self.api_key:
85
- self.api_key = os.getenv("CEREBRAS_API_KEY")
86
+ self.api_key = api_key or os.getenv("CEREBRAS_API_KEY")
86
87
 
87
88
  assert self.api_key, (
88
89
  "Please include the api_key in your config list entry for Cerebras or set the CEREBRAS_API_KEY env variable."
89
90
  )
90
91
 
91
92
  if "response_format" in kwargs and kwargs["response_format"] is not None:
92
- warnings.warn("response_format is not supported for Crebras, it will be ignored.", UserWarning)
93
+ warnings.warn("response_format is not supported for Cerebras, it will be ignored.", UserWarning)
93
94
 
94
95
  def message_retrieval(self, response: ChatCompletion) -> list:
95
96
  """Retrieve and return a list of strings or a list of Choice.Message from the response.
@@ -129,12 +130,12 @@ class CerebrasClient:
129
130
  # Validate allowed Cerebras parameters
130
131
  # https://inference-docs.cerebras.ai/api-reference/chat-completions
131
132
  cerebras_params["max_tokens"] = validate_parameter(params, "max_tokens", int, True, None, (0, None), None)
132
- cerebras_params["seed"] = validate_parameter(params, "seed", int, True, None, None, None)
133
- cerebras_params["stream"] = validate_parameter(params, "stream", bool, True, False, None, None)
134
133
  cerebras_params["temperature"] = validate_parameter(
135
- params, "temperature", (int, float), True, 1, (0, 1.5), None
134
+ params, "temperature", (int, float), True, 1.0, (0, 1.5), None
136
135
  )
137
- cerebras_params["top_p"] = validate_parameter(params, "top_p", (int, float), True, None, None, None)
136
+ cerebras_params["top_p"] = validate_parameter(params, "top_p", (int, float), True, None, (0.0, 1.0), None)
137
+ cerebras_params["seed"] = validate_parameter(params, "seed", int, True, None, None, None)
138
+ cerebras_params["stream"] = validate_parameter(params, "stream", bool, True, False, None, None)
138
139
  cerebras_params["tool_choice"] = validate_parameter(
139
140
  params, "tool_choice", str, True, None, None, ["none", "auto", "required"]
140
141
  )