Python 程序员的福音:Jupyter Lab 的 AI 扩展

喜欢 ChatGPT 的编程爱好者们有福了。 Jupyter Lab 的 AI 扩展来了!
这个扩展提供了一个聊天 UI,允许我们与 Jupyter AI 对话助手聊天。 此外,它还支持广泛的生成模型提供程序,例如 OpenAI、Anthropic、Cohere、Hugging Face 等。
设置 Jupyter AI
要安装 jupyter_ai 你需要安装 Python 3.8 到 3.10 和 JupyterLab 3。 你可以使用 conda 或 pip 安装 jupyter_ai,但如果你像我一样是基于 Apple Silicon 的 Mac 用户(M1、M1 Pro、M2 等),则应该使用 conda。
让我们使用 Python 3.10 创建一个新的虚拟环境并安装 jupyter_ai:
$ conda create -n jupyter-ai python=3.10
$ conda activate jupyter-ai
$ pip install jupyter_ai
请注意,基于 Apple Silicon 的 Mac 用户需要卸载 pip 提供的版本 grpcio,然后安装 conda 提供的版本。
$ pip uninstall grpcio; conda install grpcio
然后我们可以启动 Jupyter Lab
jupyter lab
如果一切安装成功,你应该会在 Jupyter Lab 的左侧面板中看到新的“聊天”图标。

单击“从这里开始”以选择型号并输入你的 API 密钥。

保存更改后,单击左上角的“后退”按钮。 现在你应该会看到下面的聊天界面,你可以在其中开始聊天。

稍后我们会看到你可以从聊天界面执行一些很酷的操作。 现在让我们专注于 Notebook。
使用 Jupyter AI
首先,我们需要通过在笔记本单元中运行以下代码来加载 jupyter_ai 扩展。
%load_ext jupyter_ai
然后我们可以使用下面的代码列出所有可用的提供程序和模型。
%ai list
以下是你可以使用的提供商和模型。

请注意,需要将 Jupyter AI 与特定提供商的模型一起使用,你必须安装其 Python 包并在你的环境或聊天界面中设置其 API 密钥。
比如我想使用 OpenAI 的 ChatGPT 模型。 为此,我必须安装 openai 包。
!pip install openai
并在我的环境中设置 API 密钥(要生成你的 OpenAI API 密钥,请单击此处)
import os
os.environ[“OPENAI_API_KEY”]=your-api-key
现在我们可以开始在 Jupyter Lab 中使用 ChatGPT 了。
魔术命令
让我们使用%%ai魔术命令生成代码:
%%ai chatgpt
A function that computes the lowest common multiples of two integers, and a function that runs 5 test cases of the lowest common multiple function
如果你运行上面的命令,你将获得以下输出。

如你所见,默认情况下,%%ai 命令的输出为 markdown 格式。 可以使用魔术命令的 -f 参数将输出格式更改为代码、图像、markdown、数学、HTML、JSON 和文本。
现在让我们将格式设置为代码。
%%ai chatgpt -f code
A function that computes the lowest common multiples of two integers, and a function that runs 5 test cases of the lowest common multiple function
现在,输出将被插入到一个代码单元格中。

你也可以以 markdown 格式生成数学公式。

输入、输出和错误
如果你想使用内核知道的代码执行提示,但它不在当前单元格中,你可以使用花括号语法在提示中包含变量和其他 Python 表达式。
当你想要解释位于 Jupyter notebook 中其他位置的代码时,这尤其有用。 假设我有下面的代码,其输入位于 In[12],
for i in range(1,9):
print(i)
现在我可以参考魔术 In[12] 命令%%ai来获得解释。

除了 In,Out 和 Err 也可以在你想要处理输出或得到的错误时提供帮助。
这个是 Err 的例子:

使用聊天界面
位于侧面板上的聊天界面可以帮助你执行我们之前使用魔术命令看到的类似操作 %%ai。
如果你想在提示中包含笔记本的一部分,只需选择该部分,然后选中“包括选择”框。

在下面的示例中,我要求对笔记本中的代码进行解释。

聊天界面的一个很酷的功能是根据文本提示生成整个 Notebook。 你只需要发送一条以 /generate 的消息,如在下面的例子所示。
/generate a demo of how to use the pandas library
几分钟后,你应该会收到以下消息。 如果你转到左侧面板上的文件部分,你会看到生成了一个 .ipynb 新文件。

就这些啦。 要了解更多关于Jupyter AI的信息,请访问官方网站