ag2 0.3.2b2__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 (112) hide show
  1. ag2-0.3.2b2.dist-info/LICENSE +201 -0
  2. ag2-0.3.2b2.dist-info/METADATA +490 -0
  3. ag2-0.3.2b2.dist-info/NOTICE.md +19 -0
  4. ag2-0.3.2b2.dist-info/RECORD +112 -0
  5. ag2-0.3.2b2.dist-info/WHEEL +5 -0
  6. ag2-0.3.2b2.dist-info/top_level.txt +1 -0
  7. autogen/__init__.py +17 -0
  8. autogen/_pydantic.py +116 -0
  9. autogen/agentchat/__init__.py +26 -0
  10. autogen/agentchat/agent.py +142 -0
  11. autogen/agentchat/assistant_agent.py +85 -0
  12. autogen/agentchat/chat.py +306 -0
  13. autogen/agentchat/contrib/__init__.py +0 -0
  14. autogen/agentchat/contrib/agent_builder.py +785 -0
  15. autogen/agentchat/contrib/agent_optimizer.py +450 -0
  16. autogen/agentchat/contrib/capabilities/__init__.py +0 -0
  17. autogen/agentchat/contrib/capabilities/agent_capability.py +21 -0
  18. autogen/agentchat/contrib/capabilities/generate_images.py +297 -0
  19. autogen/agentchat/contrib/capabilities/teachability.py +406 -0
  20. autogen/agentchat/contrib/capabilities/text_compressors.py +72 -0
  21. autogen/agentchat/contrib/capabilities/transform_messages.py +92 -0
  22. autogen/agentchat/contrib/capabilities/transforms.py +565 -0
  23. autogen/agentchat/contrib/capabilities/transforms_util.py +120 -0
  24. autogen/agentchat/contrib/capabilities/vision_capability.py +217 -0
  25. autogen/agentchat/contrib/gpt_assistant_agent.py +545 -0
  26. autogen/agentchat/contrib/graph_rag/__init__.py +0 -0
  27. autogen/agentchat/contrib/graph_rag/document.py +24 -0
  28. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +76 -0
  29. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +50 -0
  30. autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +56 -0
  31. autogen/agentchat/contrib/img_utils.py +390 -0
  32. autogen/agentchat/contrib/llamaindex_conversable_agent.py +114 -0
  33. autogen/agentchat/contrib/llava_agent.py +176 -0
  34. autogen/agentchat/contrib/math_user_proxy_agent.py +471 -0
  35. autogen/agentchat/contrib/multimodal_conversable_agent.py +128 -0
  36. autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +325 -0
  37. autogen/agentchat/contrib/retrieve_assistant_agent.py +56 -0
  38. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +701 -0
  39. autogen/agentchat/contrib/society_of_mind_agent.py +203 -0
  40. autogen/agentchat/contrib/text_analyzer_agent.py +76 -0
  41. autogen/agentchat/contrib/vectordb/__init__.py +0 -0
  42. autogen/agentchat/contrib/vectordb/base.py +243 -0
  43. autogen/agentchat/contrib/vectordb/chromadb.py +326 -0
  44. autogen/agentchat/contrib/vectordb/mongodb.py +559 -0
  45. autogen/agentchat/contrib/vectordb/pgvectordb.py +958 -0
  46. autogen/agentchat/contrib/vectordb/qdrant.py +334 -0
  47. autogen/agentchat/contrib/vectordb/utils.py +126 -0
  48. autogen/agentchat/contrib/web_surfer.py +305 -0
  49. autogen/agentchat/conversable_agent.py +2904 -0
  50. autogen/agentchat/groupchat.py +1666 -0
  51. autogen/agentchat/user_proxy_agent.py +109 -0
  52. autogen/agentchat/utils.py +207 -0
  53. autogen/browser_utils.py +291 -0
  54. autogen/cache/__init__.py +10 -0
  55. autogen/cache/abstract_cache_base.py +78 -0
  56. autogen/cache/cache.py +182 -0
  57. autogen/cache/cache_factory.py +85 -0
  58. autogen/cache/cosmos_db_cache.py +150 -0
  59. autogen/cache/disk_cache.py +109 -0
  60. autogen/cache/in_memory_cache.py +61 -0
  61. autogen/cache/redis_cache.py +128 -0
  62. autogen/code_utils.py +745 -0
  63. autogen/coding/__init__.py +22 -0
  64. autogen/coding/base.py +113 -0
  65. autogen/coding/docker_commandline_code_executor.py +262 -0
  66. autogen/coding/factory.py +45 -0
  67. autogen/coding/func_with_reqs.py +203 -0
  68. autogen/coding/jupyter/__init__.py +22 -0
  69. autogen/coding/jupyter/base.py +32 -0
  70. autogen/coding/jupyter/docker_jupyter_server.py +164 -0
  71. autogen/coding/jupyter/embedded_ipython_code_executor.py +182 -0
  72. autogen/coding/jupyter/jupyter_client.py +224 -0
  73. autogen/coding/jupyter/jupyter_code_executor.py +161 -0
  74. autogen/coding/jupyter/local_jupyter_server.py +168 -0
  75. autogen/coding/local_commandline_code_executor.py +410 -0
  76. autogen/coding/markdown_code_extractor.py +44 -0
  77. autogen/coding/utils.py +57 -0
  78. autogen/exception_utils.py +46 -0
  79. autogen/extensions/__init__.py +0 -0
  80. autogen/formatting_utils.py +76 -0
  81. autogen/function_utils.py +362 -0
  82. autogen/graph_utils.py +148 -0
  83. autogen/io/__init__.py +15 -0
  84. autogen/io/base.py +105 -0
  85. autogen/io/console.py +43 -0
  86. autogen/io/websockets.py +213 -0
  87. autogen/logger/__init__.py +11 -0
  88. autogen/logger/base_logger.py +140 -0
  89. autogen/logger/file_logger.py +287 -0
  90. autogen/logger/logger_factory.py +29 -0
  91. autogen/logger/logger_utils.py +42 -0
  92. autogen/logger/sqlite_logger.py +459 -0
  93. autogen/math_utils.py +356 -0
  94. autogen/oai/__init__.py +33 -0
  95. autogen/oai/anthropic.py +428 -0
  96. autogen/oai/bedrock.py +600 -0
  97. autogen/oai/cerebras.py +264 -0
  98. autogen/oai/client.py +1148 -0
  99. autogen/oai/client_utils.py +167 -0
  100. autogen/oai/cohere.py +453 -0
  101. autogen/oai/completion.py +1216 -0
  102. autogen/oai/gemini.py +469 -0
  103. autogen/oai/groq.py +281 -0
  104. autogen/oai/mistral.py +279 -0
  105. autogen/oai/ollama.py +576 -0
  106. autogen/oai/openai_utils.py +810 -0
  107. autogen/oai/together.py +343 -0
  108. autogen/retrieve_utils.py +487 -0
  109. autogen/runtime_logging.py +163 -0
  110. autogen/token_count_utils.py +257 -0
  111. autogen/types.py +20 -0
  112. autogen/version.py +7 -0
