Run LocalCommandLineCodeExecutor within venv (#3977)

* Run LocalCommandLineCodeExecutor within venv

* Remove create_virtual_env func and add docstring

* Add explanation for LocalCommandLineExecutor docstring example

* Enhance docstring example explanation

---------

Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
This commit is contained in:
Gerardo Moreno
2024-10-29 08:17:34 -07:00
committed by GitHub
parent eb4b1f856e
commit 93733dbd65
3 changed files with 176 additions and 4 deletions

View File

@@ -136,6 +136,76 @@
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Local within a Virtual Environment\n",
"\n",
"If you want the code to run within a virtual environment created as part of the applications setup, you can specify a directory for the newly created environment and pass its context to {py:class}`~autogen_core.components.code_executor.LocalCommandLineCodeExecutor`. This setup allows the executor to use the specified virtual environment consistently throughout the application's lifetime, ensuring isolated dependencies and a controlled runtime environment."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"CommandLineCodeResult(exit_code=0, output='', code_file='/Users/gziz/Dev/autogen/python/packages/autogen-core/docs/src/user-guide/core-user-guide/framework/coding/tmp_code_d2a7db48799db3cc785156a11a38822a45c19f3956f02ec69b92e4169ecbf2ca.bash')"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import venv\n",
"from pathlib import Path\n",
"\n",
"from autogen_core.base import CancellationToken\n",
"from autogen_core.components.code_executor import CodeBlock, LocalCommandLineCodeExecutor\n",
"\n",
"work_dir = Path(\"coding\")\n",
"work_dir.mkdir(exist_ok=True)\n",
"\n",
"venv_dir = work_dir / \".venv\"\n",
"venv_builder = venv.EnvBuilder(with_pip=True)\n",
"venv_builder.create(venv_dir)\n",
"venv_context = venv_builder.ensure_directories(venv_dir)\n",
"\n",
"local_executor = LocalCommandLineCodeExecutor(work_dir=work_dir, virtual_env_context=venv_context)\n",
"await local_executor.execute_code_blocks(\n",
" code_blocks=[\n",
" CodeBlock(language=\"bash\", code=\"pip install matplotlib\"),\n",
" ],\n",
" cancellation_token=CancellationToken(),\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As we can see, the code has executed successfully, and the installation has been isolated to the newly created virtual environment, without affecting our global environment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
@@ -154,7 +224,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
"version": "3.12.4"
}
},
"nbformat": 4,