Two AI workflows in one notebook

Use ordinary Python cells to compare four small pollinator surveys. Jupyter AI chat can help plan or revise code through its own agent. nbinlineai uses the tagged Markdown AI questions here to explain the nearby result. The two conversations have separate setup and history.

Two AI workflows in one notebook

Use ordinary Python cells to compare four small pollinator surveys. Jupyter AI chat can help plan or revise code through its own agent. nbinlineai uses the tagged Markdown AI questions here to explain the nearby result. The two conversations have separate setup and history.

To try both, install nbinlineai and jupyter-ai in the same JupyterLab server environment, then restart that server. Connect ChatGPT or configure an API provider in nbinlineai’s Configure AI panel. Set up Jupyter AI’s Claude or Codex chat separately using Jupyter AI’s guide. The Python analysis needs neither AI connection.

Run the code cells in order, then choose which AI question to run. Run All Cells also runs new AI questions; completed answers follow the notebook’s Keep AI answers setting.

from dataclasses import dataclass
from statistics import mean


@dataclass(frozen=True)
class Survey:
    site: str
    habitat: str
    flowers: int
    pollinator_visits: int  # Each site was observed for ten minutes.


surveys: list[Survey] = [
    Survey("North meadow", "meadow", 20, 12),
    Survey("South meadow", "meadow", 18, 9),
    Survey("East courtyard", "courtyard", 24, 5),
    Survey("West courtyard", "courtyard", 16, 4),
]

for survey in surveys:
    print(survey.site, survey.pollinator_visits)
North meadow 12
South meadow 9
East courtyard 5
West courtyard 4

Optional Jupyter AI chat: plan before editing

Open Jupyter AI’s chat sidebar if you installed and authenticated an ACP agent. You can paste this request into chat; it is an instruction for the agent, not an nbinlineai AI question:

Read the code cell with ID jai-data-setup. Propose one clear way to compare pollinator activity across habitats while accounting for different flower counts. Do not edit or execute cells yet. State two assumptions I should check.

If you want the agent to edit code later, review its proposed change first. This notebook already includes a working calculation below, so chat is optional.

# Normalize visits to ten flowers, then compare the mean site rate by habitat.
rates_by_habitat: dict[str, list[float]] = {}
for survey in surveys:
    if survey.flowers <= 0:
        raise ValueError(f"{survey.site} needs a positive flower count")
    rate = 10 * survey.pollinator_visits / survey.flowers
    rates_by_habitat.setdefault(survey.habitat, []).append(rate)

mean_rates: dict[str, float] = {
    habitat: round(mean(rates), 2)
    for habitat, rates in rates_by_habitat.items()
}
for habitat, rate in sorted(mean_rates.items()):
    print(f"{habitat}: {rate:.2f} visits per ten flowers")
courtyard: 2.29 visits per ten flowers
meadow: 5.50 visits per ten flowers
# Small deterministic checks; they do not claim a causal effect.
assert len(surveys) == 4
assert all(survey.flowers > 0 for survey in surveys)
assert set(mean_rates) == {"courtyard", "meadow"}
assert mean_rates["meadow"] > mean_rates["courtyard"]
print("Four sites checked; meadow has the higher observed normalized rate.")
Four sites checked; meadow has the higher observed normalized rate.

nbinlineai question: explain the result in place

The next tagged Markdown cell is an AI question, not Jupyter AI chat. The notebook defaults to Learning style, which should guide your reasoning with questions rather than hand you a full solution. Click its Run AI control when ready. It will use code above as notebook context, within your chosen Context settings.

Why compare visits per ten flowers instead of raw visit counts in the code above? Ask me a guiding question about what the observed difference can and cannot establish.

The sites have different numbers of flowers. If one site has more visits and more flowers, what might raw visit counts be measuring besides pollinator activity per flower?

After comparing visits per ten flowers, what can these four observed sites tell you about their rates—and what would you need to establish that habitat caused the difference?

Optional Jupyter AI chat: refactor and validate

After reading the inline answer, you may use Jupyter AI chat for a separate coding task. Paste this into chat:

Look at jai-rate-analysis and jai-checks. Suggest a small refactor into a named function that returns mean rates by habitat. Explain how to check that its output matches the existing calculation. Show a proposed patch, but do not apply or run it without my approval.

If you accept a change, rerun affected Python cells. Then use nbinlineai’s answer controls deliberately. A completed AI answer stays kept until you turn Keep off for that question. The Jupyter AI run_cell tool can execute a code cell by its stable ID, but in the default Jupyter AI setup it treats a tagged Markdown AI question as a no-op. Use nbinlineai’s Run AI or native Shift+Enter for that question.

Continue the Learning dialogue

Edit the next AI question to reflect your own interpretation before you run it. It is prefilled with a provisional thought, not a generated answer. The earlier inline question and its completed answer can inform this later turn. If you want a different answer to the earlier question after changing the analysis, turn off that cell’s Keep answer first.

My provisional interpretation is that the meadow sites had a higher observed rate in this small sample, but the difference alone does not prove the habitat caused it. Ask me one follow-up question about sampling or other explanations.

That’s a careful interpretation. With only two sites per habitat, what site differences besides habitat might explain the higher meadow rates, and how could you sample to check?

Optional: let nbinlineai add a code draft

This final step is separate from Jupyter AI chat. The code cell imports nbinlineai’s special insert_code tool; it does not call a provider. The ordinary Markdown declaration then offers that tool to the last AI question. Run that question only if you want a new unexecuted code cell. The draft appears below its paired AI answer, remains editable, and is not executed in the current Run All batch. Review it before running it yourself, then save the notebook to keep it.

from nbinlineai.tools import insert_code
print("insert_code is available for a later AI question; this cell makes no AI request.")
insert_code is available for a later AI question; this cell makes no AI request.
  • &insert_code: add an editable, unexecuted code draft to this notebook.

Use insert_code to add a short Python cell that prints each habitat’s number of surveyed sites from rates_by_habitat. Leave the new cell unexecuted so I can review it first.

Added the site-count code cell. It remains unexecuted for your review; save the notebook to keep it.

Observed live tool calls for the answer above (actual subscription events; private fields shortened).

Tool Result state Submitted arguments Observed result
insert_code completed {“content”:“for habitat, rates in sorted(rates_by_habitat.items()):\n print(f"{habitat}: {len(rates)} surveyed sites")”} Inserted unexecuted code cell 385ae2fe-4425-4c05-bd79-f7843fa438e0 in the live notebook model (not saved to disk).
for habitat, rates in sorted(rates_by_habitat.items()):
    print(f"{habitat}: {len(rates)} surveyed sites")

What to remember

Jupyter AI chat can help design or revise code, subject to its agent’s own setup and permissions. nbinlineai questions stay in the notebook and can explain local code and earlier AI turns. Both can touch the same notebook. Avoid simultaneous edits while an inline request is running. The coexistence FAQ explains native Run All, individual Jupyter AI run_cell, API keys, and the limits of the compatibility test.

← Examples guide · Download this notebook