@@ -0,0 +1,264 @@
1
+ """Create an OpenAI-compatible client using Cerebras's API.
2
+
3
+ Example:
4
+ llm_config={
5
+ "config_list": [{
6
+ "api_type": "cerebras",
7
+ "model": "llama3.1-8b",
8
+ "api_key": os.environ.get("CEREBRAS_API_KEY")
9
+ }]
10
+ }
11
+
12
+ agent = autogen.AssistantAgent("my_agent", llm_config=llm_config)
13
+
14
+ Install Cerebras's python library using: pip install --upgrade cerebras_cloud_sdk
15
+
16
+ Resources:
17
+ - https://inference-docs.cerebras.ai/quickstart
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import copy
23
+ import os
24
+ import time
25
+ import warnings
26
+ from typing import Any, Dict, List
27
+
28
+ from cerebras.cloud.sdk import Cerebras, Stream
29
+ from openai.types.chat import ChatCompletion, ChatCompletionMessageToolCall
30
+ from openai.types.chat.chat_completion import ChatCompletionMessage, Choice
31
+ from openai.types.completion_usage import CompletionUsage
32
+
33
+ from autogen.oai.client_utils import should_hide_tools, validate_parameter
34
+
35
+ CEREBRAS_PRICING_1K = {
36
+ # Convert pricing per million to per thousand tokens.
37
+ "llama3.1-8b": (0.10 / 1000, 0.10 / 1000),
38
+ "llama3.1-70b": (0.60 / 1000, 0.60 / 1000),
39
+ }
40
+
41
+
42
+ class CerebrasClient:
43
+ """Client for Cerebras's API."""
44
+
45
+ def __init__(self, api_key=None, **kwargs):
46
+ """Requires api_key or environment variable to be set
47
+
48
+ Args:
49
+ api_key (str): The API key for using Cerebras (or environment variable CEREBRAS_API_KEY needs to be set)
50
+ """
51
+ # Ensure we have the api_key upon instantiation
52
+ self.api_key = api_key
53
+ if not self.api_key:
54
+ self.api_key = os.getenv("CEREBRAS_API_KEY")
55
+
56
+ assert (
57
+ self.api_key
58
+ ), "Please include the api_key in your config list entry for Cerebras or set the CEREBRAS_API_KEY env variable."
59
+
60
+ def message_retrieval(self, response: ChatCompletion) -> List:
61
+ """
62
+ Retrieve and return a list of strings or a list of Choice.Message from the response.
63
+
64
+ NOTE: if a list of Choice.Message is returned, it currently needs to contain the fields of OpenAI's ChatCompletion Message object,
65
+ since that is expected for function or tool calling in the rest of the codebase at the moment, unless a custom agent is being used.
66
+ """
67
+ return [choice.message for choice in response.choices]
68
+
69
+ def cost(self, response: ChatCompletion) -> float:
70
+ # Note: This field isn't explicitly in `ChatCompletion`, but is injected during chat creation.
71
+ return response.cost
72
+
73
+ @staticmethod
74
+ def get_usage(response: ChatCompletion) -> Dict:
75
+ """Return usage summary of the response using RESPONSE_USAGE_KEYS."""
76
+ # ... # pragma: no cover
77
+ return {
78
+ "prompt_tokens": response.usage.prompt_tokens,
79
+ "completion_tokens": response.usage.completion_tokens,
80
+ "total_tokens": response.usage.total_tokens,
81
+ "cost": response.cost,
82
+ "model": response.model,
83
+ }
84
+
85
+ def parse_params(self, params: Dict[str, Any]) -> Dict[str, Any]:
86
+ """Loads the parameters for Cerebras API from the passed in parameters and returns a validated set. Checks types, ranges, and sets defaults"""
87
+ cerebras_params = {}
88
+
89
+ # Check that we have what we need to use Cerebras's API
90
+ # We won't enforce the available models as they are likely to change
91
+ cerebras_params["model"] = params.get("model", None)
92
+ assert cerebras_params[
93
+ "model"
94
+ ], "Please specify the 'model' in your config list entry to nominate the Cerebras model to use."
95
+
96
+ # Validate allowed Cerebras parameters
97
+ # https://inference-docs.cerebras.ai/api-reference/chat-completions
98
+ cerebras_params["max_tokens"] = validate_parameter(params, "max_tokens", int, True, None, (0, None), None)
99
+ cerebras_params["seed"] = validate_parameter(params, "seed", int, True, None, None, None)
100
+ cerebras_params["stream"] = validate_parameter(params, "stream", bool, True, False, None, None)
101
+ cerebras_params["temperature"] = validate_parameter(
102
+ params, "temperature", (int, float), True, 1, (0, 1.5), None
103
+ )
104
+ cerebras_params["top_p"] = validate_parameter(params, "top_p", (int, float), True, None, None, None)
105
+
106
+ return cerebras_params
107
+
108
+ def create(self, params: Dict) -> ChatCompletion:
109
+
110
+ messages = params.get("messages", [])
111
+
112
+ # Convert AutoGen messages to Cerebras messages
113
+ cerebras_messages = oai_messages_to_cerebras_messages(messages)
114
+
115
+ # Parse parameters to the Cerebras API's parameters
116
+ cerebras_params = self.parse_params(params)
117
+
118
+ # Add tools to the call if we have them and aren't hiding them
119
+ if "tools" in params:
120
+ hide_tools = validate_parameter(
121
+ params, "hide_tools", str, False, "never", None, ["if_all_run", "if_any_run", "never"]
122
+ )
123
+ if not should_hide_tools(cerebras_messages, params["tools"], hide_tools):
124
+ cerebras_params["tools"] = params["tools"]
125
+
126
+ cerebras_params["messages"] = cerebras_messages
127
+
128
+ # We use chat model by default, and set max_retries to 5 (in line with typical retries loop)
129
+ client = Cerebras(api_key=self.api_key, max_retries=5)
130
+
131
+ # Token counts will be returned
132
+ prompt_tokens = 0
133
+ completion_tokens = 0
134
+ total_tokens = 0
135
+
136
+ # Streaming tool call recommendations
137
+ streaming_tool_calls = []
138
+
139
+ ans = None
140
+ response = client.chat.completions.create(**cerebras_params)
141
+
142
+ if cerebras_params["stream"]:
143
+ # Read in the chunks as they stream, taking in tool_calls which may be across
144
+ # multiple chunks if more than one suggested
145
+ ans = ""
146
+ for chunk in response:
147
+ # Grab first choice, which _should_ always be generated.
148
+ ans = ans + (getattr(chunk.choices[0].delta, "content", None) or "")
149
+
150
+ if "tool_calls" in chunk.choices[0].delta:
151
+ # We have a tool call recommendation
152
+ for tool_call in chunk.choices[0].delta["tool_calls"]:
153
+ streaming_tool_calls.append(
154
+ ChatCompletionMessageToolCall(
155
+ id=tool_call["id"],
156
+ function={
157
+ "name": tool_call["function"]["name"],
158
+ "arguments": tool_call["function"]["arguments"],
159
+ },
160
+ type="function",
161
+ )
162
+ )
163
+
164
+ if chunk.choices[0].finish_reason:
165
+ prompt_tokens = chunk.usage.prompt_tokens
166
+ completion_tokens = chunk.usage.completion_tokens
167
+ total_tokens = chunk.usage.total_tokens
168
+ else:
169
+ # Non-streaming finished
170
+ ans: str = response.choices[0].message.content
171
+
172
+ prompt_tokens = response.usage.prompt_tokens
173
+ completion_tokens = response.usage.completion_tokens
174
+ total_tokens = response.usage.total_tokens
175
+
176
+ if response is not None:
177
+ if isinstance(response, Stream):
178
+ # Streaming response
179
+ if chunk.choices[0].finish_reason == "tool_calls":
180
+ cerebras_finish = "tool_calls"
181
+ tool_calls = streaming_tool_calls
182
+ else:
183
+ cerebras_finish = "stop"
184
+ tool_calls = None
185
+
186
+ response_content = ans
187
+ response_id = chunk.id
188
+ else:
189
+ # Non-streaming response
190
+ # If we have tool calls as the response, populate completed tool calls for our return OAI response
191
+ if response.choices[0].finish_reason == "tool_calls":
192
+ cerebras_finish = "tool_calls"
193
+ tool_calls = []
194
+ for tool_call in response.choices[0].message.tool_calls:
195
+ tool_calls.append(
196
+ ChatCompletionMessageToolCall(
197
+ id=tool_call.id,
198
+ function={"name": tool_call.function.name, "arguments": tool_call.function.arguments},
199
+ type="function",
200
+ )
201
+ )
202
+ else:
203
+ cerebras_finish = "stop"
204
+ tool_calls = None
205
+
206
+ response_content = response.choices[0].message.content
207
+ response_id = response.id
208
+
209
+ # 3. convert output
210
+ message = ChatCompletionMessage(
211
+ role="assistant",
212
+ content=response_content,
213
+ function_call=None,
214
+ tool_calls=tool_calls,
215
+ )
216
+ choices = [Choice(finish_reason=cerebras_finish, index=0, message=message)]
217
+
218
+ response_oai = ChatCompletion(
219
+ id=response_id,
220
+ model=cerebras_params["model"],
221
+ created=int(time.time()),
222
+ object="chat.completion",
223
+ choices=choices,
224
+ usage=CompletionUsage(
225
+ prompt_tokens=prompt_tokens,
226
+ completion_tokens=completion_tokens,
227
+ total_tokens=total_tokens,
228
+ ),
229
+ # Note: This seems to be a field that isn't in the schema of `ChatCompletion`, so Pydantic
230
+ # just adds it dynamically.
231
+ cost=calculate_cerebras_cost(prompt_tokens, completion_tokens, cerebras_params["model"]),
232
+ )
233
+
234
+ return response_oai
235
+
236
+
237
+ def oai_messages_to_cerebras_messages(messages: list[Dict[str, Any]]) -> list[dict[str, Any]]:
238
+ """Convert messages from OAI format to Cerebras's format.
239
+ We correct for any specific role orders and types.
240
+ """
241
+
242
+ cerebras_messages = copy.deepcopy(messages)
243
+
244
+ # Remove the name field
245
+ for message in cerebras_messages:
246
+ if "name" in message:
247
+ message.pop("name", None)
248
+
249
+ return cerebras_messages
250
+
251
+
252
+ def calculate_cerebras_cost(input_tokens: int, output_tokens: int, model: str) -> float:
253
+ """Calculate the cost of the completion using the Cerebras pricing."""
254
+ total = 0.0
255
+
256
+ if model in CEREBRAS_PRICING_1K:
257
+ input_cost_per_k, output_cost_per_k = CEREBRAS_PRICING_1K[model]
258
+ input_cost = (input_tokens / 1000) * input_cost_per_k
259
+ output_cost = (output_tokens / 1000) * output_cost_per_k
260
+ total = input_cost + output_cost
261
+ else:
262
+ warnings.warn(f"Cost calculation not available for model {model}", UserWarning)
263
+
264
+ return total