ag2 0.4.1__py3-none-any.whl → 0.5.0b2__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 (160) hide show
  1. {ag2-0.4.1.dist-info → ag2-0.5.0b2.dist-info}/METADATA +5 -146
  2. ag2-0.5.0b2.dist-info/RECORD +6 -0
  3. ag2-0.5.0b2.dist-info/top_level.txt +1 -0
  4. ag2-0.4.1.dist-info/RECORD +0 -158
  5. ag2-0.4.1.dist-info/top_level.txt +0 -1
  6. autogen/__init__.py +0 -17
  7. autogen/_pydantic.py +0 -116
  8. autogen/agentchat/__init__.py +0 -42
  9. autogen/agentchat/agent.py +0 -142
  10. autogen/agentchat/assistant_agent.py +0 -85
  11. autogen/agentchat/chat.py +0 -306
  12. autogen/agentchat/contrib/__init__.py +0 -0
  13. autogen/agentchat/contrib/agent_builder.py +0 -788
  14. autogen/agentchat/contrib/agent_eval/agent_eval.py +0 -107
  15. autogen/agentchat/contrib/agent_eval/criterion.py +0 -47
  16. autogen/agentchat/contrib/agent_eval/critic_agent.py +0 -47
  17. autogen/agentchat/contrib/agent_eval/quantifier_agent.py +0 -42
  18. autogen/agentchat/contrib/agent_eval/subcritic_agent.py +0 -48
  19. autogen/agentchat/contrib/agent_eval/task.py +0 -43
  20. autogen/agentchat/contrib/agent_optimizer.py +0 -450
  21. autogen/agentchat/contrib/capabilities/__init__.py +0 -0
  22. autogen/agentchat/contrib/capabilities/agent_capability.py +0 -21
  23. autogen/agentchat/contrib/capabilities/generate_images.py +0 -297
  24. autogen/agentchat/contrib/capabilities/teachability.py +0 -406
  25. autogen/agentchat/contrib/capabilities/text_compressors.py +0 -72
  26. autogen/agentchat/contrib/capabilities/transform_messages.py +0 -92
  27. autogen/agentchat/contrib/capabilities/transforms.py +0 -565
  28. autogen/agentchat/contrib/capabilities/transforms_util.py +0 -120
  29. autogen/agentchat/contrib/capabilities/vision_capability.py +0 -217
  30. autogen/agentchat/contrib/captainagent/tools/__init__.py +0 -0
  31. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_correlation.py +0 -41
  32. autogen/agentchat/contrib/captainagent/tools/data_analysis/calculate_skewness_and_kurtosis.py +0 -29
  33. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_iqr.py +0 -29
  34. autogen/agentchat/contrib/captainagent/tools/data_analysis/detect_outlier_zscore.py +0 -29
  35. autogen/agentchat/contrib/captainagent/tools/data_analysis/explore_csv.py +0 -22
  36. autogen/agentchat/contrib/captainagent/tools/data_analysis/shapiro_wilk_test.py +0 -31
  37. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_download.py +0 -26
  38. autogen/agentchat/contrib/captainagent/tools/information_retrieval/arxiv_search.py +0 -55
  39. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_image.py +0 -54
  40. autogen/agentchat/contrib/captainagent/tools/information_retrieval/extract_pdf_text.py +0 -39
  41. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_wikipedia_text.py +0 -22
  42. autogen/agentchat/contrib/captainagent/tools/information_retrieval/get_youtube_caption.py +0 -35
  43. autogen/agentchat/contrib/captainagent/tools/information_retrieval/image_qa.py +0 -61
  44. autogen/agentchat/contrib/captainagent/tools/information_retrieval/optical_character_recognition.py +0 -62
  45. autogen/agentchat/contrib/captainagent/tools/information_retrieval/perform_web_search.py +0 -48
  46. autogen/agentchat/contrib/captainagent/tools/information_retrieval/scrape_wikipedia_tables.py +0 -34
  47. autogen/agentchat/contrib/captainagent/tools/information_retrieval/transcribe_audio_file.py +0 -22
  48. autogen/agentchat/contrib/captainagent/tools/information_retrieval/youtube_download.py +0 -36
  49. autogen/agentchat/contrib/captainagent/tools/math/calculate_circle_area_from_diameter.py +0 -22
  50. autogen/agentchat/contrib/captainagent/tools/math/calculate_day_of_the_week.py +0 -19
  51. autogen/agentchat/contrib/captainagent/tools/math/calculate_fraction_sum.py +0 -29
  52. autogen/agentchat/contrib/captainagent/tools/math/calculate_matrix_power.py +0 -32
  53. autogen/agentchat/contrib/captainagent/tools/math/calculate_reflected_point.py +0 -17
  54. autogen/agentchat/contrib/captainagent/tools/math/complex_numbers_product.py +0 -26
  55. autogen/agentchat/contrib/captainagent/tools/math/compute_currency_conversion.py +0 -24
  56. autogen/agentchat/contrib/captainagent/tools/math/count_distinct_permutations.py +0 -28
  57. autogen/agentchat/contrib/captainagent/tools/math/evaluate_expression.py +0 -29
  58. autogen/agentchat/contrib/captainagent/tools/math/find_continuity_point.py +0 -35
  59. autogen/agentchat/contrib/captainagent/tools/math/fraction_to_mixed_numbers.py +0 -40
  60. autogen/agentchat/contrib/captainagent/tools/math/modular_inverse_sum.py +0 -23
  61. autogen/agentchat/contrib/captainagent/tools/math/simplify_mixed_numbers.py +0 -37
  62. autogen/agentchat/contrib/captainagent/tools/math/sum_of_digit_factorials.py +0 -16
  63. autogen/agentchat/contrib/captainagent/tools/math/sum_of_primes_below.py +0 -16
  64. autogen/agentchat/contrib/captainagent/tools/requirements.txt +0 -10
  65. autogen/agentchat/contrib/captainagent/tools/tool_description.tsv +0 -34
  66. autogen/agentchat/contrib/captainagent.py +0 -490
  67. autogen/agentchat/contrib/gpt_assistant_agent.py +0 -545
  68. autogen/agentchat/contrib/graph_rag/__init__.py +0 -0
  69. autogen/agentchat/contrib/graph_rag/document.py +0 -30
  70. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +0 -111
  71. autogen/agentchat/contrib/graph_rag/falkor_graph_rag_capability.py +0 -81
  72. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +0 -56
  73. autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +0 -64
  74. autogen/agentchat/contrib/img_utils.py +0 -390
  75. autogen/agentchat/contrib/llamaindex_conversable_agent.py +0 -123
  76. autogen/agentchat/contrib/llava_agent.py +0 -176
  77. autogen/agentchat/contrib/math_user_proxy_agent.py +0 -471
  78. autogen/agentchat/contrib/multimodal_conversable_agent.py +0 -128
  79. autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +0 -325
  80. autogen/agentchat/contrib/retrieve_assistant_agent.py +0 -56
  81. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +0 -705
  82. autogen/agentchat/contrib/society_of_mind_agent.py +0 -203
  83. autogen/agentchat/contrib/swarm_agent.py +0 -463
  84. autogen/agentchat/contrib/text_analyzer_agent.py +0 -76
  85. autogen/agentchat/contrib/tool_retriever.py +0 -120
  86. autogen/agentchat/contrib/vectordb/__init__.py +0 -0
  87. autogen/agentchat/contrib/vectordb/base.py +0 -243
  88. autogen/agentchat/contrib/vectordb/chromadb.py +0 -326
  89. autogen/agentchat/contrib/vectordb/mongodb.py +0 -559
  90. autogen/agentchat/contrib/vectordb/pgvectordb.py +0 -958
  91. autogen/agentchat/contrib/vectordb/qdrant.py +0 -334
  92. autogen/agentchat/contrib/vectordb/utils.py +0 -126
  93. autogen/agentchat/contrib/web_surfer.py +0 -305
  94. autogen/agentchat/conversable_agent.py +0 -2908
  95. autogen/agentchat/groupchat.py +0 -1668
  96. autogen/agentchat/user_proxy_agent.py +0 -109
  97. autogen/agentchat/utils.py +0 -207
  98. autogen/browser_utils.py +0 -291
  99. autogen/cache/__init__.py +0 -10
  100. autogen/cache/abstract_cache_base.py +0 -78
  101. autogen/cache/cache.py +0 -182
  102. autogen/cache/cache_factory.py +0 -85
  103. autogen/cache/cosmos_db_cache.py +0 -150
  104. autogen/cache/disk_cache.py +0 -109
  105. autogen/cache/in_memory_cache.py +0 -61
  106. autogen/cache/redis_cache.py +0 -128
  107. autogen/code_utils.py +0 -745
  108. autogen/coding/__init__.py +0 -22
  109. autogen/coding/base.py +0 -113
  110. autogen/coding/docker_commandline_code_executor.py +0 -262
  111. autogen/coding/factory.py +0 -45
  112. autogen/coding/func_with_reqs.py +0 -203
  113. autogen/coding/jupyter/__init__.py +0 -22
  114. autogen/coding/jupyter/base.py +0 -32
  115. autogen/coding/jupyter/docker_jupyter_server.py +0 -164
  116. autogen/coding/jupyter/embedded_ipython_code_executor.py +0 -182
  117. autogen/coding/jupyter/jupyter_client.py +0 -224
  118. autogen/coding/jupyter/jupyter_code_executor.py +0 -161
  119. autogen/coding/jupyter/local_jupyter_server.py +0 -168
  120. autogen/coding/local_commandline_code_executor.py +0 -410
  121. autogen/coding/markdown_code_extractor.py +0 -44
  122. autogen/coding/utils.py +0 -57
  123. autogen/exception_utils.py +0 -46
  124. autogen/extensions/__init__.py +0 -0
  125. autogen/formatting_utils.py +0 -76
  126. autogen/function_utils.py +0 -362
  127. autogen/graph_utils.py +0 -148
  128. autogen/io/__init__.py +0 -15
  129. autogen/io/base.py +0 -105
  130. autogen/io/console.py +0 -43
  131. autogen/io/websockets.py +0 -213
  132. autogen/logger/__init__.py +0 -11
  133. autogen/logger/base_logger.py +0 -140
  134. autogen/logger/file_logger.py +0 -287
  135. autogen/logger/logger_factory.py +0 -29
  136. autogen/logger/logger_utils.py +0 -42
  137. autogen/logger/sqlite_logger.py +0 -459
  138. autogen/math_utils.py +0 -356
  139. autogen/oai/__init__.py +0 -33
  140. autogen/oai/anthropic.py +0 -428
  141. autogen/oai/bedrock.py +0 -606
  142. autogen/oai/cerebras.py +0 -270
  143. autogen/oai/client.py +0 -1148
  144. autogen/oai/client_utils.py +0 -167
  145. autogen/oai/cohere.py +0 -453
  146. autogen/oai/completion.py +0 -1216
  147. autogen/oai/gemini.py +0 -469
  148. autogen/oai/groq.py +0 -281
  149. autogen/oai/mistral.py +0 -279
  150. autogen/oai/ollama.py +0 -582
  151. autogen/oai/openai_utils.py +0 -811
  152. autogen/oai/together.py +0 -343
  153. autogen/retrieve_utils.py +0 -487
  154. autogen/runtime_logging.py +0 -163
  155. autogen/token_count_utils.py +0 -259
  156. autogen/types.py +0 -20
  157. autogen/version.py +0 -7
  158. {ag2-0.4.1.dist-info → ag2-0.5.0b2.dist-info}/LICENSE +0 -0
  159. {ag2-0.4.1.dist-info → ag2-0.5.0b2.dist-info}/NOTICE.md +0 -0
  160. {ag2-0.4.1.dist-info → ag2-0.5.0b2.dist-info}/WHEEL +0 -0
