A programming framework for agentic AI
Fix #2845 - LocalCommandLineCodeExecutor is not working with virtual environments (#2926)
NanthagopalEswaranded8e1b280ae
diff --git a/autogen/coding/local_commandline_code_executor.py b/autogen/coding/local_commandline_code_executor.pyindex 29172bbe9..620b359a4 100644--- a/autogen/coding/local_commandline_code_executor.py+++ b/autogen/coding/local_commandline_code_executor.py@@ -294,10 +294,11 @@ $functions"""env = os.environ.copy()if self._virtual_env_context:- path_with_virtualenv = rf"{self._virtual_env_context.bin_path}{os.pathsep}{env['PATH']}"+ virtual_env_abs_path = os.path.abspath(self._virtual_env_context.bin_path)+ path_with_virtualenv = rf"{virtual_env_abs_path}{os.pathsep}{env['PATH']}"env["PATH"] = path_with_virtualenvif WIN32:- activation_script = os.path.join(self._virtual_env_context.bin_path, "activate.bat")+ activation_script = os.path.join(virtual_env_abs_path, "activate.bat")cmd = [activation_script, "&&", *cmd]try:diff --git a/test/coding/test_commandline_code_executor.py b/test/coding/test_commandline_code_executor.pyindex 4daf2e21b..99c564b42 100644--- a/test/coding/test_commandline_code_executor.py+++ b/test/coding/test_commandline_code_executor.py@@ -1,4 +1,5 @@import os+import shutilimport sysimport tempfileimport uuid@@ -411,3 +412,30 @@ def test_local_executor_with_custom_python_env():assert execution.exit_code == 0assert execution.output.strip() == "True"+++def test_local_executor_with_custom_python_env_in_local_relative_path():+ try:+ relative_folder_path = "temp_folder"+ if not os.path.isdir(relative_folder_path):+ os.mkdir(relative_folder_path)++ venv_path = os.path.join(relative_folder_path, ".venv")+ env_builder = venv.EnvBuilder(with_pip=True)+ env_builder.create(venv_path)+ env_builder_context = env_builder.ensure_directories(venv_path)++ executor = LocalCommandLineCodeExecutor(work_dir=relative_folder_path, virtual_env_context=env_builder_context)+ code_blocks = [+ CodeBlock(code="import sys; print(sys.executable)", language="python"),+ ]+ execution = executor.execute_code_blocks(code_blocks)++ assert execution.exit_code == 0++ # Check if the expected venv is used+ bin_path = os.path.abspath(env_builder_context.bin_path)+ assert Path(execution.output.strip()).parent.samefile(bin_path)+ finally:+ if os.path.isdir(relative_folder_path):+ shutil.rmtree(relative_folder_path)