Jupyter AI Magics

2.31.7 · active · verified Thu Apr 16

Jupyter AI Magics provides AI capabilities directly within Jupyter notebooks and JupyterLab via convenient line (`%ai`) and cell (`%%ai`) magics. It integrates with various Large Language Models (LLMs) from different providers (e.g., OpenAI, Anthropic, Ollama, Hugging Face). The current version is 2.31.7, and releases are frequent, often bi-weekly, to add new features, fix bugs, and expand LLM integrations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up environment variables for LLM providers (e.g., OpenAI), load the Jupyter AI magics extension in a Jupyter notebook cell, and then use both the line (`%ai`) and cell (`%%ai`) magics to interact with a Large Language Model. Ensure you have the necessary LLM client libraries installed (e.g., `pip install openai`) and valid API keys or a running local LLM server.

import os

# --- In a Jupyter notebook cell ---

# 1. Set your API key as an environment variable.
#    For OpenAI: uncomment the line below and replace 'sk-YOUR_OPENAI_API_KEY'
# os.environ['OPENAI_API_KEY'] = os.environ.get('OPENAI_API_KEY', 'sk-dummy-for-quickstart-test')

#    For local models like Ollama, ensure the server is running:
#    e.g., in your terminal: `ollama run mistral`

# 2. Load the Jupyter AI magics extension.
#    This makes the %ai and %%ai commands available in your notebook.
# %load_ext jupyter_ai

# 3. (Optional) List available providers and models
# %ai list

# 4. Use the %ai line magic for single-line prompts.
#    Replace 'openai:gpt-3.5-turbo' with your desired model and provider.
# %ai openai:gpt-3.5-turbo "What is the capital of France?"

# 5. Use the %%ai cell magic for multi-line prompts.
#    The prompt is the content of the cell after the magic.
# %%ai openai:gpt-3.5-turbo
# Write a short poem about the benefits of learning Python.
# It should be 4 lines long and rhyme AABB.

view raw JSON →