diff --git a/LICENSE-CODE-KUBERNETES b/LICENSE-CODE-KUBERNETES new file mode 100644 index 00000000000..45cadb395ec --- /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. diff --git a/autogen/coding/kubernetes/__init__.py b/autogen/coding/kubernetes/__init__.py new file mode 100644 index 00000000000..3129ec86bf3 --- /dev/null +++ b/autogen/coding/kubernetes/__init__.py @@ -0,0 +1,5 @@ +from .pod_commandline_code_executor import PodCommandLineCodeExecutor + +__all__ = [ + "PodCommandLineCodeExecutor", +] 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 00000000000..a232a392271 --- /dev/null +++ b/autogen/coding/kubernetes/pod_commandline_code_executor.py @@ -0,0 +1,323 @@ +from __future__ import annotations + +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 + +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 ..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, + 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"), + kube_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 + 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"). + 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 + the Python process exits with atext. Defaults to True. + execution_policies (dict[str, bool], optional): defines supported execution language + + Raises: + ValueError: On argument error, or if the container fails to start. + """ + if kube_config_file is None: + 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 + + 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( + restart_policy="Never", + 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 + self._pod = 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: + 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, stop_time: float = 0.1) -> None: + elapsed_time = 0.0 + name = self._pod.metadata.name + namespace = self._pod.metadata.namespace + while True: + sleep(stop_time) + elapsed_time += stop_time + 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: + """(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._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, + ) + + 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.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 + + 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() diff --git a/setup.py b/setup.py index fe55a4a6c2e..dfc5e912779 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( 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 00000000000..ad9348dc600 --- /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 +``` 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 00000000000..09e6b36aafa --- /dev/null +++ b/test/coding/test_kubernetes_commandline_code_executor.py @@ -0,0 +1,203 @@ +import importlib +import os +import sys +from pathlib import Path + +import pytest + +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"]) + 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 + + 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") +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 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 00000000000..2cad17e0deb --- /dev/null +++ b/website/docs/topics/code-execution/kubernetes-pod-commandline-code-executor.ipynb @@ -0,0 +1,773 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Kubernetes Pod Commandline Code Executor" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "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", + "- Access to a Kubernetes cluster\n", + "- installation `autogen` with the extra requirements `'pyautogen[kubernetes]'`\n", + "\n", + "For local development and testing, this document uses a Minikube cluster.\n", + "\n", + "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/" + ] + }, + { + "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", + "- 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" + ] + }, + { + "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, 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:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "pip install 'autogen-agentchat[kubernetes]~=0.2'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To provide kubeconfig file path with environment variable, It can be added with `os.environ[\"KUBECONFIG\"]`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\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\"" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "from autogen.coding import CodeBlock\n", + "from autogen.coding.kubernetes import PodCommandLineCodeExecutor" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "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(\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", + " # 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", + " )\n", + " )" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using a context manager(the `with` statement), the pod created by `PodCommandLineCodeExecutor` is automatically deleted after the tasks are completed.\n", + "\n", + "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:" + ] + }, + { + "cell_type": "code", + "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", + "# 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" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "python:3-slim" + ] + } + ], + "source": [ + "%%bash\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}" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "executor.stop()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To use a different container image for code executor pod, specify the desired image tag using `image` argument.\n", + "\n", + "`PodCommandLineCodeExecutor` has a default execution policy that allows Python and shell script code blocks. You can enable 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\", # 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={\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", + " code_blocks=[\n", + " CodeBlock(language=\"javascript\", code=\"console.log('Hello, World!')\"),\n", + " ]\n", + " )\n", + " )" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "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", + "The `container_name` argument should also be provided because `PodCommandLineCodeExecutor` does not automatically recognize the container where code blocks will be executed." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "from kubernetes import client\n", + "\n", + "pod = client.V1Pod(\n", + " metadata=client.V1ObjectMeta(name=\"abcd\", namespace=\"default\", annotations={\"sidecar.istio.io/inject\": \"false\"}),\n", + " spec=client.V1PodSpec(\n", + " restart_policy=\"Never\",\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", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "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, # 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", + " 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(\n", + " code=\"echo $TEST $POD_NAME\", language=\"bash\"\n", + " ), # echo environment variables specified in pod_spec\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": 19, + "metadata": {}, + "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", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "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", + "# The code writer agent's system message is to instruct the LLM on how to\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", + " 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\") 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 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", + "\n", + "pprint.pprint(chat_result)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Use ServiceAccount token" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "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", + "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 create a ServiceAccount, ClusterRole and RoleBinding with `kubectl` as shown below:" + ] + }, + { + "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 that has sufficient permissions\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 that binds ClusterRole and ServiceAccount\n", + "kubectl create rolebinding autogen-executor-rolebinding \\\n", + " --clusterrole autogen-executor-role --serviceaccount default:autogen-executor-sa" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A pod with a previously created ServiceAccount can be launched using the following command." + ] + }, + { + "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": [ + "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." + ] + }, + { + "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 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", + " print(\n", + " executor.execute_code_blocks(\n", + " code_blocks=[\n", + " CodeBlock(language=\"python\", code=\"print('Hello, World!')\"),\n", + " ]\n", + " )\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 +}