@@ -1,22 +0,0 @@
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
- from .base import CodeBlock, CodeExecutor, CodeExtractor, CodeResult
8
- from .docker_commandline_code_executor import DockerCommandLineCodeExecutor
9
- from .factory import CodeExecutorFactory
10
- from .local_commandline_code_executor import LocalCommandLineCodeExecutor
11
- from .markdown_code_extractor import MarkdownCodeExtractor
12
-
13
- __all__ = (
14
- "CodeBlock",
15
- "CodeResult",
16
- "CodeExtractor",
17
- "CodeExecutor",
18
- "CodeExecutorFactory",
19
- "MarkdownCodeExtractor",
20
- "LocalCommandLineCodeExecutor",
21
- "DockerCommandLineCodeExecutor",
22
- )
autogen/coding/base.py DELETED
@@ -1,113 +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 Any, List, Literal, Mapping, Optional, Protocol, TypedDict, Union, runtime_checkable
10
-
11
- from pydantic import BaseModel, Field
12
-
13
- from ..types import UserMessageImageContentPart, UserMessageTextContentPart
14
-
15
- __all__ = ("CodeBlock", "CodeResult", "CodeExtractor", "CodeExecutor", "CodeExecutionConfig")
16
-
17
-
18
- class CodeBlock(BaseModel):
19
- """(Experimental) A class that represents a code block."""
20
-
21
- code: str = Field(description="The code to execute.")
22
-
23
- language: str = Field(description="The language of the code.")
24
-
25
-
26
- class CodeResult(BaseModel):
27
- """(Experimental) A class that represents the result of a code execution."""
28
-
29
- exit_code: int = Field(description="The exit code of the code execution.")
30
-
31
- output: str = Field(description="The output of the code execution.")
32
-
33
-
34
- class CodeExtractor(Protocol):
35
- """(Experimental) A code extractor class that extracts code blocks from a message."""
36
-
37
- def extract_code_blocks(
38
- self, message: Union[str, List[Union[UserMessageTextContentPart, UserMessageImageContentPart]], None]
39
- ) -> List[CodeBlock]:
40
- """(Experimental) Extract code blocks from a message.
41
-
42
- Args:
43
- message (str): The message to extract code blocks from.
44
-
45
- Returns:
46
- List[CodeBlock]: The extracted code blocks.
47
- """
48
- ... # pragma: no cover
49
-
50
-
51
- @runtime_checkable
52
- class CodeExecutor(Protocol):
53
- """(Experimental) A code executor class that executes code blocks and returns the result."""
54
-
55
- @property
56
- def code_extractor(self) -> CodeExtractor:
57
- """(Experimental) The code extractor used by this code executor."""
58
- ... # pragma: no cover
59
-
60
- def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CodeResult:
61
- """(Experimental) Execute code blocks and return the result.
62
-
63
- This method should be implemented by the code executor.
64
-
65
- Args:
66
- code_blocks (List[CodeBlock]): The code blocks to execute.
67
-
68
- Returns:
69
- CodeResult: The result of the code execution.
70
- """
71
- ... # pragma: no cover
72
-
73
- def restart(self) -> None:
74
- """(Experimental) Restart the code executor.
75
-
76
- This method should be implemented by the code executor.
77
-
78
- This method is called when the agent is reset.
79
- """
80
- ... # pragma: no cover
81
-
82
-
83
- class IPythonCodeResult(CodeResult):
84
- """(Experimental) A code result class for IPython code executor."""
85
-
86
- output_files: List[str] = Field(
87
- default_factory=list,
88
- description="The list of files that the executed code blocks generated.",
89
- )
90
-
91
-
92
- CodeExecutionConfig = TypedDict(
93
- "CodeExecutionConfig",
94
- {
95
- "executor": Union[Literal["ipython-embedded", "commandline-local"], CodeExecutor],
96
- "last_n_messages": Union[int, Literal["auto"]],
97
- "timeout": int,
98
- "use_docker": Union[bool, str, List[str]],
99
- "work_dir": str,
100
- "ipython-embedded": Mapping[str, Any],
101
- "commandline-local": Mapping[str, Any],
102
- },
103
- total=False,
104
- )
105
-
106
-
107
- class CommandLineCodeResult(CodeResult):
108
- """(Experimental) A code result class for command line code executor."""
109
-
110
- code_file: Optional[str] = Field(
111
- default=None,
112
- description="The file that the executed code block was saved to.",
113
- )
@@ -1,262 +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
- import atexit
10
- import logging
11
- import sys
12
- import uuid
13
- from hashlib import md5
14
- from pathlib import Path
15
- from time import sleep
16
- from types import TracebackType
17
- from typing import Any, ClassVar, Dict, List, Optional, Type, Union
18
-
19
- import docker
20
- from docker.errors import ImageNotFound
21
-
22
- from ..code_utils import TIMEOUT_MSG, _cmd
23
- from .base import CodeBlock, CodeExecutor, CodeExtractor, CommandLineCodeResult
24
- from .markdown_code_extractor import MarkdownCodeExtractor
25
- from .utils import _get_file_name_from_content, silence_pip
26
-
27
- if sys.version_info >= (3, 11):
28
- from typing import Self
29
- else:
30
- from typing_extensions import Self
31
-
32
-
33
- def _wait_for_ready(container: Any, timeout: int = 60, stop_time: float = 0.1) -> None:
34
- elapsed_time = 0.0
35
- while container.status != "running" and elapsed_time < timeout:
36
- sleep(stop_time)
37
- elapsed_time += stop_time
38
- container.reload()
39
- continue
40
- if container.status != "running":
41
- raise ValueError("Container failed to start")
42
-
43
-
44
- __all__ = ("DockerCommandLineCodeExecutor",)
45
-
46
-
47
- class DockerCommandLineCodeExecutor(CodeExecutor):
48
- DEFAULT_EXECUTION_POLICY: ClassVar[Dict[str, bool]] = {
49
- "bash": True,
50
- "shell": True,
51
- "sh": True,
52
- "pwsh": True,
53
- "powershell": True,
54
- "ps1": True,
55
- "python": True,
56
- "javascript": False,
57
- "html": False,
58
- "css": False,
59
- }
60
- LANGUAGE_ALIASES: ClassVar[Dict[str, str]] = {"py": "python", "js": "javascript"}
61
-
62
- def __init__(
63
- self,
64
- image: str = "python:3-slim",
65
- container_name: Optional[str] = None,
66
- timeout: int = 60,
67
- work_dir: Union[Path, str] = Path("."),
68
- bind_dir: Optional[Union[Path, str]] = None,
69
- auto_remove: bool = True,
70
- stop_container: bool = True,
71
- execution_policies: Optional[Dict[str, bool]] = None,
72
- ):
73
- """(Experimental) A code executor class that executes code through
74
- a command line environment in a Docker container.
75
-
76
- The executor first saves each code block in a file in the working
77
- directory, and then executes the code file in the container.
78
- The executor executes the code blocks in the order they are received.
79
- Currently, the executor only supports Python and shell scripts.
80
- For Python code, use the language "python" for the code block.
81
- For shell scripts, use the language "bash", "shell", or "sh" for the code
82
- block.
83
-
84
- Args:
85
- image (_type_, optional): Docker image to use for code execution.
86
- Defaults to "python:3-slim".
87
- container_name (Optional[str], optional): Name of the Docker container
88
- which is created. If None, will autogenerate a name. Defaults to None.
89
- timeout (int, optional): The timeout for code execution. Defaults to 60.
90
- work_dir (Union[Path, str], optional): The working directory for the code
91
- execution. Defaults to Path(".").
92
- bind_dir (Union[Path, str], optional): The directory that will be bound
93
- to the code executor container. Useful for cases where you want to spawn
94
- the container from within a container. Defaults to work_dir.
95
- auto_remove (bool, optional): If true, will automatically remove the Docker
96
- container when it is stopped. Defaults to True.
97
- stop_container (bool, optional): If true, will automatically stop the
98
- container when stop is called, when the context manager exits or when
99
- the Python process exits with atext. Defaults to True.
100
-
101
- Raises:
102
- ValueError: On argument error, or if the container fails to start.
103
- """
104
- if timeout < 1:
105
- raise ValueError("Timeout must be greater than or equal to 1.")
106
-
107
- if isinstance(work_dir, str):
108
- work_dir = Path(work_dir)
109
- work_dir.mkdir(exist_ok=True)
110
-
111
- if bind_dir is None:
112
- bind_dir = work_dir
113
- elif isinstance(bind_dir, str):
114
- bind_dir = Path(bind_dir)
115
-
116
- client = docker.from_env()
117
- # Check if the image exists
118
- try:
119
- client.images.get(image)
120
- except ImageNotFound:
121
- logging.info(f"Pulling image {image}...")
122
- # Let the docker exception escape if this fails.
123
- client.images.pull(image)
124
-
125
- if container_name is None:
126
- container_name = f"autogen-code-exec-{uuid.uuid4()}"
127
-
128
- # Start a container from the image, read to exec commands later
129
- self._container = client.containers.create(
130
- image,
131
- name=container_name,
132
- entrypoint="/bin/sh",
133
- tty=True,
134
- auto_remove=auto_remove,
135
- volumes={str(bind_dir.resolve()): {"bind": "/workspace", "mode": "rw"}},
136
- working_dir="/workspace",
137
- )
138
- self._container.start()
139
-
140
- _wait_for_ready(self._container)
141
-
142
- def cleanup() -> None:
143
- try:
144
- container = client.containers.get(container_name)
145
- container.stop()
146
- except docker.errors.NotFound:
147
- pass
148
- atexit.unregister(cleanup)
149
-
150
- if stop_container:
151
- atexit.register(cleanup)
152
-
153
- self._cleanup = cleanup
154
-
155
- # Check if the container is running
156
- if self._container.status != "running":
157
- raise ValueError(f"Failed to start container from image {image}. Logs: {self._container.logs()}")
158
-
159
- self._timeout = timeout
160
- self._work_dir: Path = work_dir
161
- self._bind_dir: Path = bind_dir
162
- self.execution_policies = self.DEFAULT_EXECUTION_POLICY.copy()
163
- if execution_policies is not None:
164
- self.execution_policies.update(execution_policies)
165
-
166
- @property
167
- def timeout(self) -> int:
168
- """(Experimental) The timeout for code execution."""
169
- return self._timeout
170
-
171
- @property
172
- def work_dir(self) -> Path:
173
- """(Experimental) The working directory for the code execution."""
174
- return self._work_dir
175
-
176
- @property
177
- def bind_dir(self) -> Path:
178
- """(Experimental) The binding directory for the code execution container."""
179
- return self._bind_dir
180
-
181
- @property
182
- def code_extractor(self) -> CodeExtractor:
183
- """(Experimental) Export a code extractor that can be used by an agent."""
184
- return MarkdownCodeExtractor()
185
-
186
- def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CommandLineCodeResult:
187
- """(Experimental) Execute the code blocks and return the result.
188
-
189
- Args:
190
- code_blocks (List[CodeBlock]): The code blocks to execute.
191
-
192
- Returns:
193
- CommandlineCodeResult: The result of the code execution."""
194
-
195
- if len(code_blocks) == 0:
196
- raise ValueError("No code blocks to execute.")
197
-
198
- outputs = []
199
- files = []
200
- last_exit_code = 0
201
- for code_block in code_blocks:
202
- lang = self.LANGUAGE_ALIASES.get(code_block.language.lower(), code_block.language.lower())
203
- if lang not in self.DEFAULT_EXECUTION_POLICY:
204
- outputs.append(f"Unsupported language {lang}\n")
205
- last_exit_code = 1
206
- break
207
-
208
- execute_code = self.execution_policies.get(lang, False)
209
- code = silence_pip(code_block.code, lang)
210
-
211
- # Check if there is a filename comment
212
- try:
213
- filename = _get_file_name_from_content(code, self._work_dir)
214
- except ValueError:
215
- outputs.append("Filename is not in the workspace")
216
- last_exit_code = 1
217
- break
218
-
219
- if not filename:
220
- filename = f"tmp_code_{md5(code.encode()).hexdigest()}.{lang}"
221
-
222
- code_path = self._work_dir / filename
223
- with code_path.open("w", encoding="utf-8") as fout:
224
- fout.write(code)
225
- files.append(code_path)
226
-
227
- if not execute_code:
228
- outputs.append(f"Code saved to {str(code_path)}\n")
229
- continue
230
-
231
- command = ["timeout", str(self._timeout), _cmd(lang), filename]
232
- result = self._container.exec_run(command)
233
- exit_code = result.exit_code
234
- output = result.output.decode("utf-8")
235
- if exit_code == 124:
236
- output += "\n" + TIMEOUT_MSG
237
- outputs.append(output)
238
-
239
- last_exit_code = exit_code
240
- if exit_code != 0:
241
- break
242
-
243
- code_file = str(files[0]) if files else None
244
- return CommandLineCodeResult(exit_code=last_exit_code, output="".join(outputs), code_file=code_file)
245
-
246
- def restart(self) -> None:
247
- """(Experimental) Restart the code executor."""
248
- self._container.restart()
249
- if self._container.status != "running":
250
- raise ValueError(f"Failed to restart container. Logs: {self._container.logs()}")
251
-
252
- def stop(self) -> None:
253
- """(Experimental) Stop the code executor."""
254
- self._cleanup()
255
-
256
- def __enter__(self) -> Self:
257
- return self
258
-
259
- def __exit__(
260
- self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]
261
- ) -> None:
262
- self.stop()
autogen/coding/factory.py DELETED
@@ -1,45 +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 .base import CodeExecutionConfig, CodeExecutor
8
-
9
- __all__ = ("CodeExecutorFactory",)
10
-
11
-
12
- class CodeExecutorFactory:
13
- """(Experimental) A factory class for creating code executors."""
14
-
15
- @staticmethod
16
- def create(code_execution_config: CodeExecutionConfig) -> CodeExecutor:
17
- """(Experimental) Get a code executor based on the code execution config.
18
-
19
- Args:
20
- code_execution_config (Dict): The code execution config,
21
- which is a dictionary that must contain the key "executor".
22
- The value of the key "executor" can be either a string
23
- or an instance of CodeExecutor, in which case the code
24
- executor is returned directly.
25
-
26
- Returns:
27
- CodeExecutor: The code executor.
28
-
29
- Raises:
30
- ValueError: If the code executor is unknown or not specified.
31
- """
32
- executor = code_execution_config.get("executor")
33
- if isinstance(executor, CodeExecutor):
34
- # If the executor is already an instance of CodeExecutor, return it.
35
- return executor
36
- if executor == "ipython-embedded":
37
- from .jupyter.embedded_ipython_code_executor import EmbeddedIPythonCodeExecutor
38
-
39
- return EmbeddedIPythonCodeExecutor(**code_execution_config.get("ipython-embedded", {}))
40
- elif executor == "commandline-local":
41
- from .local_commandline_code_executor import LocalCommandLineCodeExecutor
42
-
43
- return LocalCommandLineCodeExecutor(**code_execution_config.get("commandline-local", {}))
44
- else:
45
- raise ValueError(f"Unknown code executor {executor}")
@@ -1,203 +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
- import functools
10
- import importlib
11
- import inspect
12
- from dataclasses import dataclass, field
13
- from importlib.abc import SourceLoader
14
- from textwrap import dedent, indent
15
- from typing import Any, Callable, Generic, List, Set, TypeVar, Union
16
-
17
- from typing_extensions import ParamSpec
18
-
19
- T = TypeVar("T")
20
- P = ParamSpec("P")
21
-
22
-
23
- def _to_code(func: Union[FunctionWithRequirements[T, P], Callable[P, T], FunctionWithRequirementsStr]) -> str:
24
- if isinstance(func, FunctionWithRequirementsStr):
25
- return func.func
26
-
27
- code = inspect.getsource(func)
28
- # Strip the decorator
29
- if code.startswith("@"):
30
- code = code[code.index("\n") + 1 :]
31
- return code
32
-
33
-
34
- @dataclass
35
- class Alias:
36
- name: str
37
- alias: str
38
-
39
-
40
- @dataclass
41
- class ImportFromModule:
42
- module: str
43
- imports: List[Union[str, Alias]]
44
-
45
-
46
- Import = Union[str, ImportFromModule, Alias]
47
-
48
-
49
- def _import_to_str(im: Import) -> str:
50
- if isinstance(im, str):
51
- return f"import {im}"
52
- elif isinstance(im, Alias):
53
- return f"import {im.name} as {im.alias}"
54
- else:
55
-
56
- def to_str(i: Union[str, Alias]) -> str:
57
- if isinstance(i, str):
58
- return i
59
- else:
60
- return f"{i.name} as {i.alias}"
61
-
62
- imports = ", ".join(map(to_str, im.imports))
63
- return f"from {im.module} import {imports}"
64
-
65
-
66
- class _StringLoader(SourceLoader):
67
- def __init__(self, data: str):
68
- self.data = data
69
-
70
- def get_source(self, fullname: str) -> str:
71
- return self.data
72
-
73
- def get_data(self, path: str) -> bytes:
74
- return self.data.encode("utf-8")
75
-
76
- def get_filename(self, fullname: str) -> str:
77
- return "<not a real path>/" + fullname + ".py"
78
-
79
-
80
- @dataclass
81
- class FunctionWithRequirementsStr:
82
- func: str
83
- _compiled_func: Callable[..., Any]
84
- _func_name: str
85
- python_packages: List[str] = field(default_factory=list)
86
- global_imports: List[Import] = field(default_factory=list)
87
-
88
- def __init__(self, func: str, python_packages: List[str] = [], global_imports: List[Import] = []):
89
- self.func = func
90
- self.python_packages = python_packages
91
- self.global_imports = global_imports
92
-
93
- module_name = "func_module"
94
- loader = _StringLoader(func)
95
- spec = importlib.util.spec_from_loader(module_name, loader)
96
- if spec is None:
97
- raise ValueError("Could not create spec")
98
- module = importlib.util.module_from_spec(spec)
99
- if spec.loader is None:
100
- raise ValueError("Could not create loader")
101
-
102
- try:
103
- spec.loader.exec_module(module)
104
- except Exception as e:
105
- raise ValueError(f"Could not compile function: {e}") from e
106
-
107
- functions = inspect.getmembers(module, inspect.isfunction)
108
- if len(functions) != 1:
109
- raise ValueError("The string must contain exactly one function")
110
-
111
- self._func_name, self._compiled_func = functions[0]
112
-
113
- def __call__(self, *args: Any, **kwargs: Any) -> None:
114
- raise NotImplementedError("String based function with requirement objects are not directly callable")
115
-
116
-
117
- @dataclass
118
- class FunctionWithRequirements(Generic[T, P]):
119
- func: Callable[P, T]
120
- python_packages: List[str] = field(default_factory=list)
121
- global_imports: List[Import] = field(default_factory=list)
122
-
123
- @classmethod
124
- def from_callable(
125
- cls, func: Callable[P, T], python_packages: List[str] = [], global_imports: List[Import] = []
126
- ) -> FunctionWithRequirements[T, P]:
127
- return cls(python_packages=python_packages, global_imports=global_imports, func=func)
128
-
129
- @staticmethod
130
- def from_str(
131
- func: str, python_packages: List[str] = [], global_imports: List[Import] = []
132
- ) -> FunctionWithRequirementsStr:
133
- return FunctionWithRequirementsStr(func=func, python_packages=python_packages, global_imports=global_imports)
134
-
135
- # Type this based on F
136
- def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
137
- return self.func(*args, **kwargs)
138
-
139
-
140
- def with_requirements(
141
- python_packages: List[str] = [], global_imports: List[Import] = []
142
- ) -> Callable[[Callable[P, T]], FunctionWithRequirements[T, P]]:
143
- """Decorate a function with package and import requirements
144
-
145
- Args:
146
- python_packages (List[str], optional): Packages required to function. Can include version info.. Defaults to [].
147
- global_imports (List[Import], optional): Required imports. Defaults to [].
148
-
149
- Returns:
150
- Callable[[Callable[P, T]], FunctionWithRequirements[T, P]]: The decorated function
151
- """
152
-
153
- def wrapper(func: Callable[P, T]) -> FunctionWithRequirements[T, P]:
154
- func_with_reqs = FunctionWithRequirements(
155
- python_packages=python_packages, global_imports=global_imports, func=func
156
- )
157
-
158
- functools.update_wrapper(func_with_reqs, func)
159
- return func_with_reqs
160
-
161
- return wrapper
162
-
163
-
164
- def _build_python_functions_file(
165
- funcs: List[Union[FunctionWithRequirements[Any, P], Callable[..., Any], FunctionWithRequirementsStr]]
166
- ) -> str:
167
- # First collect all global imports
168
- global_imports: Set[str] = set()
169
- for func in funcs:
170
- if isinstance(func, (FunctionWithRequirements, FunctionWithRequirementsStr)):
171
- global_imports.update(map(_import_to_str, func.global_imports))
172
-
173
- content = "\n".join(global_imports) + "\n\n"
174
-
175
- for func in funcs:
176
- content += _to_code(func) + "\n\n"
177
-
178
- return content
179
-
180
-
181
- def to_stub(func: Union[Callable[..., Any], FunctionWithRequirementsStr]) -> str:
182
- """Generate a stub for a function as a string
183
-
184
- Args:
185
- func (Callable[..., Any]): The function to generate a stub for
186
-
187
- Returns:
188
- str: The stub for the function
189
- """
190
- if isinstance(func, FunctionWithRequirementsStr):
191
- return to_stub(func._compiled_func)
192
-
193
- content = f"def {func.__name__}{inspect.signature(func)}:\n"
194
- docstring = func.__doc__
195
-
196
- if docstring:
197
- docstring = dedent(docstring)
198
- docstring = '"""' + docstring + '"""'
199
- docstring = indent(docstring, " ")
200
- content += docstring + "\n"
201
-
202
- content += " ..."
203
- return content
@@ -1,22 +0,0 @@
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
- from .base import JupyterConnectable, JupyterConnectionInfo
8
- from .docker_jupyter_server import DockerJupyterServer
9
- from .embedded_ipython_code_executor import EmbeddedIPythonCodeExecutor
10
- from .jupyter_client import JupyterClient
11
- from .jupyter_code_executor import JupyterCodeExecutor
12
- from .local_jupyter_server import LocalJupyterServer
13
-
14
- __all__ = [
15
- "JupyterConnectable",
16
- "JupyterConnectionInfo",
17
- "JupyterClient",
18
- "LocalJupyterServer",
19
- "DockerJupyterServer",
20
- "EmbeddedIPythonCodeExecutor",
21
- "JupyterCodeExecutor",
22
- ]