From 558b4e33287867eef45f02b27af8b9d68884f16d Mon Sep 17 00:00:00 2001 From: questcollector Date: Thu, 22 Aug 2024 09:18:34 +0900 Subject: [PATCH 01/16] remove coding directory from gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 4c925f739ec6..5bffa374a1a5 100644 --- a/.gitignore +++ b/.gitignore @@ -174,7 +174,7 @@ test/test_files/agenteval-in-out/out/ # local cache or coding foler local_cache/ -coding/ +# coding/ # Files created by tests *tmp_code_* From 0ad239e8f8b8b001cd549ff04fd5e8382e0f21e0 Mon Sep 17 00:00:00 2001 From: questcollector Date: Thu, 22 Aug 2024 10:49:59 +0900 Subject: [PATCH 02/16] add k8s PodCommandLineCodeExecutor --- autogen/coding/kubernetes/__init__.py | 5 + .../pod_commandline_code_executor.py | 268 ++++++++++++++++++ setup.py | 1 + 3 files changed, 274 insertions(+) create mode 100644 autogen/coding/kubernetes/__init__.py create mode 100644 autogen/coding/kubernetes/pod_commandline_code_executor.py diff --git a/autogen/coding/kubernetes/__init__.py b/autogen/coding/kubernetes/__init__.py new file mode 100644 index 000000000000..dc4de611a573 --- /dev/null +++ b/autogen/coding/kubernetes/__init__.py @@ -0,0 +1,5 @@ +from .pod_commandline_code_executor import PodCommandLineCodeExecutor + +__all__ = [ + "PodCommandLineCodeExecutor", +] \ No newline at end of file diff --git a/autogen/coding/kubernetes/pod_commandline_code_executor.py b/autogen/coding/kubernetes/pod_commandline_code_executor.py new file mode 100644 index 000000000000..30693d92abc0 --- /dev/null +++ b/autogen/coding/kubernetes/pod_commandline_code_executor.py @@ -0,0 +1,268 @@ +from __future__ import annotations + +from typing import Any, ClassVar, Dict, List, Optional, Type, Union +from pathlib import Path +from types import TracebackType +from hashlib import md5 +from time import sleep +import textwrap +from pathlib import Path +import uuid +import atexit +import sys + +from kubernetes import config, client +from kubernetes.stream import stream + +from ..base import CodeBlock, CodeExecutor, CodeExtractor, CommandLineCodeResult +from ..markdown_code_extractor import MarkdownCodeExtractor +from ...code_utils import TIMEOUT_MSG, _cmd +from ..utils import _get_file_name_from_content, silence_pip + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + +class PodCommandLineCodeExecutor(CodeExecutor): + DEFAULT_EXECUTION_POLICY: ClassVar[Dict[str, bool]] = { + "bash": True, + "shell": True, + "sh": True, + "pwsh": False, + "powershell": False, + "ps1": False, + "python": True, + "javascript": False, + "html": False, + "css": False, + } + LANGUAGE_ALIASES: ClassVar[Dict[str, str]] = {"py": "python", "js": "javascript"} + LANGUAGE_FILE_EXTENSION: ClassVar[Dict[str, str]] = {"python": "py", "javascript": "js", "bash": "sh", "shell": "sh", "sh": "sh"} + def __init__( + self, + image: str = "python:3-slim", + pod_name: Optional[str] = None, + namespace: Optional[str] = None, + timeout: int = 60, + work_dir: Union[Path, str] = Path("/workspace"), + kubernetes_config_file: Optional[str] = None, + stop_container: bool = True, + execution_policies: Optional[Dict[str, bool]] = None, + ): + """(Experimental) A code executor class that executes code through + a command line environment in a kubernetes pod. + + The executor first saves each code block in a file in the working + directory, and then executes the code file in the container. + The executor executes the code blocks in the order they are received. + Currently, the executor only supports Python and shell scripts. + For Python code, use the language "python" for the code block. + For shell scripts, use the language "bash", "shell", or "sh" for the code + block. + + Args: + image (_type_, optional): Docker image to use for code execution. + Defaults to "python:3-slim". + pod_name (Optional[str], optional): Name of the kubernetes pod + which is created. If None, will autogenerate a name. Defaults to None. + namespace (Optional[str], optional): namespace of kubernetes pod + which is created. If None, will use current namespace of this instance + timeout (int, optional): The timeout for code execution. Defaults to 60. + work_dir (Union[Path, str], optional): The working directory for the code + execution. Defaults to Path("/workspace"). + kubernetes_config_file (Optional[str], optional): kubernetes configuration file path. + If None, will use KUBECONFIG environment variables or service account token(incluster config) + stop_container (bool, optional): If true, will automatically stop the + container when stop is called, when the context manager exits or when + the Python process exits with atext. Defaults to True. + execution_policies (dict[str, bool], optional): defines supported execution launguage + + Raises: + ValueError: On argument error, or if the container fails to start. + """ + if kubernetes_config_file is None: + config.load_config() + else: + config.load_config(config_file=kubernetes_config_file) + + self._api_client = client.CoreV1Api() + + if timeout < 1: + raise ValueError("Timeout must be greater than or equal to 1.") + self._timeout = timeout + + if pod_name is None: + pod_name = f"autogen-code-exec-{uuid.uuid4()}" + if namespace is None: + with open("/var/run/secrets/kubernetes.io/serviceaccount/namespace", "r") as f: + namespace = f.read() + + if isinstance(work_dir, str): + work_dir = Path(work_dir) + self._work_dir: Path = work_dir + + # Start a container from the image, read to exec commands later + + pod = client.V1Pod( + metadata=client.V1ObjectMeta(name=pod_name,namespace=namespace), + spec=client.V1PodSpec( + restart_policy="Never", + containers=[client.V1Container( + args=["-c", "while true;do sleep 5; done"], + command=["/bin/sh"], + name="autogen-code-exec", + image=image + )] + ) + ) + + self._container = self._api_client.create_namespaced_pod(namespace=namespace, body=pod) + + self._wait_for_ready() + + def cleanup() -> None: + from kubernetes.client.rest import ApiException + try: + self._api_client.delete_namespaced_pod(pod_name, namespace) + except ApiException: + pass + atexit.unregister(cleanup) + + self._cleanup = cleanup + + if stop_container: + atexit.register(cleanup) + + self.execution_policies = self.DEFAULT_EXECUTION_POLICY.copy() + if execution_policies is not None: + self.execution_policies.update(execution_policies) + + def _wait_for_ready(self, timeout:int = 60, stop_time: float = 0.1) -> None: + elapsed_time = 0.0 + name = self._container.metadata.name + namespace = self._container.metadata.namespace + while True: + sleep(stop_time) + elapsed_time += stop_time + pod_status = self._api_client.read_namespaced_pod_status(name, namespace) + if pod_status.status.phase == "Running": + break + + @property + def timeout(self) -> int: + """(Experimental) The timeout for code execution.""" + return self._timeout + + @property + def work_dir(self) -> Path: + """(Experimental) The working directory for the code execution.""" + return self._work_dir + + @property + def code_extractor(self) -> CodeExtractor: + """(Experimental) Export a code extractor that can be used by an agent.""" + return MarkdownCodeExtractor() + + def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CommandLineCodeResult: + """(Experimental) Execute the code blocks and return the result. + + Args: + code_blocks (List[CodeBlock]): The code blocks to execute. + + Returns: + CommandlineCodeResult: The result of the code execution.""" + + if len(code_blocks) == 0: + raise ValueError("No code blocks to execute.") + + outputs = [] + files = [] + last_exit_code = 0 + for code_block in code_blocks: + lang = self.LANGUAGE_ALIASES.get(code_block.language.lower(), code_block.language.lower()) + if lang not in self.DEFAULT_EXECUTION_POLICY: + outputs.append(f"Unsupported language {lang}\n") + last_exit_code = 1 + break + + execute_code = self.execution_policies.get(lang, False) + code = silence_pip(code_block.code, lang) + if lang in ["bash", "shell", "sh"]: + code = "\n".join(["#!/bin/bash", code]) + + try: + filename = _get_file_name_from_content(code, self._work_dir) + except ValueError: + outputs.append("Filename is not in the workspace") + last_exit_code = 1 + break + + if not filename: + extension = self.LANGUAGE_FILE_EXTENSION.get(lang, lang) + filename =f"tmp_code_{md5(code.encode()).hexdigest()}.{extension}" + + code_path = self._work_dir / filename + + exec_script = textwrap.dedent( + """ + if [ ! -d "{workspace}" ]; then + mkdir {workspace} + fi + cat <{code_path}\n + {code} + EOM + chmod +x {code_path}""" + ) + exec_script = exec_script.format(workspace=str(self._work_dir), code_path=code_path, code=code) + stream(self._api_client.connect_get_namespaced_pod_exec, + self._container.metadata.name, self._container.metadata.namespace, + command=["/bin/sh", "-c", exec_script], + container="autogen-code-exec", + stderr=True, stdin=False, stdout=True, tty=False) + + files.append(code_path) + + if not execute_code: + outputs.append(f"Code saved to {str(code_path)}\n") + continue + + resp = stream(self._api_client.connect_get_namespaced_pod_exec, + self._container.metadata.name, self._container.metadata.namespace, + command=["timeout", str(self._timeout), _cmd(lang), str(code_path)], + container="autogen-code-exec", + stderr=True, stdin=False, stdout=True, tty=False, _preload_content=False) + + stdout_messages = [] + stderr_messages = [] + while resp.is_open(): + resp.update(timeout=1) + if resp.peek_stderr(): + stderr_messages.append(resp.read_stderr()) + if resp.peek_stdout(): + stdout_messages.append(resp.read_stdout()) + outputs = stdout_messages + stderr_messages + exit_code = resp.returncode + resp.close() + + if exit_code == 124: + outputs.append("\n" + TIMEOUT_MSG) + + last_exit_code = exit_code + if exit_code != 0: + break + + code_file = str(files[0]) if files else None + return CommandLineCodeResult(exit_code=last_exit_code, output="".join(outputs), code_file=code_file) + + def stop(self) -> None: + """(Experimental) Stop the code executor.""" + self._cleanup() + + def __enter__(self) -> Self: + return self + + def __exit__( + self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] + ) -> None: + self.stop() \ No newline at end of file diff --git a/setup.py b/setup.py index fe55a4a6c2ed..dfc5e9127794 100644 --- a/setup.py +++ b/setup.py @@ -107,6 +107,7 @@ "cohere": ["cohere>=5.5.8"], "ollama": ["ollama>=0.3.3", "fix_busted_json>=0.0.18"], "bedrock": ["boto3>=1.34.149"], + "kubernetes": ["kubernetes>=27.2.0"], } setuptools.setup( From a8d98cee8f8366e18095d353b3f4329717ce01ad Mon Sep 17 00:00:00 2001 From: questcollector Date: Thu, 22 Aug 2024 12:33:36 +0900 Subject: [PATCH 03/16] add error handlings and custom pod spec parameter --- .../pod_commandline_code_executor.py | 64 ++++++++++++------- 1 file changed, 42 insertions(+), 22 deletions(-) diff --git a/autogen/coding/kubernetes/pod_commandline_code_executor.py b/autogen/coding/kubernetes/pod_commandline_code_executor.py index 30693d92abc0..98796af09692 100644 --- a/autogen/coding/kubernetes/pod_commandline_code_executor.py +++ b/autogen/coding/kubernetes/pod_commandline_code_executor.py @@ -13,6 +13,7 @@ from kubernetes import config, client from kubernetes.stream import stream +from kubernetes.client.rest import ApiException from ..base import CodeBlock, CodeExecutor, CodeExtractor, CommandLineCodeResult from ..markdown_code_extractor import MarkdownCodeExtractor @@ -37,13 +38,16 @@ class PodCommandLineCodeExecutor(CodeExecutor): "html": False, "css": False, } - LANGUAGE_ALIASES: ClassVar[Dict[str, str]] = {"py": "python", "js": "javascript"} - LANGUAGE_FILE_EXTENSION: ClassVar[Dict[str, str]] = {"python": "py", "javascript": "js", "bash": "sh", "shell": "sh", "sh": "sh"} + LANGUAGE_ALIASES: ClassVar[Dict[str, str]] = {"py": "python", "js": "javascript",} + LANGUAGE_FILE_EXTENSION: ClassVar[Dict[str, str]] = { + "python": "py", "javascript": "js", "bash": "sh", "shell": "sh", "sh": "sh", + } def __init__( self, image: str = "python:3-slim", pod_name: Optional[str] = None, namespace: Optional[str] = None, + pod_spec: Optional[client.V1Pod] = None, timeout: int = 60, work_dir: Union[Path, str] = Path("/workspace"), kubernetes_config_file: Optional[str] = None, @@ -66,8 +70,10 @@ def __init__( Defaults to "python:3-slim". pod_name (Optional[str], optional): Name of the kubernetes pod which is created. If None, will autogenerate a name. Defaults to None. - namespace (Optional[str], optional): namespace of kubernetes pod + namespace (Optional[str], optional): Namespace of kubernetes pod which is created. If None, will use current namespace of this instance + pod_spec (Optional[client.V1Pod], optional): Pod specification of kubernetes pod. + if pod_spec is provided, params above(image, pod_name, namespace) are neglected. timeout (int, optional): The timeout for code execution. Defaults to 60. work_dir (Union[Path, str], optional): The working directory for the code execution. Defaults to Path("/workspace"). @@ -95,7 +101,10 @@ def __init__( if pod_name is None: pod_name = f"autogen-code-exec-{uuid.uuid4()}" if namespace is None: - with open("/var/run/secrets/kubernetes.io/serviceaccount/namespace", "r") as f: + namespace_path = "/var/run/secrets/kubernetes.io/serviceaccount/namespace" + if not Path(namespace_path).is_file(): + raise ValueError("Namespace where the pod will be launched must be provided") + with open(namespace_path, "r") as f: namespace = f.read() if isinstance(work_dir, str): @@ -103,26 +112,30 @@ def __init__( self._work_dir: Path = work_dir # Start a container from the image, read to exec commands later - - pod = client.V1Pod( - metadata=client.V1ObjectMeta(name=pod_name,namespace=namespace), - spec=client.V1PodSpec( - restart_policy="Never", - containers=[client.V1Container( - args=["-c", "while true;do sleep 5; done"], - command=["/bin/sh"], - name="autogen-code-exec", - image=image - )] + if not pod_spec: + pod = client.V1Pod( + metadata=client.V1ObjectMeta(name=pod_name,namespace=namespace), + spec=client.V1PodSpec( + restart_policy="Never", + containers=[client.V1Container( + args=["-c", "while true;do sleep 5; done"], + command=["/bin/sh"], + name="autogen-code-exec", + image=image + )] + ) ) - ) + else: + pod = pod_spec - self._container = self._api_client.create_namespaced_pod(namespace=namespace, body=pod) + try: + self._container = self._api_client.create_namespaced_pod(namespace=namespace, body=pod) + except ApiException as e: + raise ValueError(f"Creating pod failed: {e}") self._wait_for_ready() def cleanup() -> None: - from kubernetes.client.rest import ApiException try: self._api_client.delete_namespaced_pod(pod_name, namespace) except ApiException: @@ -138,16 +151,23 @@ def cleanup() -> None: if execution_policies is not None: self.execution_policies.update(execution_policies) - def _wait_for_ready(self, timeout:int = 60, stop_time: float = 0.1) -> None: + def _wait_for_ready(self, stop_time: float = 0.1) -> None: elapsed_time = 0.0 name = self._container.metadata.name namespace = self._container.metadata.namespace while True: sleep(stop_time) elapsed_time += stop_time - pod_status = self._api_client.read_namespaced_pod_status(name, namespace) - if pod_status.status.phase == "Running": - break + if elapsed_time > self._timeout: + raise ValueError( + f"pod name {name} on namespace {namespace} is not Ready after timeout {self._timeout} seconds" + ) + try: + pod_status = self._api_client.read_namespaced_pod_status(name, namespace) + if pod_status.status.phase == "Running": + break + except ApiException as e: + raise ValueError(f"reading pod status failed: {e}") @property def timeout(self) -> int: From 3ee1af5f988c4a80c731ca1ed7b44dfbfd9b172e Mon Sep 17 00:00:00 2001 From: questcollector Date: Thu, 22 Aug 2024 13:04:25 +0900 Subject: [PATCH 04/16] change parameter name to kube_config_file --- .../coding/kubernetes/pod_commandline_code_executor.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/autogen/coding/kubernetes/pod_commandline_code_executor.py b/autogen/coding/kubernetes/pod_commandline_code_executor.py index 98796af09692..7dd9ca887bfa 100644 --- a/autogen/coding/kubernetes/pod_commandline_code_executor.py +++ b/autogen/coding/kubernetes/pod_commandline_code_executor.py @@ -50,7 +50,7 @@ def __init__( pod_spec: Optional[client.V1Pod] = None, timeout: int = 60, work_dir: Union[Path, str] = Path("/workspace"), - kubernetes_config_file: Optional[str] = None, + kube_config_file: Optional[str] = None, stop_container: bool = True, execution_policies: Optional[Dict[str, bool]] = None, ): @@ -77,7 +77,7 @@ def __init__( timeout (int, optional): The timeout for code execution. Defaults to 60. work_dir (Union[Path, str], optional): The working directory for the code execution. Defaults to Path("/workspace"). - kubernetes_config_file (Optional[str], optional): kubernetes configuration file path. + kube_config_file (Optional[str], optional): kubernetes configuration file path. If None, will use KUBECONFIG environment variables or service account token(incluster config) stop_container (bool, optional): If true, will automatically stop the container when stop is called, when the context manager exits or when @@ -87,10 +87,10 @@ def __init__( Raises: ValueError: On argument error, or if the container fails to start. """ - if kubernetes_config_file is None: + if kube_config_file is None: config.load_config() else: - config.load_config(config_file=kubernetes_config_file) + config.load_config(config_file=kube_config_file) self._api_client = client.CoreV1Api() From f0c2b6923e62565b7132f1ccde78a900ec33d25d Mon Sep 17 00:00:00 2001 From: questcollector Date: Thu, 22 Aug 2024 16:51:21 +0900 Subject: [PATCH 05/16] add param container_name --- .../pod_commandline_code_executor.py | 32 ++++++++++++------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/autogen/coding/kubernetes/pod_commandline_code_executor.py b/autogen/coding/kubernetes/pod_commandline_code_executor.py index 7dd9ca887bfa..e106b924dbf8 100644 --- a/autogen/coding/kubernetes/pod_commandline_code_executor.py +++ b/autogen/coding/kubernetes/pod_commandline_code_executor.py @@ -48,6 +48,7 @@ def __init__( pod_name: Optional[str] = None, namespace: Optional[str] = None, pod_spec: Optional[client.V1Pod] = None, + container_name: Optional[str] = "autogen-code-exec", timeout: int = 60, work_dir: Union[Path, str] = Path("/workspace"), kube_config_file: Optional[str] = None, @@ -72,8 +73,11 @@ def __init__( which is created. If None, will autogenerate a name. Defaults to None. namespace (Optional[str], optional): Namespace of kubernetes pod which is created. If None, will use current namespace of this instance - pod_spec (Optional[client.V1Pod], optional): Pod specification of kubernetes pod. + pod_spec (Optional[client.V1Pod], optional): Specification of kubernetes pod. + custom pod spec can be provided with this param. if pod_spec is provided, params above(image, pod_name, namespace) are neglected. + container_name (Optional[str], optional): Name of the container where code block will be + executed. if pod_spec param is provided, container_name must be provided also. timeout (int, optional): The timeout for code execution. Defaults to 60. work_dir (Union[Path, str], optional): The working directory for the code execution. Defaults to Path("/workspace"). @@ -106,13 +110,18 @@ def __init__( raise ValueError("Namespace where the pod will be launched must be provided") with open(namespace_path, "r") as f: namespace = f.read() + if container_name is None: + container_name = "autogen-code-exec" + self._container_name = container_name if isinstance(work_dir, str): work_dir = Path(work_dir) self._work_dir: Path = work_dir # Start a container from the image, read to exec commands later - if not pod_spec: + if pod_spec: + pod = pod_spec + else: pod = client.V1Pod( metadata=client.V1ObjectMeta(name=pod_name,namespace=namespace), spec=client.V1PodSpec( @@ -120,16 +129,15 @@ def __init__( containers=[client.V1Container( args=["-c", "while true;do sleep 5; done"], command=["/bin/sh"], - name="autogen-code-exec", + name=container_name, image=image )] ) ) - else: - pod = pod_spec try: - self._container = self._api_client.create_namespaced_pod(namespace=namespace, body=pod) + namespace = pod.metadata.namespace + self._pod = self._api_client.create_namespaced_pod(namespace=namespace, body=pod) except ApiException as e: raise ValueError(f"Creating pod failed: {e}") @@ -153,8 +161,8 @@ def cleanup() -> None: def _wait_for_ready(self, stop_time: float = 0.1) -> None: elapsed_time = 0.0 - name = self._container.metadata.name - namespace = self._container.metadata.namespace + name = self._pod.metadata.name + namespace = self._pod.metadata.namespace while True: sleep(stop_time) elapsed_time += stop_time @@ -236,9 +244,9 @@ def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CommandLineCodeRe ) exec_script = exec_script.format(workspace=str(self._work_dir), code_path=code_path, code=code) stream(self._api_client.connect_get_namespaced_pod_exec, - self._container.metadata.name, self._container.metadata.namespace, + self._pod.metadata.name, self._pod.metadata.namespace, command=["/bin/sh", "-c", exec_script], - container="autogen-code-exec", + container=self._container_name, stderr=True, stdin=False, stdout=True, tty=False) files.append(code_path) @@ -248,9 +256,9 @@ def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CommandLineCodeRe continue resp = stream(self._api_client.connect_get_namespaced_pod_exec, - self._container.metadata.name, self._container.metadata.namespace, + self._pod.metadata.name, self._pod.metadata.namespace, command=["timeout", str(self._timeout), _cmd(lang), str(code_path)], - container="autogen-code-exec", + container=self._container_name, stderr=True, stdin=False, stdout=True, tty=False, _preload_content=False) stdout_messages = [] From 0d906834028de194a1f9c4104fba60ed0ff7fe4b Mon Sep 17 00:00:00 2001 From: questcollector Date: Fri, 23 Aug 2024 17:50:36 +0900 Subject: [PATCH 06/16] add test case for PodCommandLineCodeExecutor --- .../pod_commandline_code_executor.py | 28 +-- ...st_kubernetes_commandline_code_executor.py | 198 ++++++++++++++++++ 2 files changed, 213 insertions(+), 13 deletions(-) create mode 100644 test/coding/test_kubernetes_commandline_code_executor.py diff --git a/autogen/coding/kubernetes/pod_commandline_code_executor.py b/autogen/coding/kubernetes/pod_commandline_code_executor.py index e106b924dbf8..7310dc79d127 100644 --- a/autogen/coding/kubernetes/pod_commandline_code_executor.py +++ b/autogen/coding/kubernetes/pod_commandline_code_executor.py @@ -101,27 +101,28 @@ def __init__( if timeout < 1: raise ValueError("Timeout must be greater than or equal to 1.") self._timeout = timeout - - if pod_name is None: - pod_name = f"autogen-code-exec-{uuid.uuid4()}" - if namespace is None: - namespace_path = "/var/run/secrets/kubernetes.io/serviceaccount/namespace" - if not Path(namespace_path).is_file(): - raise ValueError("Namespace where the pod will be launched must be provided") - with open(namespace_path, "r") as f: - namespace = f.read() - if container_name is None: - container_name = "autogen-code-exec" - self._container_name = container_name if isinstance(work_dir, str): work_dir = Path(work_dir) self._work_dir: Path = work_dir + + if container_name is None: + container_name = "autogen-code-exec" + self._container_name = container_name # Start a container from the image, read to exec commands later if pod_spec: pod = pod_spec else: + if pod_name is None: + pod_name = f"autogen-code-exec-{uuid.uuid4()}" + if namespace is None: + namespace_path = "/var/run/secrets/kubernetes.io/serviceaccount/namespace" + if not Path(namespace_path).is_file(): + raise ValueError("Namespace where the pod will be launched must be provided") + with open(namespace_path, "r") as f: + namespace = f.read() + pod = client.V1Pod( metadata=client.V1ObjectMeta(name=pod_name,namespace=namespace), spec=client.V1PodSpec( @@ -136,6 +137,7 @@ def __init__( ) try: + pod_name = pod.metadata.name namespace = pod.metadata.namespace self._pod = self._api_client.create_namespaced_pod(namespace=namespace, body=pod) except ApiException as e: @@ -269,7 +271,7 @@ def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CommandLineCodeRe stderr_messages.append(resp.read_stderr()) if resp.peek_stdout(): stdout_messages.append(resp.read_stdout()) - outputs = stdout_messages + stderr_messages + outputs.extend(stdout_messages + stderr_messages) exit_code = resp.returncode resp.close() diff --git a/test/coding/test_kubernetes_commandline_code_executor.py b/test/coding/test_kubernetes_commandline_code_executor.py new file mode 100644 index 000000000000..a002e56995e8 --- /dev/null +++ b/test/coding/test_kubernetes_commandline_code_executor.py @@ -0,0 +1,198 @@ +import os +import sys +from pathlib import Path + +import pytest +from kubernetes import client, config +from kubernetes.client.rest import ApiException + +from autogen.coding.base import CodeBlock, CodeExecutor +from autogen.code_utils import TIMEOUT_MSG + +try: + from autogen.coding.kubernetes import PodCommandLineCodeExecutor + + kubeconfig = Path(".kube/config") + if os.environ.get('KUBECONFIG', None): + kubeconfig = Path(os.environ["KUBECONFIG"]) + elif sys.platform == 'win32': + kubeconfig = os.environ["userprofile"] / kubeconfig + else: + kubeconfig = os.environ["HOME"] / kubeconfig + + if kubeconfig.is_file(): + config.load_config(config_file=str(kubeconfig)) + api_client = client.CoreV1Api() + api_client.list_namespace() + skip_kubernetes_tests = False + else: + skip_kubernetes_tests = True +except: + skip_kubernetes_tests = True + + +pod_spec = client.V1Pod( + metadata=client.V1ObjectMeta(name="abcd",namespace="default", annotations={"sidecar.istio.io/inject": "false"}), + spec=client.V1PodSpec( + restart_policy="Never", + containers=[client.V1Container( + args=["-c", "while true;do sleep 5; done"], + command=["/bin/sh"], + name="abcd", + image="python:3.11-slim", + env=[client.V1EnvVar( + name="TEST", + value="TEST" + ), + client.V1EnvVar( + name="POD_NAME", + value_from=client.V1EnvVarSource( + field_ref=client.V1ObjectFieldSelector( + field_path="metadata.name" + ) + ) + )] + )], + ) +) + +@pytest.mark.skipif(skip_kubernetes_tests, reason="kubernetes not accessible") +def test_create_default_pod_executor(): + with PodCommandLineCodeExecutor(namespace="default", kube_config_file=str(kubeconfig)) as executor: + assert executor.timeout == 60 + assert executor.work_dir == Path("/workspace") + assert executor._container_name == "autogen-code-exec" + assert executor._pod.metadata.name.startswith("autogen-code-exec-") + _test_execute_code(executor) + +@pytest.mark.skipif(skip_kubernetes_tests, reason="kubernetes not accessible") +def test_create_node_pod_executor(): + with PodCommandLineCodeExecutor(image="node:22-alpine", + namespace="default", + work_dir="./app", + timeout=30, + kube_config_file=str(kubeconfig), + execution_policies={"javascript": True} + ) as executor: + assert executor.timeout == 30 + assert executor.work_dir == Path("./app") + assert executor._container_name == "autogen-code-exec" + assert executor._pod.metadata.name.startswith("autogen-code-exec-") + assert executor.execution_policies["javascript"] + + # Test single code block. + code_blocks = [CodeBlock(code="console.log('hello world!')", language="javascript")] + code_result = executor.execute_code_blocks(code_blocks) + assert code_result.exit_code == 0 and "hello world!" in code_result.output and code_result.code_file is not None + + # Test multiple code blocks. + code_blocks = [ + CodeBlock(code="console.log('hello world!')", language="javascript"), + CodeBlock(code="let a = 100 + 100; console.log(a)", language="javascript"), + ] + code_result = executor.execute_code_blocks(code_blocks) + assert ( + code_result.exit_code == 0 + and "hello world!" in code_result.output + and "200" in code_result.output + and code_result.code_file is not None + ) + + # Test running code. + file_lines = ["console.log('hello world!')", "let a = 100 + 100", "console.log(a)"] + code_blocks = [CodeBlock(code="\n".join(file_lines), language="javascript")] + code_result = executor.execute_code_blocks(code_blocks) + assert ( + code_result.exit_code == 0 + and "hello world!" in code_result.output + and "200" in code_result.output + and code_result.code_file is not None + ) + + + +@pytest.mark.skipif(skip_kubernetes_tests, reason="kubernetes not accessible") +def test_create_pod_spec_pod_executor(): + with PodCommandLineCodeExecutor(pod_spec=pod_spec, container_name="abcd", kube_config_file=str(kubeconfig)) as executor: + assert executor.timeout == 60 + assert executor._container_name == "abcd" + assert executor._pod.metadata.name == pod_spec.metadata.name + assert executor._pod.metadata.namespace == pod_spec.metadata.namespace + _test_execute_code(executor) + + # Test bash script. + if sys.platform not in ["win32"]: + code_blocks = [CodeBlock(code="echo $TEST $POD_NAME", language="bash")] + code_result = executor.execute_code_blocks(code_blocks) + assert code_result.exit_code == 0 and "TEST abcd" in code_result.output and code_result.code_file is not None + +@pytest.mark.skipif(skip_kubernetes_tests, reason="kubernetes not accessible") +def test_pod_executor_timeout(): + with PodCommandLineCodeExecutor(namespace="default", timeout=5, kube_config_file=str(kubeconfig)) as executor: + assert executor.timeout == 5 + assert executor.work_dir == Path("/workspace") + assert executor._container_name == "autogen-code-exec" + assert executor._pod.metadata.name.startswith("autogen-code-exec-") + # Test running code. + file_lines = ["import time", "time.sleep(10)", "a = 100 + 100", "print(a)"] + code_blocks = [CodeBlock(code="\n".join(file_lines), language="python")] + code_result = executor.execute_code_blocks(code_blocks) + assert ( + code_result.exit_code == 124 + and TIMEOUT_MSG in code_result.output + and code_result.code_file is not None + ) + + +def _test_execute_code(executor: CodeExecutor) -> None: + # Test single code block. + code_blocks = [CodeBlock(code="import sys; print('hello world!')", language="python")] + code_result = executor.execute_code_blocks(code_blocks) + assert code_result.exit_code == 0 and "hello world!" in code_result.output and code_result.code_file is not None + + # Test multiple code blocks. + code_blocks = [ + CodeBlock(code="import sys; print('hello world!')", language="python"), + CodeBlock(code="a = 100 + 100; print(a)", language="python"), + ] + code_result = executor.execute_code_blocks(code_blocks) + assert ( + code_result.exit_code == 0 + and "hello world!" in code_result.output + and "200" in code_result.output + and code_result.code_file is not None + ) + + # Test bash script. + if sys.platform not in ["win32"]: + code_blocks = [CodeBlock(code="echo 'hello world!'", language="bash")] + code_result = executor.execute_code_blocks(code_blocks) + assert code_result.exit_code == 0 and "hello world!" in code_result.output and code_result.code_file is not None + + # Test running code. + file_lines = ["import sys", "print('hello world!')", "a = 100 + 100", "print(a)"] + code_blocks = [CodeBlock(code="\n".join(file_lines), language="python")] + code_result = executor.execute_code_blocks(code_blocks) + assert ( + code_result.exit_code == 0 + and "hello world!" in code_result.output + and "200" in code_result.output + and code_result.code_file is not None + ) + + # Test running code has filename. + file_lines = ["# filename: test.py", "import sys", "print('hello world!')", "a = 100 + 100", "print(a)"] + code_blocks = [CodeBlock(code="\n".join(file_lines), language="python")] + code_result = executor.execute_code_blocks(code_blocks) + print(code_result.code_file) + assert ( + code_result.exit_code == 0 + and "hello world!" in code_result.output + and "200" in code_result.output + and code_result.code_file.find("test.py") > 0 + ) + + #Test error code. + code_blocks = [CodeBlock(code="print(sys.platform)", language="python")] + code_result = executor.execute_code_blocks(code_blocks) + assert code_result.exit_code == 1 and "Traceback" in code_result.output and code_result.code_file is not None From 2aa11d21539ec820ebc2604f89363cfe7e719316 Mon Sep 17 00:00:00 2001 From: questcollector Date: Fri, 23 Aug 2024 18:10:51 +0900 Subject: [PATCH 07/16] add test guide --- ...st_kubernetes.commandline_code_executor.md | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 test/coding/test_kubernetes.commandline_code_executor.md diff --git a/test/coding/test_kubernetes.commandline_code_executor.md b/test/coding/test_kubernetes.commandline_code_executor.md new file mode 100644 index 000000000000..cc61003094a1 --- /dev/null +++ b/test/coding/test_kubernetes.commandline_code_executor.md @@ -0,0 +1,44 @@ +# Test Environment for autogen.coding.kubernetes.PodCommandLineCodeExecutor + +To test PodCommandLineCodeExecutor, the following environment is required. +- kubernetes cluster config file +- autogen package + +## kubernetes cluster config file + +kubernetes cluster config file, kubeconfig file's location should be set on environment variable `KUBECONFIG` or +It must be located in the .kube/config path of your home directory. + +For Windows, `C:\Users\<>\.kube\config`, +For Linux or MacOS, place the kubeconfig file in the `/home/<>/.kube/config` directory. + +## package install + +Clone autogen github repository for package install and testing + +Clone the repository with the command below. + +before contribution +```sh +git clone -b k8s-code-executor https://github.com/questcollector/autogen.git +``` + +after contribution +```sh +git clone https://github.com/microsoft/autogen.git +``` + +install autogen with kubernetes >= 27.0.2 + +```sh +cd autogen +pip install .[kubernetes] -U +``` + +## test execution + +Perform the test with the following command + +```sh +pytest test/coding/test_kubernetes_commandline_code_executor.py +``` \ No newline at end of file From 643ecfa382b876e1763b687a29a33acbcb5a1c06 Mon Sep 17 00:00:00 2001 From: questcollector Date: Fri, 23 Aug 2024 18:42:06 +0900 Subject: [PATCH 08/16] draft for docs notebook --- ...rnetes-pod-commandline-code-executor.ipynb | 231 ++++++++++++++++++ 1 file changed, 231 insertions(+) create mode 100644 website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb diff --git a/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb new file mode 100644 index 000000000000..8506365c7547 --- /dev/null +++ b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb @@ -0,0 +1,231 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Kubernetes Pod Commandline Code Executor\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%pip -qqq install pyautogen[kubernetes]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from autogen.coding.kubernetes import PodCommandLineCodeExecutor\n", + "from autogen.coding import CodeBlock" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from pathlib import Path\n", + "import sys\n", + "import os\n", + "\n", + "kubeconfig = Path('.kube/config')\n", + "\n", + "if os.environ.get('KUBECONFIG', None):\n", + " kubeconfig = os.environ[\"KUBECONFIG\"]\n", + "elif sys.platform == \"win32\":\n", + " kubeconfig = os.environ[\"userprofile\"] / kubeconfig\n", + "else:\n", + " kubeconfig = os.environ[\"HOME\"] / kubeconfig" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "with PodCommandLineCodeExecutor(namespace=\"default\", kube_config_file=kubeconfig) as executor:\n", + " print(\n", + " executor.execute_code_blocks(\n", + " code_blocks=[\n", + " CodeBlock(language=\"python\", code=\"print('Hello, World!')\"),\n", + " ]\n", + " )\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "with PodCommandLineCodeExecutor(\n", + " image=\"node:22-alpine\",\n", + " namespace=\"default\",\n", + " work_dir=\"./app\",\n", + " timeout=10,\n", + " kube_config_file=kubeconfig,\n", + " execution_policies = {\"javascript\": True}\n", + ") as executor:\n", + " print(\n", + " executor.execute_code_blocks(\n", + " code_blocks=[\n", + " CodeBlock(language=\"javascript\", code=\"console.log('Hello, World!')\"),\n", + " ]\n", + " )\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from kubernetes import client\n", + "\n", + "pod = client.V1Pod(\n", + " metadata=client.V1ObjectMeta(name=\"abcd\", namespace=\"default\", \n", + " annotations={\"sidecar.istio.io/inject\": \"false\"}),\n", + " spec=client.V1PodSpec(\n", + " restart_policy=\"Never\",\n", + " containers=[client.V1Container(\n", + " args=[\"-c\", \"while true;do sleep 5; done\"],\n", + " command=[\"/bin/sh\"],\n", + " name=\"abcd\",\n", + " image=\"python:3.11-slim\",\n", + " env=[\n", + " client.V1EnvVar(\n", + " name=\"TEST\",\n", + " value=\"TEST\"\n", + " ),\n", + " client.V1EnvVar(\n", + " name=\"POD_NAME\",\n", + " value_from=client.V1EnvVarSource(\n", + " field_ref=client.V1ObjectFieldSelector(\n", + " field_path=\"metadata.name\"\n", + " )\n", + " )\n", + " )\n", + " ]\n", + " )],\n", + " )\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "with PodCommandLineCodeExecutor(\n", + " pod_spec=pod,\n", + " container_name=\"abcd\",\n", + " work_dir=\"/autogen\",\n", + " timeout=60,\n", + " kube_config_file=kubeconfig,\n", + ") as executor:\n", + " print(\n", + " executor.execute_code_blocks(\n", + " code_blocks=[\n", + " CodeBlock(language=\"python\", code=\"print('Hello, World!')\"),\n", + " ]\n", + " )\n", + " )\n", + " print(\n", + " executor.execute_code_blocks(\n", + " code_blocks=[\n", + " CodeBlock(code=\"echo $TEST $POD_NAME\", language=\"bash\"),\n", + " ]\n", + " )\n", + " )\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "config_list = []" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from autogen import ConversableAgent\n", + "\n", + "# The code writer agent's system message is to instruct the LLM on how to\n", + "# use the Jupyter code executor with IPython kernel.\n", + "code_writer_system_message = \"\"\"\n", + "You have been given coding capability to solve tasks using Python code.\n", + "In the following cases, suggest python code (in a python coding block) or shell script (in a sh coding block) for the user to execute.\n", + " 1. When you need to collect info, use the code to output the info you need, for example, browse or search the web, download/read a file, print the content of a webpage or a file, get the current date/time, check the operating system. After sufficient info is printed and the task is ready to be solved based on your language skill, you can solve the task by yourself.\n", + " 2. When you need to perform some task with code, use the code to perform the task and output the result. Finish the task smartly.\n", + "Solve the task step by step if you need to. If a plan is not provided, explain your plan first. Be clear which step uses code, and which step uses your language skill.\n", + "When using code, you must indicate the script type in the code block. The user cannot provide any other feedback or perform any other action beyond executing the code you suggest. The user can't modify your code. So do not suggest incomplete code which requires users to modify. Don't use a code block if it's not intended to be executed by the user.\n", + "If you want the user to save the code in a file before executing it, put # filename: inside the code block as the first line. Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user.\n", + "\"\"\"\n", + "with PodCommandLineCodeExecutor(namespace=\"default\", kube_config_file=kubeconfig) as executor:\n", + " \n", + " code_executor_agent = ConversableAgent(\n", + " name=\"code_executor_agent\",\n", + " llm_config=False,\n", + " code_execution_config={\n", + " \"executor\": executor,\n", + " },\n", + " human_input_mode=\"NEVER\",\n", + " )\n", + "\n", + " code_writer_agent = ConversableAgent(\n", + " \"code_writer\",\n", + " system_message=code_writer_system_message,\n", + " llm_config={\"config_list\": config_list},\n", + " code_execution_config=False, # Turn off code execution for this agent.\n", + " max_consecutive_auto_reply=2,\n", + " human_input_mode=\"NEVER\",\n", + " )\n", + "\n", + " chat_result = code_executor_agent.initiate_chat(\n", + " code_writer_agent, message=\"Write Python code to calculate the 14th Fibonacci number.\"\n", + " )" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "autogen", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.12" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} From 3b3c0232d260825599746530b2ffe3aee7b4aa93 Mon Sep 17 00:00:00 2001 From: questcollector Date: Fri, 23 Aug 2024 18:44:01 +0900 Subject: [PATCH 09/16] test code fix indent --- ...st_kubernetes_commandline_code_executor.py | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/test/coding/test_kubernetes_commandline_code_executor.py b/test/coding/test_kubernetes_commandline_code_executor.py index a002e56995e8..f7555cc67620 100644 --- a/test/coding/test_kubernetes_commandline_code_executor.py +++ b/test/coding/test_kubernetes_commandline_code_executor.py @@ -40,18 +40,20 @@ command=["/bin/sh"], name="abcd", image="python:3.11-slim", - env=[client.V1EnvVar( - name="TEST", - value="TEST" - ), - client.V1EnvVar( - name="POD_NAME", - value_from=client.V1EnvVarSource( - field_ref=client.V1ObjectFieldSelector( - field_path="metadata.name" + env=[ + client.V1EnvVar( + name="TEST", + value="TEST" + ), + client.V1EnvVar( + name="POD_NAME", + value_from=client.V1EnvVarSource( + field_ref=client.V1ObjectFieldSelector( + field_path="metadata.name" + ) ) ) - )] + ] )], ) ) From 1c4fa6b5a7a788b631df632e8b9dfa144b93f5d2 Mon Sep 17 00:00:00 2001 From: questcollector Date: Mon, 26 Aug 2024 16:51:38 +0900 Subject: [PATCH 10/16] add document --- ...rnetes-pod-commandline-code-executor.ipynb | 601 ++++++++++++++++-- 1 file changed, 560 insertions(+), 41 deletions(-) diff --git a/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb index 8506365c7547..e8b68d934717 100644 --- a/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb +++ b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb @@ -4,8 +4,61 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Kubernetes Pod Commandline Code Executor\n", - "\n" + "# Kubernetes Pod Commandline Code Executor" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `PodCommandLineCodeExecutor` of the autogen.coding.kubernetes module is to execute a code block using a pod in Kubernetes.\n", + "It is like DockerCommandLineCodeExecutor, but creates container on kubernetes Pod.\n", + "\n", + "There are two condition to use PodCommandLineCodeExecutor.\n", + "- accessible to kubernetes cluster\n", + "- install autogen with extra feature kubernetes\n", + "\n", + "This documents uses minikube cluster on local environment.\n", + "You can refer to the link below for installation and execution of minikube.\n", + "\n", + "https://minikube.sigs.k8s.io/docs/start/" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Access kubernetes cluster" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are four options PodCommandLineCodeExecutor to access kubernetes API server.\n", + "- default kubeconfig file path: `~/.kube/config`\n", + "- To provide kubeconfig file path to `kube_config_file` argument of `PodCommandLineCodeExecutor`.\n", + "- To provide kubeconfig file path to `KUBECONFIG` environment variable.\n", + "- To provide token from kubernetes ServiceAccount which has enough permissions" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Generally, if kubeconfig file is located in `~/.kube/config`, there's no need to provide kubeconfig file path on parameter or environment variables.\n", + "\n", + "the Tutorial of providing ServiceAccount Token is in the last section" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example\n", + "\n", + "In order to use kubernetes Pod based code executor, kubernetes python sdk is required.\n", + "It can be installed by `pip install 'kubernetes>=27'` or with the extra kubernetes" ] }, { @@ -14,7 +67,16 @@ "metadata": {}, "outputs": [], "source": [ - "%pip -qqq install pyautogen[kubernetes]" + "%pip install 'pyautogen[kubernetes]'\n", + "# or\n", + "# pip install pyautogen 'kubernetes>=27'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To provide kubeconfig file path with environment variable, It can be added with `os.environ[\"KUBECONFIG\"]`" ] }, { @@ -23,37 +85,40 @@ "metadata": {}, "outputs": [], "source": [ - "from autogen.coding.kubernetes import PodCommandLineCodeExecutor\n", - "from autogen.coding import CodeBlock" + "# import os\n", + "# # If kubeconfig file is not located on ~/.kube/config but other path, \n", + "# # you can set path of kubeconfig file on KUBECONFIG environment variables \n", + "# os.environ[\"KUBECONFIG\"] = \"kubeconfig/file/path\"" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "metadata": {}, "outputs": [], "source": [ - "from pathlib import Path\n", - "import sys\n", - "import os\n", - "\n", - "kubeconfig = Path('.kube/config')\n", - "\n", - "if os.environ.get('KUBECONFIG', None):\n", - " kubeconfig = os.environ[\"KUBECONFIG\"]\n", - "elif sys.platform == \"win32\":\n", - " kubeconfig = os.environ[\"userprofile\"] / kubeconfig\n", - "else:\n", - " kubeconfig = os.environ[\"HOME\"] / kubeconfig" + "from autogen.coding.kubernetes import PodCommandLineCodeExecutor\n", + "from autogen.coding import CodeBlock" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "exit_code=0 output='Hello, World!\\n' code_file='/workspace/tmp_code_07da107bb575cc4e02b0e1d6d99cc204.py'\n" + ] + } + ], "source": [ - "with PodCommandLineCodeExecutor(namespace=\"default\", kube_config_file=kubeconfig) as executor:\n", + "with PodCommandLineCodeExecutor(\n", + " namespace=\"default\",\n", + " # kube_config_file=\"kubeconfig/file/path\" # If you have another kubeconfig file, you can add it on kube_config_file argument\n", + " ) as executor:\n", " print(\n", " executor.execute_code_blocks(\n", " code_blocks=[\n", @@ -63,19 +128,103 @@ " )" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "With context manager(with statement), the pod created by PodCommandLineCodeExecutor deleted automatically after tasks done.\n", + "\n", + "To delete the pod manually, you can use `stop()` method" + ] + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "executor = PodCommandLineCodeExecutor(namespace=\"default\")" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "NAME READY STATUS RESTARTS AGE\n", + "autogen-code-exec-afd217ac-f77b-4ede-8c53-1297eca5ec64 1/1 Running 0 10m\n" + ] + } + ], + "source": [ + "%%bash\n", + "# default pod name is autogen-code-exec-{uuid.uuid4()}\n", + "kubectl get pod -n default" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "python:3-slim" + ] + } + ], + "source": [ + "%%bash\n", + "# default container image is python:3-slim\n", + "kubectl get pod autogen-code-exec-afd217ac-f77b-4ede-8c53-1297eca5ec64 -o jsonpath={.spec.containers[0].image}" + ] + }, + { + "cell_type": "code", + "execution_count": 12, "metadata": {}, "outputs": [], + "source": [ + "executor.stop()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you use another container image for code executor pod, you can provide image tag to `image` argument.\n", + "\n", + "PodCommandLineCode Executor has default execution policy that allows python and shell script code blocks.\n", + "\n", + "It can be allowed other languages with `execution_policies` argument." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "exit_code=0 output='Hello, World!\\n' code_file='app/tmp_code_8c34c8586cb47943728afe1297b7a51c.js'\n" + ] + } + ], "source": [ "with PodCommandLineCodeExecutor(\n", - " image=\"node:22-alpine\",\n", + " image=\"node:22-alpine\", # you can provide runtime environments through container image\n", " namespace=\"default\",\n", - " work_dir=\"./app\",\n", - " timeout=10,\n", - " kube_config_file=kubeconfig,\n", - " execution_policies = {\"javascript\": True}\n", + " work_dir=\"./app\", # workspace directory for code block files\n", + " timeout=10, # timeout(seconds) value for waiting pod creation, execution of code blocks. default is 60 seconds\n", + " execution_policies = {\"javascript\": True} # allowed execution languages can be updated with execution_policy dictionary\n", ") as executor:\n", " print(\n", " executor.execute_code_blocks(\n", @@ -86,9 +235,19 @@ " )" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you want to give custom settings for executor pod, such as annotations, environment variables, commands, volumes etc., \n", + "you can provide custom pod specification with `kubernetes.client.V1Pod` format.\n", + "\n", + "`container_name` argument should also be provided because PodCommandLineCodeExecutor do not automatically recognize a container where code blocks will be executed " + ] + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, "metadata": {}, "outputs": [], "source": [ @@ -102,7 +261,7 @@ " containers=[client.V1Container(\n", " args=[\"-c\", \"while true;do sleep 5; done\"],\n", " command=[\"/bin/sh\"],\n", - " name=\"abcd\",\n", + " name=\"abcd\", # container name where code blocks will be executed should be provided to `container_name` argument\n", " image=\"python:3.11-slim\",\n", " env=[\n", " client.V1EnvVar(\n", @@ -125,16 +284,24 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "exit_code=0 output='Hello, World!\\n' code_file='/autogen/tmp_code_07da107bb575cc4e02b0e1d6d99cc204.py'\n", + "exit_code=0 output='TEST abcd\\n' code_file='/autogen/tmp_code_202399627ea7fb8d8e816f4910b7f87b.sh'\n" + ] + } + ], "source": [ "with PodCommandLineCodeExecutor(\n", - " pod_spec=pod,\n", - " container_name=\"abcd\",\n", + " pod_spec=pod, # custom executor pod spec\n", + " container_name=\"abcd\", # If custom executor pod spec is provided, container_name where code block will be executed should be specified\n", " work_dir=\"/autogen\",\n", " timeout=60,\n", - " kube_config_file=kubeconfig,\n", ") as executor:\n", " print(\n", " executor.execute_code_blocks(\n", @@ -146,27 +313,116 @@ " print(\n", " executor.execute_code_blocks(\n", " code_blocks=[\n", - " CodeBlock(code=\"echo $TEST $POD_NAME\", language=\"bash\"),\n", + " CodeBlock(code=\"echo $TEST $POD_NAME\", language=\"bash\"), # echo environment variables specified in pod_spec\n", " ]\n", " )\n", " )\n", " " ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Integrates with AutoGen Agents" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "PodCommandLineCodeExecutor can be integrated with Agents." + ] + }, { "cell_type": "code", - "execution_count": null, + "execution_count": 19, "metadata": {}, "outputs": [], "source": [ - "config_list = []" + "from autogen import config_list_from_json\n", + "config_list = config_list_from_json(\n", + " env_or_file=\"OAI_CONFIG_LIST\",\n", + ")" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 20, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\u001b[33mcode_executor_agent\u001b[0m (to code_writer):\n", + "\n", + "Write Python code to calculate the moves of disk on tower of hanoi with 3 disks\n", + "\n", + "--------------------------------------------------------------------------------\n", + "\u001b[33mcode_writer\u001b[0m (to code_executor_agent):\n", + "\n", + "The problem of the Tower of Hanoi with 3 disks involves moving the disks from one peg to another, following these rules:\n", + "1. Only one disk can be moved at a time.\n", + "2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty peg.\n", + "3. No disk may be placed on top of a smaller disk.\n", + "\n", + "In the solution, I will use a recursive function to calculate the moves and print them out. Here's the Python code to accomplish this:\n", + "\n", + "```python\n", + "def tower_of_hanoi(n, from_rod, to_rod, aux_rod):\n", + " if n == 1:\n", + " print(f\"Move disk 1 from rod {from_rod} to rod {to_rod}\")\n", + " return\n", + " tower_of_hanoi(n-1, from_rod, aux_rod, to_rod)\n", + " print(f\"Move disk {n} from rod {from_rod} to rod {to_rod}\")\n", + " tower_of_hanoi(n-1, aux_rod, to_rod, from_rod)\n", + "\n", + "n = 3 # Number of disks\n", + "tower_of_hanoi(n, 'A', 'C', 'B') # A, B and C are names of the rods\n", + "```\n", + "\n", + "This script defines a function `tower_of_hanoi` that will print out each move necessary to solve the Tower of Hanoi problem with the specified number of disks `n`. This specific setup will solve for 3 disks moving from rod 'A' to rod 'C' with the help of rod 'B'.\n", + "\n", + "--------------------------------------------------------------------------------\n", + "\u001b[31m\n", + ">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001b[0m\n", + "\u001b[33mcode_executor_agent\u001b[0m (to code_writer):\n", + "\n", + "exitcode: 0 (execution succeeded)\n", + "Code output: Move disk 1 from rod A to rod C\n", + "Move disk 2 from rod A to rod B\n", + "Move disk 1 from rod C to rod B\n", + "Move disk 3 from rod A to rod C\n", + "Move disk 1 from rod B to rod A\n", + "Move disk 2 from rod B to rod C\n", + "Move disk 1 from rod A to rod C\n", + "\n", + "\n", + "--------------------------------------------------------------------------------\n", + "\u001b[33mcode_writer\u001b[0m (to code_executor_agent):\n", + "\n", + "The execution of the provided code successfully calculated and printed the moves for solving the Tower of Hanoi with 3 disks. Here are the steps it performed:\n", + "\n", + "1. Move disk 1 from rod A to rod C.\n", + "2. Move disk 2 from rod A to rod B.\n", + "3. Move disk 1 from rod C to rod B.\n", + "4. Move disk 3 from rod A to rod C.\n", + "5. Move disk 1 from rod B to rod A.\n", + "6. Move disk 2 from rod B to rod C.\n", + "7. Move disk 1 from rod A to rod C.\n", + "\n", + "This sequence effectively transfers all disks from rod A to rod C using rod B as an auxiliary, following the rules of the Tower of Hanoi puzzle. If you have any more tasks or need further explanation, feel free to ask!\n", + "\n", + "--------------------------------------------------------------------------------\n", + "\u001b[33mcode_executor_agent\u001b[0m (to code_writer):\n", + "\n", + "\n", + "\n", + "--------------------------------------------------------------------------------\n" + ] + } + ], "source": [ "from autogen import ConversableAgent\n", "\n", @@ -181,7 +437,7 @@ "When using code, you must indicate the script type in the code block. The user cannot provide any other feedback or perform any other action beyond executing the code you suggest. The user can't modify your code. So do not suggest incomplete code which requires users to modify. Don't use a code block if it's not intended to be executed by the user.\n", "If you want the user to save the code in a file before executing it, put # filename: inside the code block as the first line. Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user.\n", "\"\"\"\n", - "with PodCommandLineCodeExecutor(namespace=\"default\", kube_config_file=kubeconfig) as executor:\n", + "with PodCommandLineCodeExecutor(namespace=\"default\") as executor:\n", " \n", " code_executor_agent = ConversableAgent(\n", " name=\"code_executor_agent\",\n", @@ -202,7 +458,270 @@ " )\n", "\n", " chat_result = code_executor_agent.initiate_chat(\n", - " code_writer_agent, message=\"Write Python code to calculate the 14th Fibonacci number.\"\n", + " code_writer_agent, message=\"Write Python code to calculate the moves of disk on tower of hanoi with 10 disks\"\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "93802984-3207-430b-a205-82f0a77df2b2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ChatResult(chat_id=None,\n", + " chat_history=[{'content': 'Write Python code to calculate the moves '\n", + " 'of disk on tower of hanoi with 3 disks',\n", + " 'name': 'code_executor_agent',\n", + " 'role': 'assistant'},\n", + " {'content': 'The problem of the Tower of Hanoi with 3 '\n", + " 'disks involves moving the disks from one '\n", + " 'peg to another, following these rules:\\n'\n", + " '1. Only one disk can be moved at a '\n", + " 'time.\\n'\n", + " '2. Each move consists of taking the '\n", + " 'upper disk from one of the stacks and '\n", + " 'placing it on top of another stack or on '\n", + " 'an empty peg.\\n'\n", + " '3. No disk may be placed on top of a '\n", + " 'smaller disk.\\n'\n", + " '\\n'\n", + " 'In the solution, I will use a recursive '\n", + " 'function to calculate the moves and '\n", + " \"print them out. Here's the Python code \"\n", + " 'to accomplish this:\\n'\n", + " '\\n'\n", + " '```python\\n'\n", + " 'def tower_of_hanoi(n, from_rod, to_rod, '\n", + " 'aux_rod):\\n'\n", + " ' if n == 1:\\n'\n", + " ' print(f\"Move disk 1 from rod '\n", + " '{from_rod} to rod {to_rod}\")\\n'\n", + " ' return\\n'\n", + " ' tower_of_hanoi(n-1, from_rod, '\n", + " 'aux_rod, to_rod)\\n'\n", + " ' print(f\"Move disk {n} from rod '\n", + " '{from_rod} to rod {to_rod}\")\\n'\n", + " ' tower_of_hanoi(n-1, aux_rod, to_rod, '\n", + " 'from_rod)\\n'\n", + " '\\n'\n", + " 'n = 3 # Number of disks\\n'\n", + " \"tower_of_hanoi(n, 'A', 'C', 'B') # A, B \"\n", + " 'and C are names of the rods\\n'\n", + " '```\\n'\n", + " '\\n'\n", + " 'This script defines a function '\n", + " '`tower_of_hanoi` that will print out '\n", + " 'each move necessary to solve the Tower '\n", + " 'of Hanoi problem with the specified '\n", + " 'number of disks `n`. This specific setup '\n", + " 'will solve for 3 disks moving from rod '\n", + " \"'A' to rod 'C' with the help of rod 'B'.\",\n", + " 'name': 'code_writer',\n", + " 'role': 'user'},\n", + " {'content': 'exitcode: 0 (execution succeeded)\\n'\n", + " 'Code output: Move disk 1 from rod A to '\n", + " 'rod C\\n'\n", + " 'Move disk 2 from rod A to rod B\\n'\n", + " 'Move disk 1 from rod C to rod B\\n'\n", + " 'Move disk 3 from rod A to rod C\\n'\n", + " 'Move disk 1 from rod B to rod A\\n'\n", + " 'Move disk 2 from rod B to rod C\\n'\n", + " 'Move disk 1 from rod A to rod C\\n',\n", + " 'name': 'code_executor_agent',\n", + " 'role': 'assistant'},\n", + " {'content': 'The execution of the provided code '\n", + " 'successfully calculated and printed the '\n", + " 'moves for solving the Tower of Hanoi '\n", + " 'with 3 disks. Here are the steps it '\n", + " 'performed:\\n'\n", + " '\\n'\n", + " '1. Move disk 1 from rod A to rod C.\\n'\n", + " '2. Move disk 2 from rod A to rod B.\\n'\n", + " '3. Move disk 1 from rod C to rod B.\\n'\n", + " '4. Move disk 3 from rod A to rod C.\\n'\n", + " '5. Move disk 1 from rod B to rod A.\\n'\n", + " '6. Move disk 2 from rod B to rod C.\\n'\n", + " '7. Move disk 1 from rod A to rod C.\\n'\n", + " '\\n'\n", + " 'This sequence effectively transfers all '\n", + " 'disks from rod A to rod C using rod B as '\n", + " 'an auxiliary, following the rules of the '\n", + " 'Tower of Hanoi puzzle. If you have any '\n", + " 'more tasks or need further explanation, '\n", + " 'feel free to ask!',\n", + " 'name': 'code_writer',\n", + " 'role': 'user'},\n", + " {'content': '',\n", + " 'name': 'code_executor_agent',\n", + " 'role': 'assistant'}],\n", + " summary='',\n", + " cost={'usage_excluding_cached_inference': {'total_cost': 0},\n", + " 'usage_including_cached_inference': {'gpt-4-turbo-2024-04-09': {'completion_tokens': 499,\n", + " 'cost': 0.0269,\n", + " 'prompt_tokens': 1193,\n", + " 'total_tokens': 1692},\n", + " 'total_cost': 0.0269}},\n", + " human_input=[])\n" + ] + } + ], + "source": [ + "import pprint\n", + "pprint.pprint(chat_result)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Use ServiceAccount token" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If a PodCommandLineCodeExecutor instance executes on inside of kubernetes Pod, instance can use token which is generated from ServiceAccount to access kubernetes API server.\n", + "\n", + "PodCommandLineCodeExecutor needs permissions of verbs `create`, `get`, `delete` on resource `pods`, and verb `get` for resources `pods/status`, `pods/exec`.\n", + "\n", + "You can make ServiceAccount, ClusterRole and RoleBinding with kubectl." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "serviceaccount/autogen-executor-sa created\n" + ] + } + ], + "source": [ + "%%bash\n", + "# create ServiceAccount on default namespace\n", + "kubectl create sa autogen-executor-sa" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "clusterrole.rbac.authorization.k8s.io/autogen-executor-role created\n" + ] + } + ], + "source": [ + "%%bash\n", + "# create ClusterRole\n", + "kubectl create clusterrole autogen-executor-role \\\n", + " --verb=get,create,delete --resource=pods,pods/status,pods/exec" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "rolebinding.rbac.authorization.k8s.io/autogen-executor-rolebinding created\n" + ] + } + ], + "source": [ + "%%bash\n", + "# create RoleBinding\n", + "kubectl create rolebinding autogen-executor-rolebinding \\\n", + " --clusterrole autogen-executor-role --serviceaccount default:autogen-executor-sa" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Pod with serviceAccount created before can be launched by below" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "pod/autogen-executor created\n" + ] + } + ], + "source": [ + "%%bash\n", + "# create pod with serviceaccount\n", + "kubectl run autogen-executor --image python:3 \\\n", + " --overrides='{\"spec\":{\"serviceAccount\": \"autogen-executor-sa\"}}' \\\n", + " -- bash -c 'pip install pyautogen[kubernetes] && sleep inifinity'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Execute PodCommandLineCodeExecutor in autogen-executor Pod" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%%bash\n", + "kubectl exec autogen-executor -it -- python" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "kube_config_path not provided and default location (~/.kube/config) does not exist. Using inCluster Config. This might not work.\n", + "exit_code=0 output='Hello, World!\\n' code_file='/workspace/tmp_code_07da107bb575cc4e02b0e1d6d99cc204.py'" + ] + } + ], + "source": [ + "from autogen.coding.kubernetes import PodCommandLineCodeExecutor\n", + "from autogen.coding import CodeBlock\n", + "\n", + "# PodCommandLineCodeExecutor uses token generated from ServiceAccount by kubernetes incluster config\n", + "with PodCommandLineCodeExecutor() as executor:\n", + " print(\n", + " executor.execute_code_blocks(\n", + " code_blocks=[\n", + " CodeBlock(language=\"python\", code=\"print('Hello, World!')\"),\n", + " ]\n", + " )\n", " )" ] } From 1483efad9d76d2a278dfe4fc94c46f8adc19a992 Mon Sep 17 00:00:00 2001 From: questcollector Date: Mon, 26 Aug 2024 16:51:48 +0900 Subject: [PATCH 11/16] add license info --- LICENSE-CODE-KUBERNETES | 201 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 LICENSE-CODE-KUBERNETES diff --git a/LICENSE-CODE-KUBERNETES b/LICENSE-CODE-KUBERNETES new file mode 100644 index 000000000000..621c73eb1442 --- /dev/null +++ b/LICENSE-CODE-KUBERNETES @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 The Kubernetes Authors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file From dd3154bef8a6740d1067f8d626df8c39c23567a2 Mon Sep 17 00:00:00 2001 From: "kiyoung.you" Date: Mon, 26 Aug 2024 22:20:51 +0900 Subject: [PATCH 12/16] revise documentation --- ...rnetes-pod-commandline-code-executor.ipynb | 115 +++++++++++------- 1 file changed, 68 insertions(+), 47 deletions(-) diff --git a/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb index e8b68d934717..3af3f5fc60f2 100644 --- a/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb +++ b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb @@ -11,17 +11,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `PodCommandLineCodeExecutor` of the autogen.coding.kubernetes module is to execute a code block using a pod in Kubernetes.\n", - "It is like DockerCommandLineCodeExecutor, but creates container on kubernetes Pod.\n", + "The `PodCommandLineCodeExecutor` in the `autogen.coding.kubernetes` module is designed to execute code blocks using a pod in Kubernetes.\n", + "It functions similarly to the `DockerCommandLineCodeExecutor`, but specifically creates container within Kubernetes environments.\n", "\n", "There are two condition to use PodCommandLineCodeExecutor.\n", - "- accessible to kubernetes cluster\n", - "- install autogen with extra feature kubernetes\n", + "- Access to a Kubernetes cluster\n", + "- installation `autogen` with the extra requirements `'pyautogen[kubernetes]'`\n", "\n", - "This documents uses minikube cluster on local environment.\n", - "You can refer to the link below for installation and execution of minikube.\n", + "For local development and testing, this document uses a Minikube cluster.\n", "\n", - "https://minikube.sigs.k8s.io/docs/start/" + "Minikube is a tool that allows you to run a single-node Kubernetes cluster on you local machine. \n", + "You can refer to the link below for installation and setup of Minikube.\n", + "\n", + "🔗 https://minikube.sigs.k8s.io/docs/start/" ] }, { @@ -37,9 +39,9 @@ "source": [ "There are four options PodCommandLineCodeExecutor to access kubernetes API server.\n", "- default kubeconfig file path: `~/.kube/config`\n", - "- To provide kubeconfig file path to `kube_config_file` argument of `PodCommandLineCodeExecutor`.\n", - "- To provide kubeconfig file path to `KUBECONFIG` environment variable.\n", - "- To provide token from kubernetes ServiceAccount which has enough permissions" + "- Provide a custom kubeconfig file path using the `kube_config_file` argument of `PodCommandLineCodeExecutor`.\n", + "- Set the kubeconfig file path using the `KUBECONFIG` environment variable.\n", + "- Provide token from Kubernetes ServiceAccount with sufficient permissions" ] }, { @@ -48,7 +50,7 @@ "source": [ "Generally, if kubeconfig file is located in `~/.kube/config`, there's no need to provide kubeconfig file path on parameter or environment variables.\n", "\n", - "the Tutorial of providing ServiceAccount Token is in the last section" + "The tutorial of providing ServiceAccount Token is in the last section" ] }, { @@ -57,8 +59,25 @@ "source": [ "## Example\n", "\n", - "In order to use kubernetes Pod based code executor, kubernetes python sdk is required.\n", - "It can be installed by `pip install 'kubernetes>=27'` or with the extra kubernetes" + "In order to use kubernetes Pod based code executor, you need to install Kubernetes Python SDK.\n", + "\n", + "You can do this by running the following command:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "pip install 'kubernetes>=27'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Alternatively, you can install it with the extra features for Kubernetes:" ] }, { @@ -67,9 +86,7 @@ "metadata": {}, "outputs": [], "source": [ - "%pip install 'pyautogen[kubernetes]'\n", - "# or\n", - "# pip install pyautogen 'kubernetes>=27'" + "pip install 'pyautogen[kubernetes]'" ] }, { @@ -85,10 +102,10 @@ "metadata": {}, "outputs": [], "source": [ - "# import os\n", - "# # If kubeconfig file is not located on ~/.kube/config but other path, \n", - "# # you can set path of kubeconfig file on KUBECONFIG environment variables \n", - "# os.environ[\"KUBECONFIG\"] = \"kubeconfig/file/path\"" + "import os\n", + "# Set the KUBECONFIG environment variable \n", + "# if the kubeconfig file is not in the default location(~/.kube/cofig).\n", + "os.environ[\"KUBECONFIG\"] = \"path/to/your/kubeconfig\"" ] }, { @@ -121,6 +138,7 @@ " ) as executor:\n", " print(\n", " executor.execute_code_blocks(\n", + " # Example of executing a simple Python code block within a Kubernetes pod.\n", " code_blocks=[\n", " CodeBlock(language=\"python\", code=\"print('Hello, World!')\"),\n", " ]\n", @@ -132,9 +150,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "With context manager(with statement), the pod created by PodCommandLineCodeExecutor deleted automatically after tasks done.\n", + "Using a context manager(the `with` statement), the pod created by `PodCommandLineCodeExecutor` is automatically deleted after the tasks are completed.\n", "\n", - "To delete the pod manually, you can use `stop()` method" + "Although the pod is automatically deleted when using a context manager, you might sometimes need to delete it manually. You can do this using `stop()` method, as shown below:" ] }, { @@ -162,7 +180,8 @@ ], "source": [ "%%bash\n", - "# default pod name is autogen-code-exec-{uuid.uuid4()}\n", + "# This command lists all pods in the default namespace. \n", + "# The default pod name follows the format autogen-code-exec-{uuid.uuid4()}.\n", "kubectl get pod -n default" ] }, @@ -181,7 +200,8 @@ ], "source": [ "%%bash\n", - "# default container image is python:3-slim\n", + "# This command shows container's image in the pod.\n", + "# The default container image is python:3-slim\n", "kubectl get pod autogen-code-exec-afd217ac-f77b-4ede-8c53-1297eca5ec64 -o jsonpath={.spec.containers[0].image}" ] }, @@ -198,11 +218,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "If you use another container image for code executor pod, you can provide image tag to `image` argument.\n", + "To use a different container image for code executor pod, specify the desired image tag using `image` argument.\n", "\n", - "PodCommandLineCode Executor has default execution policy that allows python and shell script code blocks.\n", - "\n", - "It can be allowed other languages with `execution_policies` argument." + "`PodCommandLineCodeExecutor` has a default execution policy that allows Python and shell script code blocks. You can enable other languages with `execution_policies` argument." ] }, { @@ -220,11 +238,11 @@ ], "source": [ "with PodCommandLineCodeExecutor(\n", - " image=\"node:22-alpine\", # you can provide runtime environments through container image\n", + " image=\"node:22-alpine\", # Specifies the runtime environments using a container image\n", " namespace=\"default\",\n", - " work_dir=\"./app\", # workspace directory for code block files\n", - " timeout=10, # timeout(seconds) value for waiting pod creation, execution of code blocks. default is 60 seconds\n", - " execution_policies = {\"javascript\": True} # allowed execution languages can be updated with execution_policy dictionary\n", + " work_dir=\"./app\", # Directory within the container where code block files are stored\n", + " timeout=10, # Timeout in seconds for pod creation and code block execution (default is 60 seconds)\n", + " execution_policies = {\"javascript\": True} # Enable execution of Javascript code blocks by updating execution policies\n", ") as executor:\n", " print(\n", " executor.execute_code_blocks(\n", @@ -239,10 +257,10 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "If you want to give custom settings for executor pod, such as annotations, environment variables, commands, volumes etc., \n", - "you can provide custom pod specification with `kubernetes.client.V1Pod` format.\n", + "If you want to apply custom settings for executor pod, such as annotations, environment variables, commands, volumes etc., \n", + "you can provide a custom pod specification using `kubernetes.client.V1Pod` format.\n", "\n", - "`container_name` argument should also be provided because PodCommandLineCodeExecutor do not automatically recognize a container where code blocks will be executed " + "The `container_name` argument should also be provided because `PodCommandLineCodeExecutor` does not automatically recognize the container where code blocks will be executed." ] }, { @@ -261,7 +279,7 @@ " containers=[client.V1Container(\n", " args=[\"-c\", \"while true;do sleep 5; done\"],\n", " command=[\"/bin/sh\"],\n", - " name=\"abcd\", # container name where code blocks will be executed should be provided to `container_name` argument\n", + " name=\"abcd\", # container name where code blocks will be executed should be provided using `container_name` argument\n", " image=\"python:3.11-slim\",\n", " env=[\n", " client.V1EnvVar(\n", @@ -299,7 +317,7 @@ "source": [ "with PodCommandLineCodeExecutor(\n", " pod_spec=pod, # custom executor pod spec\n", - " container_name=\"abcd\", # If custom executor pod spec is provided, container_name where code block will be executed should be specified\n", + " container_name=\"abcd\", # To use custom executor pod spec, container_name where code block will be executed should be specified\n", " work_dir=\"/autogen\",\n", " timeout=60,\n", ") as executor:\n", @@ -331,7 +349,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "PodCommandLineCodeExecutor can be integrated with Agents." + "`PodCommandLineCodeExecutor` can be integrated with Agents." ] }, { @@ -427,7 +445,7 @@ "from autogen import ConversableAgent\n", "\n", "# The code writer agent's system message is to instruct the LLM on how to\n", - "# use the Jupyter code executor with IPython kernel.\n", + "# use the code executor with python or shell script code\n", "code_writer_system_message = \"\"\"\n", "You have been given coding capability to solve tasks using Python code.\n", "In the following cases, suggest python code (in a python coding block) or shell script (in a sh coding block) for the user to execute.\n", @@ -585,11 +603,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "If a PodCommandLineCodeExecutor instance executes on inside of kubernetes Pod, instance can use token which is generated from ServiceAccount to access kubernetes API server.\n", + "If a `PodCommandLineCodeExecutor` instance runs inside of Kubernetes Pod, it can use a token generated from a ServiceAccount to access Kubernetes API server.\n", "\n", - "PodCommandLineCodeExecutor needs permissions of verbs `create`, `get`, `delete` on resource `pods`, and verb `get` for resources `pods/status`, `pods/exec`.\n", + "The `PodCommandLineCodeExecutor` requires the following permissions:\n", + "the verbs `create`, `get`, `delete` for `pods` resource, and the verb `get` for resources `pods/status`, `pods/exec`.\n", "\n", - "You can make ServiceAccount, ClusterRole and RoleBinding with kubectl." + "You can create a ServiceAccount, ClusterRole and RoleBinding with `kubectl` as shown below:" ] }, { @@ -607,7 +626,7 @@ ], "source": [ "%%bash\n", - "# create ServiceAccount on default namespace\n", + "# Create ServiceAccount on default namespace\n", "kubectl create sa autogen-executor-sa" ] }, @@ -626,7 +645,7 @@ ], "source": [ "%%bash\n", - "# create ClusterRole\n", + "# Create ClusterRole that has sufficient permissions\n", "kubectl create clusterrole autogen-executor-role \\\n", " --verb=get,create,delete --resource=pods,pods/status,pods/exec" ] @@ -646,7 +665,7 @@ ], "source": [ "%%bash\n", - "# create RoleBinding\n", + "# Create RoleBinding that binds ClusterRole and ServiceAccount\n", "kubectl create rolebinding autogen-executor-rolebinding \\\n", " --clusterrole autogen-executor-role --serviceaccount default:autogen-executor-sa" ] @@ -655,7 +674,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Pod with serviceAccount created before can be launched by below" + "A pod with a previously created ServiceAccount can be launched using the following command." ] }, { @@ -683,7 +702,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Execute PodCommandLineCodeExecutor in autogen-executor Pod" + "You can execute `PodCommandLineCodeExecutor` inside the Python interpreter process from `autogen-executor` Pod.\n", + "\n", + "It creates new pod for code execution using token generated from `autogen-executor-sa` ServiceAccount." ] }, { From 58dd0ca0024d9c7cc0cb5c0e6fc94692e151faf3 Mon Sep 17 00:00:00 2001 From: questcollector Date: Fri, 11 Oct 2024 13:03:59 +0900 Subject: [PATCH 13/16] modify document: install autogen-agentchat --- .../kubernetes-pod-commandline-code-executor.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb index 3af3f5fc60f2..3a284f25e226 100644 --- a/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb +++ b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb @@ -86,7 +86,7 @@ "metadata": {}, "outputs": [], "source": [ - "pip install 'pyautogen[kubernetes]'" + "pip install 'autogen-agentchat[kubernetes]~=0.2'" ] }, { From 378e2d69856d9c9d75ad5868f9e34a94889983ad Mon Sep 17 00:00:00 2001 From: questcollector Date: Tue, 15 Oct 2024 13:25:13 +0900 Subject: [PATCH 14/16] apply pre-commit --- LICENSE-CODE-KUBERNETES | 2 +- autogen/coding/kubernetes/__init__.py | 2 +- .../pod_commandline_code_executor.py | 141 +++++++++++------- ...st_kubernetes.commandline_code_executor.md | 4 +- ...st_kubernetes_commandline_code_executor.py | 98 ++++++------ ...rnetes-pod-commandline-code-executor.ipynb | 80 +++++----- 6 files changed, 178 insertions(+), 149 deletions(-) diff --git a/LICENSE-CODE-KUBERNETES b/LICENSE-CODE-KUBERNETES index 621c73eb1442..45cadb395ec4 100644 --- a/LICENSE-CODE-KUBERNETES +++ b/LICENSE-CODE-KUBERNETES @@ -198,4 +198,4 @@ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file + limitations under the License. diff --git a/autogen/coding/kubernetes/__init__.py b/autogen/coding/kubernetes/__init__.py index dc4de611a573..3129ec86bf3e 100644 --- a/autogen/coding/kubernetes/__init__.py +++ b/autogen/coding/kubernetes/__init__.py @@ -2,4 +2,4 @@ __all__ = [ "PodCommandLineCodeExecutor", -] \ No newline at end of file +] diff --git a/autogen/coding/kubernetes/pod_commandline_code_executor.py b/autogen/coding/kubernetes/pod_commandline_code_executor.py index 7310dc79d127..a232a3922717 100644 --- a/autogen/coding/kubernetes/pod_commandline_code_executor.py +++ b/autogen/coding/kubernetes/pod_commandline_code_executor.py @@ -1,23 +1,24 @@ from __future__ import annotations -from typing import Any, ClassVar, Dict, List, Optional, Type, Union -from pathlib import Path -from types import TracebackType -from hashlib import md5 -from time import sleep -import textwrap -from pathlib import Path -import uuid import atexit +import importlib import sys +import textwrap +import uuid +from hashlib import md5 +from pathlib import Path +from time import sleep +from types import TracebackType +from typing import Any, ClassVar, Dict, List, Optional, Type, Union -from kubernetes import config, client -from kubernetes.stream import stream -from kubernetes.client.rest import ApiException +client = importlib.import_module("kubernetes.client") +config = importlib.import_module("kubernetes.config") +ApiException = importlib.import_module("kubernetes.client.rest").ApiException +stream = importlib.import_module("kubernetes.stream").stream +from ...code_utils import TIMEOUT_MSG, _cmd from ..base import CodeBlock, CodeExecutor, CodeExtractor, CommandLineCodeResult from ..markdown_code_extractor import MarkdownCodeExtractor -from ...code_utils import TIMEOUT_MSG, _cmd from ..utils import _get_file_name_from_content, silence_pip if sys.version_info >= (3, 11): @@ -25,6 +26,7 @@ else: from typing_extensions import Self + class PodCommandLineCodeExecutor(CodeExecutor): DEFAULT_EXECUTION_POLICY: ClassVar[Dict[str, bool]] = { "bash": True, @@ -38,16 +40,24 @@ class PodCommandLineCodeExecutor(CodeExecutor): "html": False, "css": False, } - LANGUAGE_ALIASES: ClassVar[Dict[str, str]] = {"py": "python", "js": "javascript",} + LANGUAGE_ALIASES: ClassVar[Dict[str, str]] = { + "py": "python", + "js": "javascript", + } LANGUAGE_FILE_EXTENSION: ClassVar[Dict[str, str]] = { - "python": "py", "javascript": "js", "bash": "sh", "shell": "sh", "sh": "sh", + "python": "py", + "javascript": "js", + "bash": "sh", + "shell": "sh", + "sh": "sh", } + def __init__( self, image: str = "python:3-slim", pod_name: Optional[str] = None, namespace: Optional[str] = None, - pod_spec: Optional[client.V1Pod] = None, + pod_spec: Optional[client.V1Pod] = None, # type: ignore container_name: Optional[str] = "autogen-code-exec", timeout: int = 60, work_dir: Union[Path, str] = Path("/workspace"), @@ -74,7 +84,7 @@ def __init__( namespace (Optional[str], optional): Namespace of kubernetes pod which is created. If None, will use current namespace of this instance pod_spec (Optional[client.V1Pod], optional): Specification of kubernetes pod. - custom pod spec can be provided with this param. + custom pod spec can be provided with this param. if pod_spec is provided, params above(image, pod_name, namespace) are neglected. container_name (Optional[str], optional): Name of the container where code block will be executed. if pod_spec param is provided, container_name must be provided also. @@ -86,7 +96,7 @@ def __init__( stop_container (bool, optional): If true, will automatically stop the container when stop is called, when the context manager exits or when the Python process exits with atext. Defaults to True. - execution_policies (dict[str, bool], optional): defines supported execution launguage + execution_policies (dict[str, bool], optional): defines supported execution language Raises: ValueError: On argument error, or if the container fails to start. @@ -95,13 +105,13 @@ def __init__( config.load_config() else: config.load_config(config_file=kube_config_file) - + self._api_client = client.CoreV1Api() - + if timeout < 1: raise ValueError("Timeout must be greater than or equal to 1.") self._timeout = timeout - + if isinstance(work_dir, str): work_dir = Path(work_dir) self._work_dir: Path = work_dir @@ -109,7 +119,7 @@ def __init__( if container_name is None: container_name = "autogen-code-exec" self._container_name = container_name - + # Start a container from the image, read to exec commands later if pod_spec: pod = pod_spec @@ -124,18 +134,20 @@ def __init__( namespace = f.read() pod = client.V1Pod( - metadata=client.V1ObjectMeta(name=pod_name,namespace=namespace), + metadata=client.V1ObjectMeta(name=pod_name, namespace=namespace), spec=client.V1PodSpec( restart_policy="Never", - containers=[client.V1Container( - args=["-c", "while true;do sleep 5; done"], - command=["/bin/sh"], - name=container_name, - image=image - )] - ) + containers=[ + client.V1Container( + args=["-c", "while true;do sleep 5; done"], + command=["/bin/sh"], + name=container_name, + image=image, + ) + ], + ), ) - + try: pod_name = pod.metadata.name namespace = pod.metadata.namespace @@ -153,15 +165,15 @@ def cleanup() -> None: atexit.unregister(cleanup) self._cleanup = cleanup - + if stop_container: atexit.register(cleanup) - + self.execution_policies = self.DEFAULT_EXECUTION_POLICY.copy() if execution_policies is not None: self.execution_policies.update(execution_policies) - - def _wait_for_ready(self, stop_time: float = 0.1) -> None: + + def _wait_for_ready(self, stop_time: float = 0.1) -> None: elapsed_time = 0.0 name = self._pod.metadata.name namespace = self._pod.metadata.namespace @@ -178,12 +190,12 @@ def _wait_for_ready(self, stop_time: float = 0.1) -> None: break except ApiException as e: raise ValueError(f"reading pod status failed: {e}") - + @property def timeout(self) -> int: """(Experimental) The timeout for code execution.""" return self._timeout - + @property def work_dir(self) -> Path: """(Experimental) The working directory for the code execution.""" @@ -220,22 +232,22 @@ def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CommandLineCodeRe code = silence_pip(code_block.code, lang) if lang in ["bash", "shell", "sh"]: code = "\n".join(["#!/bin/bash", code]) - + try: filename = _get_file_name_from_content(code, self._work_dir) except ValueError: outputs.append("Filename is not in the workspace") last_exit_code = 1 break - + if not filename: extension = self.LANGUAGE_FILE_EXTENSION.get(lang, lang) - filename =f"tmp_code_{md5(code.encode()).hexdigest()}.{extension}" - + filename = f"tmp_code_{md5(code.encode()).hexdigest()}.{extension}" + code_path = self._work_dir / filename exec_script = textwrap.dedent( - """ + """ if [ ! -d "{workspace}" ]; then mkdir {workspace} fi @@ -245,24 +257,37 @@ def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CommandLineCodeRe chmod +x {code_path}""" ) exec_script = exec_script.format(workspace=str(self._work_dir), code_path=code_path, code=code) - stream(self._api_client.connect_get_namespaced_pod_exec, - self._pod.metadata.name, self._pod.metadata.namespace, - command=["/bin/sh", "-c", exec_script], - container=self._container_name, - stderr=True, stdin=False, stdout=True, tty=False) - + stream( + self._api_client.connect_get_namespaced_pod_exec, + self._pod.metadata.name, + self._pod.metadata.namespace, + command=["/bin/sh", "-c", exec_script], + container=self._container_name, + stderr=True, + stdin=False, + stdout=True, + tty=False, + ) + files.append(code_path) - + if not execute_code: outputs.append(f"Code saved to {str(code_path)}\n") continue - - resp = stream(self._api_client.connect_get_namespaced_pod_exec, - self._pod.metadata.name, self._pod.metadata.namespace, - command=["timeout", str(self._timeout), _cmd(lang), str(code_path)], - container=self._container_name, - stderr=True, stdin=False, stdout=True, tty=False, _preload_content=False) - + + resp = stream( + self._api_client.connect_get_namespaced_pod_exec, + self._pod.metadata.name, + self._pod.metadata.namespace, + command=["timeout", str(self._timeout), _cmd(lang), str(code_path)], + container=self._container_name, + stderr=True, + stdin=False, + stdout=True, + tty=False, + _preload_content=False, + ) + stdout_messages = [] stderr_messages = [] while resp.is_open(): @@ -274,10 +299,10 @@ def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CommandLineCodeRe outputs.extend(stdout_messages + stderr_messages) exit_code = resp.returncode resp.close() - + if exit_code == 124: outputs.append("\n" + TIMEOUT_MSG) - + last_exit_code = exit_code if exit_code != 0: break @@ -295,4 +320,4 @@ def __enter__(self) -> Self: def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: - self.stop() \ No newline at end of file + self.stop() diff --git a/test/coding/test_kubernetes.commandline_code_executor.md b/test/coding/test_kubernetes.commandline_code_executor.md index cc61003094a1..ad9348dc6007 100644 --- a/test/coding/test_kubernetes.commandline_code_executor.md +++ b/test/coding/test_kubernetes.commandline_code_executor.md @@ -6,7 +6,7 @@ To test PodCommandLineCodeExecutor, the following environment is required. ## kubernetes cluster config file -kubernetes cluster config file, kubeconfig file's location should be set on environment variable `KUBECONFIG` or +kubernetes cluster config file, kubeconfig file's location should be set on environment variable `KUBECONFIG` or It must be located in the .kube/config path of your home directory. For Windows, `C:\Users\<>\.kube\config`, @@ -41,4 +41,4 @@ Perform the test with the following command ```sh pytest test/coding/test_kubernetes_commandline_code_executor.py -``` \ No newline at end of file +``` diff --git a/test/coding/test_kubernetes_commandline_code_executor.py b/test/coding/test_kubernetes_commandline_code_executor.py index f7555cc67620..a4483f0c67f9 100644 --- a/test/coding/test_kubernetes_commandline_code_executor.py +++ b/test/coding/test_kubernetes_commandline_code_executor.py @@ -1,25 +1,27 @@ +import importlib import os import sys from pathlib import Path import pytest -from kubernetes import client, config -from kubernetes.client.rest import ApiException -from autogen.coding.base import CodeBlock, CodeExecutor +client = importlib.import_module("kubernetes.client") +config = importlib.import_module("kubernetes.config") + from autogen.code_utils import TIMEOUT_MSG +from autogen.coding.base import CodeBlock, CodeExecutor try: from autogen.coding.kubernetes import PodCommandLineCodeExecutor - + kubeconfig = Path(".kube/config") - if os.environ.get('KUBECONFIG', None): + if os.environ.get("KUBECONFIG", None): kubeconfig = Path(os.environ["KUBECONFIG"]) - elif sys.platform == 'win32': + elif sys.platform == "win32": kubeconfig = os.environ["userprofile"] / kubeconfig else: kubeconfig = os.environ["HOME"] / kubeconfig - + if kubeconfig.is_file(): config.load_config(config_file=str(kubeconfig)) api_client = client.CoreV1Api() @@ -27,37 +29,35 @@ skip_kubernetes_tests = False else: skip_kubernetes_tests = True -except: +except Exception: skip_kubernetes_tests = True pod_spec = client.V1Pod( - metadata=client.V1ObjectMeta(name="abcd",namespace="default", annotations={"sidecar.istio.io/inject": "false"}), + metadata=client.V1ObjectMeta(name="abcd", namespace="default", annotations={"sidecar.istio.io/inject": "false"}), spec=client.V1PodSpec( restart_policy="Never", - containers=[client.V1Container( - args=["-c", "while true;do sleep 5; done"], - command=["/bin/sh"], - name="abcd", - image="python:3.11-slim", - env=[ - client.V1EnvVar( - name="TEST", - value="TEST" - ), - client.V1EnvVar( - name="POD_NAME", - value_from=client.V1EnvVarSource( - field_ref=client.V1ObjectFieldSelector( - field_path="metadata.name" - ) - ) - ) - ] - )], - ) + containers=[ + client.V1Container( + args=["-c", "while true;do sleep 5; done"], + command=["/bin/sh"], + name="abcd", + image="python:3.11-slim", + env=[ + client.V1EnvVar(name="TEST", value="TEST"), + client.V1EnvVar( + name="POD_NAME", + value_from=client.V1EnvVarSource( + field_ref=client.V1ObjectFieldSelector(field_path="metadata.name") + ), + ), + ], + ) + ], + ), ) + @pytest.mark.skipif(skip_kubernetes_tests, reason="kubernetes not accessible") def test_create_default_pod_executor(): with PodCommandLineCodeExecutor(namespace="default", kube_config_file=str(kubeconfig)) as executor: @@ -67,21 +67,23 @@ def test_create_default_pod_executor(): assert executor._pod.metadata.name.startswith("autogen-code-exec-") _test_execute_code(executor) + @pytest.mark.skipif(skip_kubernetes_tests, reason="kubernetes not accessible") def test_create_node_pod_executor(): - with PodCommandLineCodeExecutor(image="node:22-alpine", - namespace="default", - work_dir="./app", - timeout=30, - kube_config_file=str(kubeconfig), - execution_policies={"javascript": True} - ) as executor: + with PodCommandLineCodeExecutor( + image="node:22-alpine", + namespace="default", + work_dir="./app", + timeout=30, + kube_config_file=str(kubeconfig), + execution_policies={"javascript": True}, + ) as executor: assert executor.timeout == 30 assert executor.work_dir == Path("./app") assert executor._container_name == "autogen-code-exec" assert executor._pod.metadata.name.startswith("autogen-code-exec-") assert executor.execution_policies["javascript"] - + # Test single code block. code_blocks = [CodeBlock(code="console.log('hello world!')", language="javascript")] code_result = executor.execute_code_blocks(code_blocks) @@ -112,21 +114,25 @@ def test_create_node_pod_executor(): ) - @pytest.mark.skipif(skip_kubernetes_tests, reason="kubernetes not accessible") def test_create_pod_spec_pod_executor(): - with PodCommandLineCodeExecutor(pod_spec=pod_spec, container_name="abcd", kube_config_file=str(kubeconfig)) as executor: + with PodCommandLineCodeExecutor( + pod_spec=pod_spec, container_name="abcd", kube_config_file=str(kubeconfig) + ) as executor: assert executor.timeout == 60 assert executor._container_name == "abcd" assert executor._pod.metadata.name == pod_spec.metadata.name assert executor._pod.metadata.namespace == pod_spec.metadata.namespace _test_execute_code(executor) - + # Test bash script. if sys.platform not in ["win32"]: code_blocks = [CodeBlock(code="echo $TEST $POD_NAME", language="bash")] code_result = executor.execute_code_blocks(code_blocks) - assert code_result.exit_code == 0 and "TEST abcd" in code_result.output and code_result.code_file is not None + assert ( + code_result.exit_code == 0 and "TEST abcd" in code_result.output and code_result.code_file is not None + ) + @pytest.mark.skipif(skip_kubernetes_tests, reason="kubernetes not accessible") def test_pod_executor_timeout(): @@ -139,11 +145,7 @@ def test_pod_executor_timeout(): file_lines = ["import time", "time.sleep(10)", "a = 100 + 100", "print(a)"] code_blocks = [CodeBlock(code="\n".join(file_lines), language="python")] code_result = executor.execute_code_blocks(code_blocks) - assert ( - code_result.exit_code == 124 - and TIMEOUT_MSG in code_result.output - and code_result.code_file is not None - ) + assert code_result.exit_code == 124 and TIMEOUT_MSG in code_result.output and code_result.code_file is not None def _test_execute_code(executor: CodeExecutor) -> None: @@ -194,7 +196,7 @@ def _test_execute_code(executor: CodeExecutor) -> None: and code_result.code_file.find("test.py") > 0 ) - #Test error code. + # Test error code. code_blocks = [CodeBlock(code="print(sys.platform)", language="python")] code_result = executor.execute_code_blocks(code_blocks) assert code_result.exit_code == 1 and "Traceback" in code_result.output and code_result.code_file is not None diff --git a/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb index 3a284f25e226..2cad17e0deb5 100644 --- a/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb +++ b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb @@ -103,8 +103,9 @@ "outputs": [], "source": [ "import os\n", - "# Set the KUBECONFIG environment variable \n", - "# if the kubeconfig file is not in the default location(~/.kube/cofig).\n", + "\n", + "# Set the KUBECONFIG environment variable\n", + "# if the kubeconfig file is not in the default location(~/.kube/config).\n", "os.environ[\"KUBECONFIG\"] = \"path/to/your/kubeconfig\"" ] }, @@ -114,8 +115,8 @@ "metadata": {}, "outputs": [], "source": [ - "from autogen.coding.kubernetes import PodCommandLineCodeExecutor\n", - "from autogen.coding import CodeBlock" + "from autogen.coding import CodeBlock\n", + "from autogen.coding.kubernetes import PodCommandLineCodeExecutor" ] }, { @@ -135,7 +136,7 @@ "with PodCommandLineCodeExecutor(\n", " namespace=\"default\",\n", " # kube_config_file=\"kubeconfig/file/path\" # If you have another kubeconfig file, you can add it on kube_config_file argument\n", - " ) as executor:\n", + ") as executor:\n", " print(\n", " executor.execute_code_blocks(\n", " # Example of executing a simple Python code block within a Kubernetes pod.\n", @@ -238,11 +239,13 @@ ], "source": [ "with PodCommandLineCodeExecutor(\n", - " image=\"node:22-alpine\", # Specifies the runtime environments using a container image\n", + " image=\"node:22-alpine\", # Specifies the runtime environments using a container image\n", " namespace=\"default\",\n", - " work_dir=\"./app\", # Directory within the container where code block files are stored\n", - " timeout=10, # Timeout in seconds for pod creation and code block execution (default is 60 seconds)\n", - " execution_policies = {\"javascript\": True} # Enable execution of Javascript code blocks by updating execution policies\n", + " work_dir=\"./app\", # Directory within the container where code block files are stored\n", + " timeout=10, # Timeout in seconds for pod creation and code block execution (default is 60 seconds)\n", + " execution_policies={\n", + " \"javascript\": True\n", + " }, # Enable execution of Javascript code blocks by updating execution policies\n", ") as executor:\n", " print(\n", " executor.execute_code_blocks(\n", @@ -272,31 +275,27 @@ "from kubernetes import client\n", "\n", "pod = client.V1Pod(\n", - " metadata=client.V1ObjectMeta(name=\"abcd\", namespace=\"default\", \n", - " annotations={\"sidecar.istio.io/inject\": \"false\"}),\n", + " metadata=client.V1ObjectMeta(name=\"abcd\", namespace=\"default\", annotations={\"sidecar.istio.io/inject\": \"false\"}),\n", " spec=client.V1PodSpec(\n", " restart_policy=\"Never\",\n", - " containers=[client.V1Container(\n", - " args=[\"-c\", \"while true;do sleep 5; done\"],\n", - " command=[\"/bin/sh\"],\n", - " name=\"abcd\", # container name where code blocks will be executed should be provided using `container_name` argument\n", - " image=\"python:3.11-slim\",\n", - " env=[\n", - " client.V1EnvVar(\n", - " name=\"TEST\",\n", - " value=\"TEST\"\n", - " ),\n", - " client.V1EnvVar(\n", - " name=\"POD_NAME\",\n", - " value_from=client.V1EnvVarSource(\n", - " field_ref=client.V1ObjectFieldSelector(\n", - " field_path=\"metadata.name\"\n", - " )\n", - " )\n", - " )\n", - " ]\n", - " )],\n", - " )\n", + " containers=[\n", + " client.V1Container(\n", + " args=[\"-c\", \"while true;do sleep 5; done\"],\n", + " command=[\"/bin/sh\"],\n", + " name=\"abcd\", # container name where code blocks will be executed should be provided using `container_name` argument\n", + " image=\"python:3.11-slim\",\n", + " env=[\n", + " client.V1EnvVar(name=\"TEST\", value=\"TEST\"),\n", + " client.V1EnvVar(\n", + " name=\"POD_NAME\",\n", + " value_from=client.V1EnvVarSource(\n", + " field_ref=client.V1ObjectFieldSelector(field_path=\"metadata.name\")\n", + " ),\n", + " ),\n", + " ],\n", + " )\n", + " ],\n", + " ),\n", ")" ] }, @@ -316,8 +315,8 @@ ], "source": [ "with PodCommandLineCodeExecutor(\n", - " pod_spec=pod, # custom executor pod spec\n", - " container_name=\"abcd\", # To use custom executor pod spec, container_name where code block will be executed should be specified\n", + " pod_spec=pod, # custom executor pod spec\n", + " container_name=\"abcd\", # To use custom executor pod spec, container_name where code block will be executed should be specified\n", " work_dir=\"/autogen\",\n", " timeout=60,\n", ") as executor:\n", @@ -331,11 +330,12 @@ " print(\n", " executor.execute_code_blocks(\n", " code_blocks=[\n", - " CodeBlock(code=\"echo $TEST $POD_NAME\", language=\"bash\"), # echo environment variables specified in pod_spec\n", + " CodeBlock(\n", + " code=\"echo $TEST $POD_NAME\", language=\"bash\"\n", + " ), # echo environment variables specified in pod_spec\n", " ]\n", " )\n", - " )\n", - " " + " )" ] }, { @@ -359,6 +359,7 @@ "outputs": [], "source": [ "from autogen import config_list_from_json\n", + "\n", "config_list = config_list_from_json(\n", " env_or_file=\"OAI_CONFIG_LIST\",\n", ")" @@ -456,7 +457,7 @@ "If you want the user to save the code in a file before executing it, put # filename: inside the code block as the first line. Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user.\n", "\"\"\"\n", "with PodCommandLineCodeExecutor(namespace=\"default\") as executor:\n", - " \n", + "\n", " code_executor_agent = ConversableAgent(\n", " name=\"code_executor_agent\",\n", " llm_config=False,\n", @@ -589,6 +590,7 @@ ], "source": [ "import pprint\n", + "\n", "pprint.pprint(chat_result)" ] }, @@ -732,8 +734,8 @@ } ], "source": [ - "from autogen.coding.kubernetes import PodCommandLineCodeExecutor\n", "from autogen.coding import CodeBlock\n", + "from autogen.coding.kubernetes import PodCommandLineCodeExecutor\n", "\n", "# PodCommandLineCodeExecutor uses token generated from ServiceAccount by kubernetes incluster config\n", "with PodCommandLineCodeExecutor() as executor:\n", From d3f9fe49404f994e140e1858b64b2dda78105326 Mon Sep 17 00:00:00 2001 From: Jack Gerrits Date: Tue, 15 Oct 2024 12:16:48 -0400 Subject: [PATCH 15/16] revert change to gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 5bffa374a1a5..4c925f739ec6 100644 --- a/.gitignore +++ b/.gitignore @@ -174,7 +174,7 @@ test/test_files/agenteval-in-out/out/ # local cache or coding foler local_cache/ -# coding/ +coding/ # Files created by tests *tmp_code_* From 03de569e1b8841d16bd283b98d232361dc12295c Mon Sep 17 00:00:00 2001 From: questcollector Date: Wed, 16 Oct 2024 12:51:10 +0900 Subject: [PATCH 16/16] error handling: move import block into try block --- ...st_kubernetes_commandline_code_executor.py | 57 ++++++++++--------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/test/coding/test_kubernetes_commandline_code_executor.py b/test/coding/test_kubernetes_commandline_code_executor.py index a4483f0c67f9..09e6b36aafaf 100644 --- a/test/coding/test_kubernetes_commandline_code_executor.py +++ b/test/coding/test_kubernetes_commandline_code_executor.py @@ -5,15 +5,15 @@ import pytest -client = importlib.import_module("kubernetes.client") -config = importlib.import_module("kubernetes.config") - from autogen.code_utils import TIMEOUT_MSG from autogen.coding.base import CodeBlock, CodeExecutor try: from autogen.coding.kubernetes import PodCommandLineCodeExecutor + client = importlib.import_module("kubernetes.client") + config = importlib.import_module("kubernetes.config") + kubeconfig = Path(".kube/config") if os.environ.get("KUBECONFIG", None): kubeconfig = Path(os.environ["KUBECONFIG"]) @@ -29,33 +29,34 @@ skip_kubernetes_tests = False else: skip_kubernetes_tests = True -except Exception: - skip_kubernetes_tests = True - -pod_spec = client.V1Pod( - metadata=client.V1ObjectMeta(name="abcd", namespace="default", annotations={"sidecar.istio.io/inject": "false"}), - spec=client.V1PodSpec( - restart_policy="Never", - containers=[ - client.V1Container( - args=["-c", "while true;do sleep 5; done"], - command=["/bin/sh"], - name="abcd", - image="python:3.11-slim", - env=[ - client.V1EnvVar(name="TEST", value="TEST"), - client.V1EnvVar( - name="POD_NAME", - value_from=client.V1EnvVarSource( - field_ref=client.V1ObjectFieldSelector(field_path="metadata.name") + pod_spec = client.V1Pod( + metadata=client.V1ObjectMeta( + name="abcd", namespace="default", annotations={"sidecar.istio.io/inject": "false"} + ), + spec=client.V1PodSpec( + restart_policy="Never", + containers=[ + client.V1Container( + args=["-c", "while true;do sleep 5; done"], + command=["/bin/sh"], + name="abcd", + image="python:3.11-slim", + env=[ + client.V1EnvVar(name="TEST", value="TEST"), + client.V1EnvVar( + name="POD_NAME", + value_from=client.V1EnvVarSource( + field_ref=client.V1ObjectFieldSelector(field_path="metadata.name") + ), ), - ), - ], - ) - ], - ), -) + ], + ) + ], + ), + ) +except Exception: + skip_kubernetes_tests = True @pytest.mark.skipif(skip_kubernetes_tests, reason="kubernetes not accessible")