ag2 0.3.2__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.
- ag2-0.3.2.dist-info/LICENSE +201 -0
- ag2-0.3.2.dist-info/METADATA +490 -0
- ag2-0.3.2.dist-info/NOTICE.md +19 -0
- ag2-0.3.2.dist-info/RECORD +112 -0
- ag2-0.3.2.dist-info/WHEEL +5 -0
- ag2-0.3.2.dist-info/top_level.txt +1 -0
- autogen/__init__.py +17 -0
- autogen/_pydantic.py +116 -0
- autogen/agentchat/__init__.py +26 -0
- autogen/agentchat/agent.py +142 -0
- autogen/agentchat/assistant_agent.py +85 -0
- autogen/agentchat/chat.py +306 -0
- autogen/agentchat/contrib/__init__.py +0 -0
- autogen/agentchat/contrib/agent_builder.py +785 -0
- autogen/agentchat/contrib/agent_optimizer.py +450 -0
- autogen/agentchat/contrib/capabilities/__init__.py +0 -0
- autogen/agentchat/contrib/capabilities/agent_capability.py +21 -0
- autogen/agentchat/contrib/capabilities/generate_images.py +297 -0
- autogen/agentchat/contrib/capabilities/teachability.py +406 -0
- autogen/agentchat/contrib/capabilities/text_compressors.py +72 -0
- autogen/agentchat/contrib/capabilities/transform_messages.py +92 -0
- autogen/agentchat/contrib/capabilities/transforms.py +565 -0
- autogen/agentchat/contrib/capabilities/transforms_util.py +120 -0
- autogen/agentchat/contrib/capabilities/vision_capability.py +217 -0
- autogen/agentchat/contrib/gpt_assistant_agent.py +545 -0
- autogen/agentchat/contrib/graph_rag/__init__.py +0 -0
- autogen/agentchat/contrib/graph_rag/document.py +24 -0
- autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +76 -0
- autogen/agentchat/contrib/graph_rag/graph_query_engine.py +50 -0
- autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +56 -0
- autogen/agentchat/contrib/img_utils.py +390 -0
- autogen/agentchat/contrib/llamaindex_conversable_agent.py +114 -0
- autogen/agentchat/contrib/llava_agent.py +176 -0
- autogen/agentchat/contrib/math_user_proxy_agent.py +471 -0
- autogen/agentchat/contrib/multimodal_conversable_agent.py +128 -0
- autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +325 -0
- autogen/agentchat/contrib/retrieve_assistant_agent.py +56 -0
- autogen/agentchat/contrib/retrieve_user_proxy_agent.py +701 -0
- autogen/agentchat/contrib/society_of_mind_agent.py +203 -0
- autogen/agentchat/contrib/text_analyzer_agent.py +76 -0
- autogen/agentchat/contrib/vectordb/__init__.py +0 -0
- autogen/agentchat/contrib/vectordb/base.py +243 -0
- autogen/agentchat/contrib/vectordb/chromadb.py +326 -0
- autogen/agentchat/contrib/vectordb/mongodb.py +559 -0
- autogen/agentchat/contrib/vectordb/pgvectordb.py +958 -0
- autogen/agentchat/contrib/vectordb/qdrant.py +334 -0
- autogen/agentchat/contrib/vectordb/utils.py +126 -0
- autogen/agentchat/contrib/web_surfer.py +305 -0
- autogen/agentchat/conversable_agent.py +2904 -0
- autogen/agentchat/groupchat.py +1666 -0
- autogen/agentchat/user_proxy_agent.py +109 -0
- autogen/agentchat/utils.py +207 -0
- autogen/browser_utils.py +291 -0
- autogen/cache/__init__.py +10 -0
- autogen/cache/abstract_cache_base.py +78 -0
- autogen/cache/cache.py +182 -0
- autogen/cache/cache_factory.py +85 -0
- autogen/cache/cosmos_db_cache.py +150 -0
- autogen/cache/disk_cache.py +109 -0
- autogen/cache/in_memory_cache.py +61 -0
- autogen/cache/redis_cache.py +128 -0
- autogen/code_utils.py +745 -0
- autogen/coding/__init__.py +22 -0
- autogen/coding/base.py +113 -0
- autogen/coding/docker_commandline_code_executor.py +262 -0
- autogen/coding/factory.py +45 -0
- autogen/coding/func_with_reqs.py +203 -0
- autogen/coding/jupyter/__init__.py +22 -0
- autogen/coding/jupyter/base.py +32 -0
- autogen/coding/jupyter/docker_jupyter_server.py +164 -0
- autogen/coding/jupyter/embedded_ipython_code_executor.py +182 -0
- autogen/coding/jupyter/jupyter_client.py +224 -0
- autogen/coding/jupyter/jupyter_code_executor.py +161 -0
- autogen/coding/jupyter/local_jupyter_server.py +168 -0
- autogen/coding/local_commandline_code_executor.py +410 -0
- autogen/coding/markdown_code_extractor.py +44 -0
- autogen/coding/utils.py +57 -0
- autogen/exception_utils.py +46 -0
- autogen/extensions/__init__.py +0 -0
- autogen/formatting_utils.py +76 -0
- autogen/function_utils.py +362 -0
- autogen/graph_utils.py +148 -0
- autogen/io/__init__.py +15 -0
- autogen/io/base.py +105 -0
- autogen/io/console.py +43 -0
- autogen/io/websockets.py +213 -0
- autogen/logger/__init__.py +11 -0
- autogen/logger/base_logger.py +140 -0
- autogen/logger/file_logger.py +287 -0
- autogen/logger/logger_factory.py +29 -0
- autogen/logger/logger_utils.py +42 -0
- autogen/logger/sqlite_logger.py +459 -0
- autogen/math_utils.py +356 -0
- autogen/oai/__init__.py +33 -0
- autogen/oai/anthropic.py +428 -0
- autogen/oai/bedrock.py +600 -0
- autogen/oai/cerebras.py +264 -0
- autogen/oai/client.py +1148 -0
- autogen/oai/client_utils.py +167 -0
- autogen/oai/cohere.py +453 -0
- autogen/oai/completion.py +1216 -0
- autogen/oai/gemini.py +469 -0
- autogen/oai/groq.py +281 -0
- autogen/oai/mistral.py +279 -0
- autogen/oai/ollama.py +576 -0
- autogen/oai/openai_utils.py +810 -0
- autogen/oai/together.py +343 -0
- autogen/retrieve_utils.py +487 -0
- autogen/runtime_logging.py +163 -0
- autogen/token_count_utils.py +257 -0
- autogen/types.py +20 -0
- autogen/version.py +7 -0
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
# Copyright (c) 2023 - 2024, Owners of https://github.com/autogen-ai
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
#
|
|
5
|
+
# Original portions of this file are derived from https://github.com/microsoft/autogen 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
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Copyright (c) 2023 - 2024, Owners of https://github.com/autogen-ai
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
#
|
|
5
|
+
# Original portions of this file are derived from https://github.com/microsoft/autogen 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
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Copyright (c) 2023 - 2024, Owners of https://github.com/autogen-ai
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
#
|
|
5
|
+
# Original portions of this file are derived from https://github.com/microsoft/autogen 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)
|
|
@@ -0,0 +1,46 @@
|
|
|
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
|
|
@@ -0,0 +1,76 @@
|
|
|
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)
|