Jupyter Code Executor
AutoGen is able to execute code in a stateful Jupyter kernel, this is in contrast to the command line code executor where each code block is executed in a new process. This means that you can define variables in one code block and use them in another. One of the interesting properties of this is that when an error is encountered, only the failing code needs to be re-executed, and not the entire script.
To use the
JupyterCodeExecutor
you need a Jupyter server running. This can be in Docker, local, or even
a remote server. Then, when constructing the
JupyterCodeExecutor
you pass it the server it should connect to.
Dependencies
In order to use Jupyter based code execution some extra dependencies are
required. These can be installed with the extra jupyter-executor
:
Jupyter Server
Docker
To run a Docker based Jupyter server, the
DockerJupyterServer
can be used.
By default the
DockerJupyterServer
will build and use a bundled Dockerfile, which can be seen below:
Custom Docker Image
A custom image can be used by passing the custom_image_name
parameter
to the
DockerJupyterServer
constructor. There are some requirements of the image for it to work
correctly:
- The image must have Jupyer Kernel
Gateway
installed and running on port 8888 for the
JupyterCodeExecutor
to be able to connect to it. - Respect the
TOKEN
environment variable, which is used to authenticate theJupyterCodeExecutor
with the Jupyter server. - Ensure the
jupyter kernelgateway
is started with:--JupyterApp.answer_yes=true
- this ensures that the kernel gateway does not prompt for confirmation when shut down.--JupyterWebsocketPersonality.list_kernels=true
- this ensures that the kernel gateway lists the available kernels.
If you wanted to add extra dependencies (for example matplotlib
and
numpy
) to this image you could customize the Dockerfile like so:
Local
To run a local Jupyter server, the
LocalJupyterServer
can be used.
Remote
The
JupyterCodeExecutor
can also connect to a remote Jupyter server. This is done by passing
connection information rather than an actual server object into the
JupyterCodeExecutor
constructor.
Image outputs
When Jupyter outputs an image, this is saved as a file into the
output_dir
of the
JupyterCodeExecutor
,
as specified by the constructor. By default this is the current working
directory.
Assigning to an agent
A single server can support multiple agents, as each executor will create its own kernel. To assign an executor to an agent it can be done like so:
When using code execution it is critical that you update the system
prompt of agents you expect to write code to be able to make use of the
executor. For example, for the
JupyterCodeExecutor
you might setup a code writing agent like so:
Then we can use these two agents to solve a problem:
Finally, stop the server. Or better yet use a context manager for it to be stopped automatically.