ag2 0.4.1__py3-none-any.whl → 0.4.2b1__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 (161) hide show
  1. ag2-0.4.2b1.dist-info/METADATA +19 -0
  2. ag2-0.4.2b1.dist-info/RECORD +6 -0
  3. ag2-0.4.2b1.dist-info/top_level.txt +1 -0
  4. ag2-0.4.1.dist-info/METADATA +0 -500
  5. ag2-0.4.1.dist-info/RECORD +0 -158
  6. ag2-0.4.1.dist-info/top_level.txt +0 -1
  7. autogen/__init__.py +0 -17
  8. autogen/_pydantic.py +0 -116
  9. autogen/agentchat/__init__.py +0 -42
  10. autogen/agentchat/agent.py +0 -142
  11. autogen/agentchat/assistant_agent.py +0 -85
  12. autogen/agentchat/chat.py +0 -306
  13. autogen/agentchat/contrib/__init__.py +0 -0
  14. autogen/agentchat/contrib/agent_builder.py +0 -788
  15. autogen/agentchat/contrib/agent_eval/agent_eval.py +0 -107
  16. autogen/agentchat/contrib/agent_eval/criterion.py +0 -47
  17. autogen/agentchat/contrib/agent_eval/critic_agent.py +0 -47
  18. autogen/agentchat/contrib/agent_eval/quantifier_agent.py +0 -42
  19. autogen/agentchat/contrib/agent_eval/subcritic_agent.py +0 -48
  20. autogen/agentchat/contrib/agent_eval/task.py +0 -43
  21. autogen/agentchat/contrib/agent_optimizer.py +0 -450
  22. autogen/agentchat/contrib/capabilities/__init__.py +0 -0
  23. autogen/agentchat/contrib/capabilities/agent_capability.py +0 -21
  24. autogen/agentchat/contrib/capabilities/generate_images.py +0 -297
  25. autogen/agentchat/contrib/capabilities/teachability.py +0 -406
  26. autogen/agentchat/contrib/capabilities/text_compressors.py +0 -72
  27. autogen/agentchat/contrib/capabilities/transform_messages.py +0 -92
  28. autogen/agentchat/contrib/capabilities/transforms.py +0 -565
  29. autogen/agentchat/contrib/capabilities/transforms_util.py +0 -120
  30. autogen/agentchat/contrib/capabilities/vision_capability.py +0 -217
  31. autogen/agentchat/contrib/captainagent/tools/__init__.py +0 -0
  32. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_correlation.py +0 -41
  33. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_skewness_and_kurtosis.py +0 -29
  34. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_iqr.py +0 -29
  35. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_zscore.py +0 -29
  36. autogen/agentchat/contrib/captainagent/tools/data_analysis/explore_csv.py +0 -22
  37. autogen/agentchat/contrib/captainagent/tools/data_analysis/shapiro_wilk_test.py +0 -31
  38. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_download.py +0 -26
  39. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_search.py +0 -55
  40. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_image.py +0 -54
  41. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_text.py +0 -39
  42. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_wikipedia_text.py +0 -22
  43. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_youtube_caption.py +0 -35
  44. autogen/agentchat/contrib/captainagent/tools/information_retrieval/image_qa.py +0 -61
  45. autogen/agentchat/contrib/captainagent/tools/information_retrieval/optical_character_recognition.py +0 -62
  46. autogen/agentchat/contrib/captainagent/tools/information_retrieval/perform_web_search.py +0 -48
  47. autogen/agentchat/contrib/captainagent/tools/information_retrieval/scrape_wikipedia_tables.py +0 -34
  48. autogen/agentchat/contrib/captainagent/tools/information_retrieval/transcribe_audio_file.py +0 -22
  49. autogen/agentchat/contrib/captainagent/tools/information_retrieval/youtube_download.py +0 -36
  50. autogen/agentchat/contrib/captainagent/tools/math/calculate_circle_area_from_diameter.py +0 -22
  51. autogen/agentchat/contrib/captainagent/tools/math/calculate_day_of_the_week.py +0 -19
  52. autogen/agentchat/contrib/captainagent/tools/math/calculate_fraction_sum.py +0 -29
  53. autogen/agentchat/contrib/captainagent/tools/math/calculate_matrix_power.py +0 -32
  54. autogen/agentchat/contrib/captainagent/tools/math/calculate_reflected_point.py +0 -17
  55. autogen/agentchat/contrib/captainagent/tools/math/complex_numbers_product.py +0 -26
  56. autogen/agentchat/contrib/captainagent/tools/math/compute_currency_conversion.py +0 -24
  57. autogen/agentchat/contrib/captainagent/tools/math/count_distinct_permutations.py +0 -28
  58. autogen/agentchat/contrib/captainagent/tools/math/evaluate_expression.py +0 -29
  59. autogen/agentchat/contrib/captainagent/tools/math/find_continuity_point.py +0 -35
  60. autogen/agentchat/contrib/captainagent/tools/math/fraction_to_mixed_numbers.py +0 -40
  61. autogen/agentchat/contrib/captainagent/tools/math/modular_inverse_sum.py +0 -23
  62. autogen/agentchat/contrib/captainagent/tools/math/simplify_mixed_numbers.py +0 -37
  63. autogen/agentchat/contrib/captainagent/tools/math/sum_of_digit_factorials.py +0 -16
  64. autogen/agentchat/contrib/captainagent/tools/math/sum_of_primes_below.py +0 -16
  65. autogen/agentchat/contrib/captainagent/tools/requirements.txt +0 -10
  66. autogen/agentchat/contrib/captainagent/tools/tool_description.tsv +0 -34
  67. autogen/agentchat/contrib/captainagent.py +0 -490
  68. autogen/agentchat/contrib/gpt_assistant_agent.py +0 -545
  69. autogen/agentchat/contrib/graph_rag/__init__.py +0 -0
  70. autogen/agentchat/contrib/graph_rag/document.py +0 -30
  71. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +0 -111
  72. autogen/agentchat/contrib/graph_rag/falkor_graph_rag_capability.py +0 -81
  73. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +0 -56
  74. autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +0 -64
  75. autogen/agentchat/contrib/img_utils.py +0 -390
  76. autogen/agentchat/contrib/llamaindex_conversable_agent.py +0 -123
  77. autogen/agentchat/contrib/llava_agent.py +0 -176
  78. autogen/agentchat/contrib/math_user_proxy_agent.py +0 -471
  79. autogen/agentchat/contrib/multimodal_conversable_agent.py +0 -128
  80. autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +0 -325
  81. autogen/agentchat/contrib/retrieve_assistant_agent.py +0 -56
  82. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +0 -705
  83. autogen/agentchat/contrib/society_of_mind_agent.py +0 -203
  84. autogen/agentchat/contrib/swarm_agent.py +0 -463
  85. autogen/agentchat/contrib/text_analyzer_agent.py +0 -76
  86. autogen/agentchat/contrib/tool_retriever.py +0 -120
  87. autogen/agentchat/contrib/vectordb/__init__.py +0 -0
  88. autogen/agentchat/contrib/vectordb/base.py +0 -243
  89. autogen/agentchat/contrib/vectordb/chromadb.py +0 -326
  90. autogen/agentchat/contrib/vectordb/mongodb.py +0 -559
  91. autogen/agentchat/contrib/vectordb/pgvectordb.py +0 -958
  92. autogen/agentchat/contrib/vectordb/qdrant.py +0 -334
  93. autogen/agentchat/contrib/vectordb/utils.py +0 -126
  94. autogen/agentchat/contrib/web_surfer.py +0 -305
  95. autogen/agentchat/conversable_agent.py +0 -2908
  96. autogen/agentchat/groupchat.py +0 -1668
  97. autogen/agentchat/user_proxy_agent.py +0 -109
  98. autogen/agentchat/utils.py +0 -207
  99. autogen/browser_utils.py +0 -291
  100. autogen/cache/__init__.py +0 -10
  101. autogen/cache/abstract_cache_base.py +0 -78
  102. autogen/cache/cache.py +0 -182
  103. autogen/cache/cache_factory.py +0 -85
  104. autogen/cache/cosmos_db_cache.py +0 -150
  105. autogen/cache/disk_cache.py +0 -109
  106. autogen/cache/in_memory_cache.py +0 -61
  107. autogen/cache/redis_cache.py +0 -128
  108. autogen/code_utils.py +0 -745
  109. autogen/coding/__init__.py +0 -22
  110. autogen/coding/base.py +0 -113
  111. autogen/coding/docker_commandline_code_executor.py +0 -262
  112. autogen/coding/factory.py +0 -45
  113. autogen/coding/func_with_reqs.py +0 -203
  114. autogen/coding/jupyter/__init__.py +0 -22
  115. autogen/coding/jupyter/base.py +0 -32
  116. autogen/coding/jupyter/docker_jupyter_server.py +0 -164
  117. autogen/coding/jupyter/embedded_ipython_code_executor.py +0 -182
  118. autogen/coding/jupyter/jupyter_client.py +0 -224
  119. autogen/coding/jupyter/jupyter_code_executor.py +0 -161
  120. autogen/coding/jupyter/local_jupyter_server.py +0 -168
  121. autogen/coding/local_commandline_code_executor.py +0 -410
  122. autogen/coding/markdown_code_extractor.py +0 -44
  123. autogen/coding/utils.py +0 -57
  124. autogen/exception_utils.py +0 -46
  125. autogen/extensions/__init__.py +0 -0
  126. autogen/formatting_utils.py +0 -76
  127. autogen/function_utils.py +0 -362
  128. autogen/graph_utils.py +0 -148
  129. autogen/io/__init__.py +0 -15
  130. autogen/io/base.py +0 -105
  131. autogen/io/console.py +0 -43
  132. autogen/io/websockets.py +0 -213
  133. autogen/logger/__init__.py +0 -11
  134. autogen/logger/base_logger.py +0 -140
  135. autogen/logger/file_logger.py +0 -287
  136. autogen/logger/logger_factory.py +0 -29
  137. autogen/logger/logger_utils.py +0 -42
  138. autogen/logger/sqlite_logger.py +0 -459
  139. autogen/math_utils.py +0 -356
  140. autogen/oai/__init__.py +0 -33
  141. autogen/oai/anthropic.py +0 -428
  142. autogen/oai/bedrock.py +0 -606
  143. autogen/oai/cerebras.py +0 -270
  144. autogen/oai/client.py +0 -1148
  145. autogen/oai/client_utils.py +0 -167
  146. autogen/oai/cohere.py +0 -453
  147. autogen/oai/completion.py +0 -1216
  148. autogen/oai/gemini.py +0 -469
  149. autogen/oai/groq.py +0 -281
  150. autogen/oai/mistral.py +0 -279
  151. autogen/oai/ollama.py +0 -582
  152. autogen/oai/openai_utils.py +0 -811
  153. autogen/oai/together.py +0 -343
  154. autogen/retrieve_utils.py +0 -487
  155. autogen/runtime_logging.py +0 -163
  156. autogen/token_count_utils.py +0 -259
  157. autogen/types.py +0 -20
  158. autogen/version.py +0 -7
  159. {ag2-0.4.1.dist-info → ag2-0.4.2b1.dist-info}/LICENSE +0 -0
  160. {ag2-0.4.1.dist-info → ag2-0.4.2b1.dist-info}/NOTICE.md +0 -0
  161. {ag2-0.4.1.dist-info → ag2-0.4.2b1.dist-info}/WHEEL +0 -0
