Jupyter AI#
Jupyter AI 是一个 JupyterLab 扩展,提供了用户与 AI 模型之间友好的用户界面。
此演示展示了 Jupyter AI 开箱即用的 IPython 魔法命令。
加载 IPython 扩展:
[1]:
%load_ext jupyter_ai
开始使用#
要开始使用 Jupyter AI,请使用 %%ai
单元魔法,并通过语法 <provider-id>:<model-id>
指定模型。第一行之后的每一行都应该包含提示。
目前,我们支持以下提供者:
ai21
anthropic
cohere
huggingface_hub
openai
openai-chat
sagemaker-endpoint
这些是 LangChain LLM 提供者 (langchain.llms
)。对于相应提供者的任何有效模型 ID,在 AI 魔法中都是有效的。例如,claude-v1.2
是 anthropic
提供者的有效模型 ID,可以通过如下方式调用 Jupyter AI 魔法:
[2]:
%%ai anthropic:claude-v1.2
Write a poem about C++.
O C++, language so keen,
With classes, objects and templates so sheen.
Inheritance and polymorphism galore,
Abstracting the complexity to the core.
Support for low and high level alike,
Helping programmers day and night.
Pointers, references and RAII,
OOP and generic programming, my oh my!
Exception handling and lambda’s too,
There’s so much you help me do!
A powerful language, sometimes complex,
But in the end, truly adept.
That’s my poem about C++,
A language with power, through and through!
隐式提供者#
如果您的模型 ID 是唯一的,那么我们也可以隐式推断提供者 ID:
[3]:
%%ai j2-jumbo-instruct
Write some JavaScript code that prints "hello world" to the console.
Copy code console . log ( “hello world” );
快速实验不同的HF Hub模型#
我们可以直接在Hugging Face Hub上调用模型:
[4]:
%%ai huggingface_hub:google/flan-t5-xl
What is the capital of New York state?
If that’s the question you’re looking for, here’s the bottom line for New York: $2.13 per day.
It’s not surprising then, because as you can see
[5]:
%%ai huggingface_hub:gpt2
What is the square root of 2?
2 is the number of times a point in a circle is square. Thus, one is squared twice: 2 x 2 = 19 x 18 = 51 / 2 x 2 = 49, and I was
通过 -f/--format
格式化#
您也可以传递 -f/--format
参数来指定用于渲染输出的 IPython 显示。有效的格式有:
markdown
math
html
json
[6]:
%%ai anthropic:claude-v1.2 -f html
Create a square using SVG with a black border and white fill.
[8]:
%%ai chatgpt -f math
Generate the 2D heat equation.
IPython 插值#
您还可以通过大括号将 IPython 范围插入到您的提示中。
[9]:
poet = "Walt Whitman"
[10]:
%%ai chatgpt
Write a poem in the style of {poet}
[11]:
for i in range(0, 5):
print(i)
0
1
2
3
4
[12]:
%%ai cohere:command-xlarge-nightly
Please explain the code below:
--
{In[11]}
The above code will print the numbers 0 through 4. It will not print the number 5 because the range function includes the first value (i.e. 0) but not the last value (i.e. 5).
完整示例:拉普拉斯方程#
假设我刚刚收到教授关于“拉普拉斯方程”的作业。
什么是拉普拉斯方程?
拉普拉斯方程在极坐标中的形式是什么?
编写一个Python算法以数值方式求解拉普拉斯方程。
问题是:我对他们所说的完全没有头绪。
让我们询问一个大型语言模型(LLM)这个作业的内容。
[13]:
%%ai claude-v1.2
What is the 2d Laplace equation and when is it used? Use LaTeX for equations delimited by `$`.
The 2D Laplace equation is:
where \(f\) is a scalar function.
It is used to describe steady-state heat flow, electrostatics, fluid flow, and other phenomena in two dimensions under the assumption of no sources. The Laplace equation arises from simplifying the Poisson equation by setting the charge density to 0. It is a key partial differential equation used in modeling many physical systems.
The Laplace equation implies that the sum of second derivatives of \(f\) with respect to \(x\) and \(y\) is zero, which means the curvature of the solution surface is constant. So, the solutions have a minimal surface with constant negative Gaussian curvature.
Does this help explain the 2D Laplace equation? Let me know if you have any other questions!
[14]:
%%ai j2-jumbo-instruct --format math
Write the 2d Laplace equation in polar coordinates.
[15]:
%%ai chatgpt
Please generate the Python code to solve the 2D Laplace equation in cartesian coordinates.
Solve the equation on the square domain x=(0,1) and y=(0,1) with vanishing boundary conditions.
Plot the solution using Matplotlib.
Please also provide an explanation.
Here’s the Python code to solve the 2D Laplace equation in Cartesian coordinates:
import numpy as np
import matplotlib.pyplot as plt
# Set up grid
nx = 101
ny = 101
nt = 100
dx = 1. / (nx - 1)
dy = 1. / (ny - 1)
x = np.linspace(0, 1, nx)
y = np.linspace(0, 1, ny)
# Initialize solution
u = np.zeros((nx, ny))
# Set boundary conditions
u[0,:] = 0
u[-1,:] = 0
u[:,0] = 0
u[:,-1] = 0
# Set up source term
f = np.zeros((nx, ny))
f[int(nx/2), int(ny/2)] = 1 / (dx * dy)
# Set up iteration parameters
tolerance = 1e-5
omega = 1.8
# Iterative solver
for n in range(nt):
for i in range(1, nx-1):
for j in range(1, ny-1):
u_old = u[i,j]
u[i,j] = (1-omega)*u[i,j] + omega*(dx**2*(u[i+1,j]+u[i-1,j]) + dy**2*(u[i,j+1]+u[i,j-1]) - dx**2*dy**2*f[i,j]) / (2*(dx**2+dy**2))
if abs(u[i,j] - u_old) < tolerance:
break
# Plot solution
X, Y = np.meshgrid(x, y)
plt.contourf(X, Y, u.T, 100, cmap='viridis')
plt.colorbar()
plt.xlabel('x')
plt.ylabel('y')
plt.title('2D Laplace equation solution')
plt.show()
Explanation:
This code uses finite difference methods to solve the 2D Laplace equation, which is given by:
∇²u(x,y) = 0
on the square domain x=(0,1) and y=(0,1) with vanishing boundary conditions.
We set up a grid with nx x ny points in the x and y directions, respectively. We initialize a solution vector u with zeros, and then set the boundary conditions to zero. We also set up a source term f, which is a delta function located at the center of the domain. The source term is used to enforce the vanishing boundary conditions.
We then use an iterative solver to solve the Laplace equation. The solver updates the values of the solution vector at each point on the grid until the difference between consecutive iterations is below a certain tolerance.
Finally, we plot the solution using Matplotlib, which creates a contour plot of the solution on the domain. The contour plot is a visualization of the solution u(x,y) as a height map, which provides a 2D picture of the solution.