@@ -1,410 +0,0 @@
1
- # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
- #
3
- # SPDX-License-Identifier: Apache-2.0
4
- #
5
- # Portions derived from https://github.com/microsoft/autogen are under the MIT License.
6
- # SPDX-License-Identifier: MIT
7
- import logging
8
- import os
9
- import re
10
- import subprocess
11
- import sys
12
- import warnings
13
- from hashlib import md5
14
- from pathlib import Path
15
- from string import Template
16
- from types import SimpleNamespace
17
- from typing import Any, Callable, ClassVar, Dict, List, Optional, Union
18
-
19
- from typing_extensions import ParamSpec
20
-
21
- from autogen.coding.func_with_reqs import (
22
- FunctionWithRequirements,
23
- FunctionWithRequirementsStr,
24
- _build_python_functions_file,
25
- to_stub,
26
- )
27
-
28
- from ..code_utils import PYTHON_VARIANTS, TIMEOUT_MSG, WIN32, _cmd
29
- from .base import CodeBlock, CodeExecutor, CodeExtractor, CommandLineCodeResult
30
- from .markdown_code_extractor import MarkdownCodeExtractor
31
- from .utils import _get_file_name_from_content, silence_pip
32
-
33
- __all__ = ("LocalCommandLineCodeExecutor",)
34
-
35
- A = ParamSpec("A")
36
-
37
-
38
- class LocalCommandLineCodeExecutor(CodeExecutor):
39
- SUPPORTED_LANGUAGES: ClassVar[List[str]] = [
40
- "bash",
41
- "shell",
42
- "sh",
43
- "pwsh",
44
- "powershell",
45
- "ps1",
46
- "python",
47
- "javascript",
48
- "html",
49
- "css",
50
- ]
51
- DEFAULT_EXECUTION_POLICY: ClassVar[Dict[str, bool]] = {
52
- "bash": True,
53
- "shell": True,
54
- "sh": True,
55
- "pwsh": True,
56
- "powershell": True,
57
- "ps1": True,
58
- "python": True,
59
- "javascript": False,
60
- "html": False,
61
- "css": False,
62
- }
63
-
64
- FUNCTION_PROMPT_TEMPLATE: ClassVar[
65
- str
66
- ] = """You have access to the following user defined functions. They can be accessed from the module called `$module_name` by their function names.
67
-
68
- For example, if there was a function called `foo` you could import it by writing `from $module_name import foo`
69
-
70
- $functions"""
71
-
72
- def __init__(
73
- self,
74
- timeout: int = 60,
75
- virtual_env_context: Optional[SimpleNamespace] = None,
76
- work_dir: Union[Path, str] = Path("."),
77
- functions: List[Union[FunctionWithRequirements[Any, A], Callable[..., Any], FunctionWithRequirementsStr]] = [],
78
- functions_module: str = "functions",
79
- execution_policies: Optional[Dict[str, bool]] = None,
80
- ):
81
- """(Experimental) A code executor class that executes or saves LLM generated code a local command line
82
- environment.
83
-
84
- **This will execute or save LLM generated code on the local machine.**
85
-
86
- Each code block is saved as a file in the working directory. Depending on the execution policy,
87
- the code may be executed in a separate process.
88
- The code blocks are executed or save in the order they are received.
89
- Command line code is sanitized against a list of dangerous commands to prevent self-destructive commands from being executed,
90
- which could potentially affect the user's environment. Supported languages include Python, shell scripts (bash, shell, sh),
91
- PowerShell (pwsh, powershell, ps1), HTML, CSS, and JavaScript.
92
- Execution policies determine whether each language's code blocks are executed or saved only.
93
-
94
- ## Execution with a Python virtual environment
95
- A python virtual env can be used to execute code and install dependencies. This has the added benefit of not polluting the
96
- base environment with unwanted modules.
97
- ```python
98
- from autogen.code_utils import create_virtual_env
99
- from autogen.coding import LocalCommandLineCodeExecutor
100
-
101
- venv_dir = ".venv"
102
- venv_context = create_virtual_env(venv_dir)
103
-
104
- executor = LocalCommandLineCodeExecutor(virtual_env_context=venv_context)
105
- ```
106
-
107
- Args:
108
- timeout (int): The timeout for code execution, default is 60 seconds.
109
- virtual_env_context (Optional[SimpleNamespace]): The virtual environment context to use.
110
- work_dir (Union[Path, str]): The working directory for code execution, defaults to the current directory.
111
- functions (List[Union[FunctionWithRequirements[Any, A], Callable[..., Any], FunctionWithRequirementsStr]]): A list of callable functions available to the executor.
112
- functions_module (str): The module name under which functions are accessible.
113
- execution_policies (Optional[Dict[str, bool]]): A dictionary mapping languages to execution policies (True for execution, False for saving only). Defaults to class-wide DEFAULT_EXECUTION_POLICY.
114
- """
115
-
116
- if timeout < 1:
117
- raise ValueError("Timeout must be greater than or equal to 1.")
118
-
119
- if isinstance(work_dir, str):
120
- work_dir = Path(work_dir)
121
-
122
- if not functions_module.isidentifier():
123
- raise ValueError("Module name must be a valid Python identifier")
124
-
125
- self._functions_module = functions_module
126
-
127
- work_dir.mkdir(exist_ok=True)
128
-
129
- self._timeout = timeout
130
- self._work_dir: Path = work_dir
131
- self._virtual_env_context: Optional[SimpleNamespace] = virtual_env_context
132
-
133
- self._functions = functions
134
- # Setup could take some time so we intentionally wait for the first code block to do it.
135
- if len(functions) > 0:
136
- self._setup_functions_complete = False
137
- else:
138
- self._setup_functions_complete = True
139
-
140
- self.execution_policies = self.DEFAULT_EXECUTION_POLICY.copy()
141
- if execution_policies is not None:
142
- self.execution_policies.update(execution_policies)
143
-
144
- def format_functions_for_prompt(self, prompt_template: str = FUNCTION_PROMPT_TEMPLATE) -> str:
145
- """(Experimental) Format the functions for a prompt.
146
-
147
- The template includes two variables:
148
- - `$module_name`: The module name.
149
- - `$functions`: The functions formatted as stubs with two newlines between each function.
150
-
151
- Args:
152
- prompt_template (str): The prompt template. Default is the class default.
153
-
154
- Returns:
155
- str: The formatted prompt.
156
- """
157
- template = Template(prompt_template)
158
- return template.substitute(
159
- module_name=self._functions_module,
160
- functions="\n\n".join([to_stub(func) for func in self._functions]),
161
- )
162
-
163
- @property
164
- def functions_module(self) -> str:
165
- """(Experimental) The module name for the functions."""
166
- return self._functions_module
167
-
168
- @property
169
- def functions(
170
- self,
171
- ) -> List[Union[FunctionWithRequirements[Any, A], Callable[..., Any], FunctionWithRequirementsStr]]:
172
- """(Experimental) The functions that are available to the code executor."""
173
- return self._functions
174
-
175
- @property
176
- def timeout(self) -> int:
177
- """(Experimental) The timeout for code execution."""
178
- return self._timeout
179
-
180
- @property
181
- def work_dir(self) -> Path:
182
- """(Experimental) The working directory for the code execution."""
183
- return self._work_dir
184
-
185
- @property
186
- def code_extractor(self) -> CodeExtractor:
187
- """(Experimental) Export a code extractor that can be used by an agent."""
188
- return MarkdownCodeExtractor()
189
-
190
- @staticmethod
191
- def sanitize_command(lang: str, code: str) -> None:
192
- """
193
- Sanitize the code block to prevent dangerous commands.
194
- This approach acknowledges that while Docker or similar
195
- containerization/sandboxing technologies provide a robust layer of security,
196
- not all users may have Docker installed or may choose not to use it.
197
- Therefore, having a baseline level of protection helps mitigate risks for users who,
198
- either out of choice or necessity, run code outside of a sandboxed environment.
199
- """
200
- dangerous_patterns = [
201
- (r"\brm\s+-rf\b", "Use of 'rm -rf' command is not allowed."),
202
- (r"\bmv\b.*?\s+/dev/null", "Moving files to /dev/null is not allowed."),
203
- (r"\bdd\b", "Use of 'dd' command is not allowed."),
204
- (r">\s*/dev/sd[a-z][1-9]?", "Overwriting disk blocks directly is not allowed."),
205
- (r":\(\)\{\s*:\|\:&\s*\};:", "Fork bombs are not allowed."),
206
- ]
207
- if lang in ["bash", "shell", "sh"]:
208
- for pattern, message in dangerous_patterns:
209
- if re.search(pattern, code):
210
- raise ValueError(f"Potentially dangerous command detected: {message}")
211
-
212
- def _setup_functions(self) -> None:
213
- func_file_content = _build_python_functions_file(self._functions)
214
- func_file = self._work_dir / f"{self._functions_module}.py"
215
- func_file.write_text(func_file_content)
216
-
217
- # Collect requirements
218
- lists_of_packages = [x.python_packages for x in self._functions if isinstance(x, FunctionWithRequirements)]
219
- flattened_packages = [item for sublist in lists_of_packages for item in sublist]
220
- required_packages = list(set(flattened_packages))
221
- if len(required_packages) > 0:
222
- logging.info("Ensuring packages are installed in executor.")
223
- if self._virtual_env_context:
224
- py_executable = self._virtual_env_context.env_exe
225
- else:
226
- py_executable = sys.executable
227
- cmd = [py_executable, "-m", "pip", "install"] + required_packages
228
- try:
229
- result = subprocess.run(
230
- cmd,
231
- cwd=self._work_dir,
232
- capture_output=True,
233
- text=True,
234
- timeout=float(self._timeout),
235
- encoding="utf-8",
236
- )
237
- except subprocess.TimeoutExpired as e:
238
- raise ValueError("Pip install timed out") from e
239
- if result.returncode != 0:
240
- raise ValueError(f"Pip install failed. {result.stdout}, {result.stderr}")
241
- # Attempt to load the function file to check for syntax errors, imports etc.
242
- exec_result = self._execute_code_dont_check_setup([CodeBlock(code=func_file_content, language="python")])
243
- if exec_result.exit_code != 0:
244
- raise ValueError(f"Functions failed to load: {exec_result.output}")
245
- self._setup_functions_complete = True
246
-
247
- def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CommandLineCodeResult:
248
- """(Experimental) Execute the code blocks and return the result.
249
-
250
- Args:
251
- code_blocks (List[CodeBlock]): The code blocks to execute.
252
-
253
- Returns:
254
- CommandLineCodeResult: The result of the code execution."""
255
- if not self._setup_functions_complete:
256
- self._setup_functions()
257
- return self._execute_code_dont_check_setup(code_blocks)
258
-
259
- def _execute_code_dont_check_setup(self, code_blocks: List[CodeBlock]) -> CommandLineCodeResult:
260
- logs_all = ""
261
- file_names = []
262
- for code_block in code_blocks:
263
- lang, code = code_block.language, code_block.code
264
- lang = lang.lower()
265
-
266
- LocalCommandLineCodeExecutor.sanitize_command(lang, code)
267
- code = silence_pip(code, lang)
268
-
269
- if lang in PYTHON_VARIANTS:
270
- lang = "python"
271
-
272
- if WIN32 and lang in ["sh", "shell"]:
273
- lang = "ps1"
274
-
275
- if lang not in self.SUPPORTED_LANGUAGES:
276
- # In case the language is not supported, we return an error message.
277
- exitcode = 1
278
- logs_all += "\n" + f"unknown language {lang}"
279
- break
280
-
281
- execute_code = self.execution_policies.get(lang, False)
282
- try:
283
- # Check if there is a filename comment
284
- filename = _get_file_name_from_content(code, self._work_dir)
285
- except ValueError:
286
- return CommandLineCodeResult(exit_code=1, output="Filename is not in the workspace")
287
-
288
- if filename is None:
289
- # create a file with an automatically generated name
290
- code_hash = md5(code.encode()).hexdigest()
291
- filename = f"tmp_code_{code_hash}.{'py' if lang.startswith('python') else lang}"
292
- written_file = (self._work_dir / filename).resolve()
293
- with written_file.open("w", encoding="utf-8") as f:
294
- f.write(code)
295
- file_names.append(written_file)
296
-
297
- if not execute_code:
298
- # Just return a message that the file is saved.
299
- logs_all += f"Code saved to {str(written_file)}\n"
300
- exitcode = 0
301
- continue
302
-
303
- program = _cmd(lang)
304
- cmd = [program, str(written_file.absolute())]
305
- env = os.environ.copy()
306
-
307
- if self._virtual_env_context:
308
- virtual_env_abs_path = os.path.abspath(self._virtual_env_context.bin_path)
309
- path_with_virtualenv = rf"{virtual_env_abs_path}{os.pathsep}{env['PATH']}"
310
- env["PATH"] = path_with_virtualenv
311
- if WIN32:
312
- activation_script = os.path.join(virtual_env_abs_path, "activate.bat")
313
- cmd = [activation_script, "&&", *cmd]
314
-
315
- try:
316
- result = subprocess.run(
317
- cmd,
318
- cwd=self._work_dir,
319
- capture_output=True,
320
- text=True,
321
- timeout=float(self._timeout),
322
- env=env,
323
- encoding="utf-8",
324
- )
325
- except subprocess.TimeoutExpired:
326
- logs_all += "\n" + TIMEOUT_MSG
327
- # Same exit code as the timeout command on linux.
328
- exitcode = 124
329
- break
330
-
331
- logs_all += result.stderr
332
- logs_all += result.stdout
333
- exitcode = result.returncode
334
-
335
- if exitcode != 0:
336
- break
337
-
338
- code_file = str(file_names[0]) if len(file_names) > 0 else None
339
- return CommandLineCodeResult(exit_code=exitcode, output=logs_all, code_file=code_file)
340
-
341
- def restart(self) -> None:
342
- """(Experimental) Restart the code executor."""
343
- warnings.warn("Restarting local command line code executor is not supported. No action is taken.")
344
-
345
-
346
- # From stack overflow: https://stackoverflow.com/a/52087847/2214524
347
- class _DeprecatedClassMeta(type):
348
- def __new__(cls, name, bases, classdict, *args, **kwargs): # type: ignore[no-untyped-def]
349
- alias = classdict.get("_DeprecatedClassMeta__alias")
350
-
351
- if alias is not None:
352
-
353
- def new(cls, *args, **kwargs): # type: ignore[no-untyped-def]
354
- alias = getattr(cls, "_DeprecatedClassMeta__alias")
355
-
356
- if alias is not None:
357
- warnings.warn(
358
- "{} has been renamed to {}, the alias will be "
359
- "removed in the future".format(cls.__name__, alias.__name__),
360
- DeprecationWarning,
361
- stacklevel=2,
362
- )
363
-
364
- return alias(*args, **kwargs)
365
-
366
- classdict["__new__"] = new
367
- classdict["_DeprecatedClassMeta__alias"] = alias
368
-
369
- fixed_bases = []
370
-
371
- for b in bases:
372
- alias = getattr(b, "_DeprecatedClassMeta__alias", None)
373
-
374
- if alias is not None:
375
- warnings.warn(
376
- "{} has been renamed to {}, the alias will be "
377
- "removed in the future".format(b.__name__, alias.__name__),
378
- DeprecationWarning,
379
- stacklevel=2,
380
- )
381
-
382
- # Avoid duplicate base classes.
383
- b = alias or b
384
- if b not in fixed_bases:
385
- fixed_bases.append(b)
386
-
387
- fixed_bases = tuple(fixed_bases) # type: ignore[assignment]
388
-
389
- return super().__new__(cls, name, fixed_bases, classdict, *args, **kwargs) # type: ignore[call-overload]
390
-
391
- def __instancecheck__(cls, instance): # type: ignore[no-untyped-def]
392
- return any(cls.__subclasscheck__(c) for c in {type(instance), instance.__class__}) # type: ignore[no-untyped-call]
393
-
394
- def __subclasscheck__(cls, subclass): # type: ignore[no-untyped-def]
395
- if subclass is cls:
396
- return True
397
- else:
398
- return issubclass(subclass, getattr(cls, "_DeprecatedClassMeta__alias"))
399
-
400
-
401
- class LocalCommandlineCodeExecutor(metaclass=_DeprecatedClassMeta):
402
- """LocalCommandlineCodeExecutor renamed to LocalCommandLineCodeExecutor"""
403
-
404
- _DeprecatedClassMeta__alias = LocalCommandLineCodeExecutor
405
-
406
-
407
- class CommandlineCodeResult(metaclass=_DeprecatedClassMeta):
408
- """CommandlineCodeResult renamed to CommandLineCodeResult"""
409
-
410
- _DeprecatedClassMeta__alias = CommandLineCodeResult
@@ -1,44 +0,0 @@
1
- # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
- #
3
- # SPDX-License-Identifier: Apache-2.0
4
- #
5
- # Portions derived from https://github.com/microsoft/autogen are under the MIT License.
6
- # SPDX-License-Identifier: MIT
7
- import re
8
- from typing import Any, Dict, List, Optional, Union
9
-
10
- from ..code_utils import CODE_BLOCK_PATTERN, UNKNOWN, content_str, infer_lang
11
- from ..types import UserMessageImageContentPart, UserMessageTextContentPart
12
- from .base import CodeBlock, CodeExtractor
13
-
14
- __all__ = ("MarkdownCodeExtractor",)
15
-
16
-
17
- class MarkdownCodeExtractor(CodeExtractor):
18
- """(Experimental) A class that extracts code blocks from a message using Markdown syntax."""
19
-
20
- def extract_code_blocks(
21
- self, message: Union[str, List[Union[UserMessageTextContentPart, UserMessageImageContentPart]], None]
22
- ) -> List[CodeBlock]:
23
- """(Experimental) Extract code blocks from a message. If no code blocks are found,
24
- return an empty list.
25
-
26
- Args:
27
- message (str): The message to extract code blocks from.
28
-
29
- Returns:
30
- List[CodeBlock]: The extracted code blocks or an empty list.
31
- """
32
-
33
- text = content_str(message)
34
- match = re.findall(CODE_BLOCK_PATTERN, text, flags=re.DOTALL)
35
- if not match:
36
- return []
37
- code_blocks = []
38
- for lang, code in match:
39
- if lang == "":
40
- lang = infer_lang(code)
41
- if lang == UNKNOWN:
42
- lang = ""
43
- code_blocks.append(CodeBlock(code=code, language=lang))
44
- return code_blocks
autogen/coding/utils.py DELETED
@@ -1,57 +0,0 @@
1
- # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
- #
3
- # SPDX-License-Identifier: Apache-2.0
4
- #
5
- # Portions derived from https://github.com/ag2ai/ag2 are under the MIT License.
6
- # SPDX-License-Identifier: MIT
7
- # Will return the filename relative to the workspace path
8
- import re
9
- from pathlib import Path
10
- from typing import Optional
11
-
12
- filename_patterns = [
13
- re.compile(r"^<!-- (filename:)?(.+?) -->", re.DOTALL),
14
- re.compile(r"^/\* (filename:)?(.+?) \*/", re.DOTALL),
15
- re.compile(r"^// (filename:)?(.+?)$", re.DOTALL),
16
- re.compile(r"^# (filename:)?(.+?)$", re.DOTALL),
17
- ]
18
-
19
-
20
- # Raises ValueError if the file is not in the workspace
21
- def _get_file_name_from_content(code: str, workspace_path: Path) -> Optional[str]:
22
- first_line = code.split("\n")[0].strip()
23
- # TODO - support other languages
24
- for pattern in filename_patterns:
25
- matches = pattern.match(first_line)
26
- if matches is not None:
27
- filename = matches.group(2).strip()
28
-
29
- # Handle relative paths in the filename
30
- path = Path(filename)
31
- if not path.is_absolute():
32
- path = workspace_path / path
33
- path = path.resolve()
34
- # Throws an error if the file is not in the workspace
35
- relative = path.relative_to(workspace_path.resolve())
36
- return str(relative)
37
- return None
38
-
39
-
40
- def silence_pip(code: str, lang: str) -> str:
41
- """Apply -qqq flag to pip install commands."""
42
- if lang == "python":
43
- regex = r"^! ?pip install"
44
- elif lang in ["bash", "shell", "sh", "pwsh", "powershell", "ps1"]:
45
- regex = r"^pip install"
46
- else:
47
- return code
48
-
49
- # Find lines that start with pip install and make sure "-qqq" flag is added.
50
- lines = code.split("\n")
51
- for i, line in enumerate(lines):
52
- # use regex to find lines that start with pip install.
53
- match = re.search(regex, line)
54
- if match is not None:
55
- if "-qqq" not in line:
56
- lines[i] = line.replace(match.group(0), match.group(0) + " -qqq")
57
- return "\n".join(lines)
@@ -1,46 +0,0 @@
1
- # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
- #
3
- # SPDX-License-Identifier: Apache-2.0
4
- #
5
- # Portions derived from https://github.com/microsoft/autogen are under the MIT License.
6
- # SPDX-License-Identifier: MIT
7
- from typing import Any
8
-
9
-
10
- class AgentNameConflict(Exception):
11
- def __init__(self, msg: str = "Found multiple agents with the same name.", *args: Any, **kwargs: Any):
12
- super().__init__(msg, *args, **kwargs)
13
-
14
-
15
- class NoEligibleSpeaker(Exception):
16
- """Exception raised for early termination of a GroupChat."""
17
-
18
- def __init__(self, message: str = "No eligible speakers."):
19
- self.message = message
20
- super().__init__(self.message)
21
-
22
-
23
- class SenderRequired(Exception):
24
- """Exception raised when the sender is required but not provided."""
25
-
26
- def __init__(self, message: str = "Sender is required but not provided."):
27
- self.message = message
28
- super().__init__(self.message)
29
-
30
-
31
- class InvalidCarryOverType(Exception):
32
- """Exception raised when the carryover type is invalid."""
33
-
34
- def __init__(
35
- self, message: str = "Carryover should be a string or a list of strings. Not adding carryover to the message."
36
- ):
37
- self.message = message
38
- super().__init__(self.message)
39
-
40
-
41
- class UndefinedNextAgent(Exception):
42
- """Exception raised when the provided next agents list does not overlap with agents in the group."""
43
-
44
- def __init__(self, message: str = "The provided agents list does not overlap with agents in the group."):
45
- self.message = message
46
- super().__init__(self.message)
File without changes
@@ -1,76 +0,0 @@
1
- # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
- #
3
- # SPDX-License-Identifier: Apache-2.0
4
- #
5
- # Portions derived from https://github.com/microsoft/autogen are under the MIT License.
6
- # SPDX-License-Identifier: MIT
7
- from __future__ import annotations
8
-
9
- from typing import Iterable, Literal
10
-
11
- try:
12
- from termcolor import colored
13
- except ImportError:
14
- # termcolor is an optional dependency - if it cannot be imported then no color is used.
15
- # Alternatively the envvar NO_COLOR can be used to disable color.
16
- # To allow for proper typing and for termcolor to be optional we need to re-define the types used in the lib here.
17
- # This is the direct function definition from termcolor.
18
- Attribute = Literal[
19
- "bold",
20
- "dark",
21
- "underline",
22
- "blink",
23
- "reverse",
24
- "concealed",
25
- ]
26
-
27
- Highlight = Literal[
28
- "on_black",
29
- "on_grey",
30
- "on_red",
31
- "on_green",
32
- "on_yellow",
33
- "on_blue",
34
- "on_magenta",
35
- "on_cyan",
36
- "on_light_grey",
37
- "on_dark_grey",
38
- "on_light_red",
39
- "on_light_green",
40
- "on_light_yellow",
41
- "on_light_blue",
42
- "on_light_magenta",
43
- "on_light_cyan",
44
- "on_white",
45
- ]
46
-
47
- Color = Literal[
48
- "black",
49
- "grey",
50
- "red",
51
- "green",
52
- "yellow",
53
- "blue",
54
- "magenta",
55
- "cyan",
56
- "light_grey",
57
- "dark_grey",
58
- "light_red",
59
- "light_green",
60
- "light_yellow",
61
- "light_blue",
62
- "light_magenta",
63
- "light_cyan",
64
- "white",
65
- ]
66
-
67
- def colored(
68
- text: object,
69
- color: Color | None = None,
70
- on_color: Highlight | None = None,
71
- attrs: Iterable[Attribute] | None = None,
72
- *,
73
- no_color: bool | None = None,
74
- force_color: bool | None = None,
75
- ) -> str:
76
- return str(text)