All in One View
Content from Prompting effectively
Last updated on 2026-11-10 | Edit this page
Estimated time: 39 minutes
Overview
Questions
- How does implementing prompting strategies affect the result for research code?
Objectives
- Apply the CLEAR framework for effective prompting.
- Apply introspection to refine code.
- Employ prompt design patterns
Introduction
Helen has received the code and datasets from her colleague, and he has mentioned that his code should be able to run with the three provided datasets. She is aware that the provided code should generate a plot for each dataset.
Challenge 1: Prompt as usual
Write and execute a prompt for running the code in all the datasets.
A possible prompt is:
Hey, I have this code "code.py" and two datasets "data1.csv" and "data2.csv", please write the code to run the code in each dataset.
Notice that you can communicate the same intention in many other ways. Similarly, because the response of these models is not deterministic, you will receive different results even if you use the same prompt in the same model! In our case, using ChatGPT on May 10th, 2026, we received this answer:
PYTHON
import subprocess # List of datasets datasets = ["data1.csv", "data2.csv"] # Run code.py for each dataset for dataset in datasets: print(f"Running code.py with {dataset}...") subprocess.run( ["python", "code.py", dataset], check=True ) print("All datasets processed.")This assumes that
code.pyaccepts the dataset filename as a command-line argument, for example:You can run the launcher script with:
Notice that in the original prompt, we wrote “… write the code to run the code…”, while this is a way of doing it, it already primed the generative model to write a script to write the original code three times.
A small tweak in the prompt can set the model into writing a simpler approach.
Prompt:
Hey, I have this code "code.py" and three datasets "data1.csv", "data2.csv", and "data3.csv", please help me execute the code in each dataset.
AI Response:
If
code.pyaccepts a dataset file as an argument, the simplest way is usually:Or automate it with a small shell loop:
If your
code.pyinstead expects named arguments, it could look like:in which case the loop becomes:
You can also do it directly inside Python:
PYTHON
import subprocess datasets = ["data1.csv", "data2.csv"] for dataset in datasets: subprocess.run(["python", "code.py", dataset])If you paste the contents of
code.py, I can give you the exact command for your specific script.
Notice that the response of the LLM usually finishes by asking for more context, as you continue the conversation it can better tailor its responses, as we will see now with the CLEAR framework.
In groups of three, talk about how you usually prompt.
- What works for you? What errors or mistakes have you caught?
- Did the model’s response improve?
Writing Good Chat Prompts
AI tools work best with context, so it’s good to be as specific and concise as possible.
It’s also a good idea to provide simple questions, so if you end up with a large question that is decomposable into separate steps, ask each step separately and you’ll typically get a better outcome. This implies that it’s good to use a logical, iterative process of using AI to assist, using responses to simple questions to inform the next question, and so on.
There’s a very useful cheat sheet developed by Northwestern University (US) Research Computing and Data Services, which can be found in their GitHub promptEngineering repository.
The CLEAR framework
The CLEAR framework, developed by Leo Lo, provides a structured approach to prompt engineering:
graph LR
C[Concise] --> L[Logical]
L --> E[Explicit]
E --> A[Adaptive]
A --> R[Reflective]
R -->|Feedback Loop| A
style R fill:#bbf,stroke:#333,stroke-width:2px
Effective prompts are concise and logical, prioritizing important information and following a sequence of steps. They are also explicit, specifying the scope, persona, and tone of the output. When the AI produces poor results, be adaptive by rephrasing or splitting tasks. Finally, be reflective—evaluate the output and verify facts using other sources rather than trusting the response.
The quality of AI-generated code depends heavily on how you ask for it.
Challenge 2: Rewrite the prompt
Rewrite the prompt using the CLEAR framework, execute the refined prompt, and compare the model’s response with its previous version.
A possible new prompt is as follows. We added the CLEAR framework stamps for emphasizing its use, but these are not necessary in the final prompt. Prompt:
[C] Concise:
I have a Python script, `code.py`, and two datasets:
`co2_per_capita.csv` and `gdp_per_capita.csv`.
[L] Logical:
I want to execute the code for each dataset.
[E] Explicit:
My colleague said that `code.py` accepts the dataset path as an argument.
Use a beginner-friendly explanation.
[A] Adaptive:
If there is a more scalable or maintainable approach for handling many datasets, include it as an alternative and explain when it would be preferable.
[R] Reflective:
(Wait for the answer and evaluate its output. Check other sources if necessary or refine your prompt and try again.)
Reflection
- How much longer was your refined prompt compared to your first one?
- How much time does it take to write the prompt in comparison to implementing the solution if you know it?
This serves as illustration of the CLEAR framework, but you will tailor your prompts according to your experience and the complexity of your task.
Challenge 3: Minimal-change prompt
Take your refined prompt from Challenge 2 and make the smallest possible change so the model now produces a script that combines multiple CSVs and plots the combined data (e.g., merge CO2 and GDP by country and year, then plot them together). Keep everything else in your prompt unchanged.
One minimal change is to replace the “run for each dataset” line with a “combine and plot” line:
[L] Logical:
I want to load both datasets, merge them by country and year, and plot the combined data in one
figure.
Introspection
The CLEAR framework guides your input, but you can also force the AI to critique its own output. This is often called self-correction.
Emphasize this section. Most learners treat AI output as final. The idea that they can ask the AI to fix its own work is often a new concept. It is like asking a student, “Are you sure you checked your work?”—they often find their own mistakes when asked.
AI models are often better at verifying code than writing it. Never accept the first draft. It is often better to use a different model, or at least a new chat, for the review so the critique is less influenced by the same context that produced the code. Follow up with an introspection prompt:
- “Review the code you just wrote. Are there any edge cases or security vulnerabilities?”
- “Did you hardcode any file paths?”
- “Critique your own implementation. Is there a more efficient way?”
Challenge 4: The introspection loop
Test the AI as a verifier principle. Ask the AI to find flaws in its code before you run it.
- Generate a script — enter this prompt in your chat
Write a script that reads 'gdp_per_capita.csv' and generates a timeseries of the 10 years rolling average for a country that is passed as argument in the terminal. Handle missing values.
- Force introspection: Once the code is generated, do not run it. Follow up in the same session:
Review the script you just wrote. Are there any edge cases (like having fewer than 10 years of consecutive data) where this would fail? If so, provide an updated version.
- Compare: Did the AI find a mistake in its first draft? Did it add a correction?
AI models are often more accurate when asked to critique logic than when asked to generate it. This second pass is part of the editor mindset and reduces manual debugging, but it does not replace a human checking the code to make sure it does the right thing.
Prompt patterns - Plan before you act
As tasks grow more complex, asking the model to write code immediately leads to more rewrite time. The emerging best practice is to request a plan first, review it, and approve it before any files are written.
The think-then-do pattern
Start any multi-step task with an explicit planning prompt:
Before writing any code, describe your approach in numbered steps. Do not write any files yet.
Review the plan, push back on steps you disagree with, and ask for alternatives. Once you are satisfied, say “proceed with step 1.”
Checkpoint prompts
Break large tasks into explicit phases so you review the output at each stage before moving forward:
Step 1 only: read the three CSV files and tell me what inconsistencies you find. Do not write any code yet.
This is especially valuable in research because it catches misunderstandings about your data before they propagate into broken code.
The plan file
For complex projects, ask the model to write a PLAN.md
first:
Write a PLAN.md outlining the steps to clean and merge these files. I will review and edit it before you write any code.
This makes the plan a reviewable, editable artifact — a more formal version of the Bootstrap Workflow. Once approved, refer back to it in follow-up prompts: “Proceed with step 2 from PLAN.md.”
Challenge: Plan before you clean
Practice the think-then-do pattern before moving on to the code cleaning episode. Inside your chat session, type:
I have a script without comments, consistent variable names, and information for the plots it generates. Before writing any code, outline a step-by-step plan for cleaning this file. Do not write any code yet.
Review the plan. Does it include an audit step? Does it address missing values? Revise the plan in the conversation until you are satisfied, then save it by asking: “Write this plan to PLAN.md.”
- An audit step — inspect files before changing them
- A re naming of variables
- A documentation step
- A missing value strategy
- An output verification step
If the model skipped any of these, ask it to revise before you proceed. The goal is to catch gaps in the plan, not in the code.
Challenge: Plan ownership reflection
Write a short reflection (3-5 sentences) on your responsibility when asking a model to plan. Use these prompts:
- What domain knowledge do you need to judge whether a plan is reasonable?
- What parts of the plan would you not be able to critique without that knowledge?
- How would you verify or fill those gaps before letting the model implement the plan?
I need enough domain knowledge to judge whether the steps are valid and complete. Without that knowledge, I would not know if the plan skips a critical audit step or uses the wrong data assumptions. Before implementation, I should consult documentation, run small checks, or ask a subject expert so I can meaningfully critique the plan and adjust it.
There are more patterns that can be used to guide LLMs. See Prompt Pattern Catalog to Enhance Prompt Engineering
Concrete examples: From bad to good
| Aspect | Bad prompt | Good prompt |
|---|---|---|
| Vague vs specific | “Clean this data.” | “In data.csv, remove rows with missing
values in the ‘age’ column and save as
clean_data.csv.” |
| No context vs context | “Write a plot script.” | “I am building a report for a climate study. Write a
Python script using seaborn to create a line plot of ‘temp’ over ‘year’
from results.csv.” |
| Silent vs validated | “Run a t-test.” | “Perform a paired t-test between ‘pre’ and ‘post’ columns. Print the t-statistic, p-value, and an interpretation of the result at alpha=0.05.” |
- Be specific and provide context.
- The better your prompt, the better the result you will obtain.
- Introspection improves code quality.
- Plan before you act: request a numbered plan and approve it before any files are written.
Content from Explain and clean scripts
Last updated on 2026-11-04 | Edit this page
Estimated time: 33 minutes
Overview
Questions
- How do you use an LLM chatbot for explaining code?
- What modifications can change the readability of code without altering its functionality?
Objectives
- Ask for explanations of a snippet of code to a chatbot.
- Analyse the explanations of a chatbot for understanding the snippet.
- Adapt the script to improve its clarity, modularity, and reusability.
A browser-based LLM chatbot is a low-friction way to understand unfamiliar code, but the responsibility for understanding and verification stays with you. If you cannot explain the code to a colleague, you should not rely on it. To manage cognitive load when a chatbot produces long explanations, anchor your understanding by reading the code alongside the explanation and testing small parts when something is unclear.
In general, attempting to understand a new codebase, whether it’s your first week on a project or one you have inherited from another source, can be difficult. This can be due to many reasons; documentation may be incomplete, architectural decisions may be undocumented, and the people who know the system may be unavailable or have left the organisation.
We can use a chatbot to build our understanding and confidence about our codebase by asking natural-language questions about the code. It helps you:
- Build a high-level mental model of the system, which with complex codebases is often a huge task!
- Identify where key functionality is located in the code
- Understand naming conventions, patterns, and dependencies
- Reduce the cognitive load of first contact with unfamiliar code
Sounds great, but…
It’s important to understand that no LLM is an absolute source of truth, but more of a guide to help build your own understanding of a codebase.
Asking for explanations
Now that Helen has been able to execute the code to generate the plots, she wants to understand and clean the script. Even though the code executes without errors, Helen struggles to understand what each section is doing.
Let’s use an LLM to help us investigate how our existing script works.
- Open
files/code/code.py, copy the script, and paste it into your browser chatbot. - Ask for a high-level explanation first, then a line-by-line
walkthrough. For example:
Explain what this script does, the expected input and output files, and any assumptions it makes. Then walk through each block of code. - Follow up on anything unclear. Good follow-up prompts include:
Can you explain what line 5 is doing with the transpose?andWhat does line 15 do to missing values? - Verify the explanation against the code. Write a short summary in your own words that describes the inputs, processing steps, and outputs.
Analyzing the explanation
- Identify two statements in the chatbot’s explanation and point to the exact lines in the script that support them.
- Find one place where the explanation is vague or makes an assumption (inputs, outputs, or edge cases). Ask a follow-up question to clarify.
- Note one potential risk or gap in the explanation (for example, handling missing values or unexpected columns).
- Write a short evaluation (2–3 sentences) of how trustworthy and complete the explanation is, based on your checks.
Cleaning the script
- Ask the chatbot for a refactor that improves readability and
modularity without changing behavior. Example:
Refactor this script to improve readability and modularity. Keep the same inputs, outputs, and libraries. Do not change behavior. - Apply small, safe changes only. Typical improvements include:
- Move all imports to the top of the file.
- Rename variables (
d,x,y0) to meaningful names. - Extract repeated logic into functions (loading data, computing series, plotting).
- Add a short module docstring describing what the script does.
- Compare the refactored version to the original. If you can run the script, generate the plot with the same input and confirm the output is unchanged.
Challenges
Challenge 1: Verify a refactor
Ask the chatbot to refactor the script. Pick two changes it suggests and explain how you would confirm that each change did not alter the script’s behavior.
Compare outputs on the same input (e.g., run both versions and compare the plot), and review the diff to ensure only structural changes were made (renames, function extraction, and docstrings) without altering calculations or file outputs.
Challenge 2: Mitigate risks
List three practices that reduce risk when accepting chatbot-driven refactors.
- Keep prompts specific and scope-limited.
- Review and understand every suggested change before accepting it.
- Compare outputs against the original version
- Re-run available tests if they exist, if none exist, add them.
- Ask for explanations before you reuse or modify code, and verify them against the source.
- If you cannot explain the code to a colleague, do not trust it.
- Keep refactors small and behavior-preserving; modular, readable code is easier to verify.
- Reduce risk by keeping prompts specific and confirming outputs after changes.
Content from Write and validate scripts
Last updated on 2026-11-04 | Edit this page
Estimated time: 34 minutes
Overview
Questions
- How do IDE-integrated AI assistants like GitHub Copilot work?
- What information is sent to remote servers when I use these tools?
- How can I configure these tools to balance productivity and privacy?
- How do I move from vibe coding to research orchestration?
- How can I use one AI to catch the errors of another?
Objectives
- Compare the functioning, scope, and risks of the IDE integrated LLM in relation to the chat-based LLM.
- Choose a generative AI tool for writing code according to the task.
- Write a snippet of code using generative AI directly in the IDE.
- Validate AI generated scripts using a critical framework (that the AI is doing the right thing)
- Understand how IDE-integrated AI assistants process your code
- Learn to configure GitHub Copilot and similar tools
- Recognize the reduced transparency compared to chat-based approaches
- Develop habits for reviewing inline suggestions critically
- Shift from a writer to an auditor mindset using the approval gate.
- Use a four-layer validation stack with explicit requirement constraints.
- Use multi-model verification to peer-review research code.
Introduction
Helen has cleaned the inherited script and now wants to extend it with a sensitive survey dataset. She needs to merge country-level environmental and economic concern data with CO2 and GDP per capita, and plot two new scatter plots. She shifts from chat-based prompting to an IDE-integrated assistant, but to do this safely, she decides to do this only after sandboxing the project and restrict what the tool can see.
The new file, survey_participants.csv, contains
information about 100 researchers with direct identifiers (names and
emails), demographics (age, gender, nationality, institution,
department, income band), and survey responses on AI tools, data
sharing, open science, and concern levels.
The IDE integration scenario
In this scenario, AI assistance is integrated directly into your development environment. As you type, the AI suggests completions, entire functions, or even multi-line code blocks.
Generative AI has the potential to transform how researchers work with code, and with the integration of such capability within common IDEs, such as Visual Studio Code, provide the coding researcher with powerful tools to modify, expand and otherwise work with code. But this potential needs to be tempered with critical thinking and a healthy degree of skepticism.

Common tasks and features
AI coding assistants in IDEs (such as GitHub Copilot) provide a bewildering array of support for various tasks. For code editing, these include:
- Code completion and generation - suggests and generates code snippets based on context, reducing time spent on boilerplate and repetitive code
- Function and method suggestions - proposes complete function implementations based on function signatures and docstrings
- Refactoring support - suggestions for improving code structure and readability
At a higher level, they can also provide:
- Code explanation - explains how existing code works, helping researchers understand unfamiliar code or learn new programming patterns
- Debugging assistance - identifies potential bugs and suggests fixes for problematic code
- Documentation generation - automatically generates comments, docstrings, and README content
- Test generation - creates unit tests for existing code to improve code reliability
- Language/framework translation - converts code between programming languages and frameworks
Such tools can also assist with writing new code, helping to structure projects and write new functionality by generating code based on high-level descriptions, function signatures, and requirements. These initial implementations are then reviewed and refined by developers.
Benefits and risks
AI coding assistants can accelerate development by reducing time spent on routine coding tasks, allowing researchers to focus on domain-specific problems. For those new to a programming language, these tools help lower the learning curve and enable faster productivity. The suggestions and examples provided by AI assistants may also encourage better coding practices and improve overall code quality, including documentation.
However, they also introduce significant risks:
- Correctness and validation - generative systems optimize for likelihood, not correctness. AI-generated code can sound confident but be incomplete, incorrect, or insecure. Researchers remain fully responsible for validating outputs.
- Limited explanation - unlike a standalone AI like ChatGPT, IDE-integrated AI often provides suggestions without detailed reasoning. This can reduce researchers’ understanding of AI-generated code.
- Potential over-reliance - it can be very tempting to accept AI code suggestions that appear to work without fully understanding them.
- Privacy and security risks - the AI may send code snippets to cloud services for processing. Sensitive data or unpublished research could be exposed if this is not carefully managed.
- Context and edge cases - AI assistants may miss domain-specific requirements, edge cases, or research-specific constraints that are critical for correctness.
- Code quality - generated code may work but be inefficient, poorly structured, or violate best practices, degrading long-term maintainability.
How this differs from chat-based coding
| Aspect | Chat-based (Scenario I) | IDE-integrated (Scenario II) |
|---|---|---|
| Data flow | You explicitly paste code | Context sent automatically |
| Visibility | You see exactly what you share | Less clear what’s transmitted |
| Execution | Manual copy/paste | Still manual, but faster |
| Context | Limited to what you provide | May include entire project |
What information leaves your machine?
When you use IDE-integrated tools, data transmission happens automatically and continuously. Understanding what’s sent is crucial.
Typically transmitted data
| Data Type | Purpose | Privacy Concern |
|---|---|---|
| Current file content | Generate relevant suggestions | May contain sensitive code |
| Open file tabs | Broader context | More exposure |
| File paths | Understand project structure | Reveals project organization |
| Cursor position | Know what to complete | Minimal concern |
| Recent edits | Understand your intent | Sent frequently |
What may be transmitted (tool-dependent)
- Other files in your workspace
- Git history
- Comments and docstrings
- Import statements (revealing your dependencies)
:::{callout} Read your tool’s documentation Each tool has different data collection policies. For example: - GitHub Copilot transmits code context to GitHub/Microsoft servers - Some tools offer “local only” models (e.g., Tabnine) - Enterprise tiers may offer data isolation guarantees :::
Setting up GitHub Copilot
GitHub Copilot is currently the most widely-used IDE-integrated assistant. Here’s how to set it up with privacy and control in mind.
GitHub Copilot integrates directly into Visual Studio Code as an extension installable from within the IDE, providing access to:
- On-request explanations - allowing you to obtain responses to questions in a chat interface
- Real-time assistance as you continue to develop your code - where Copilot continuously analyzes the code you write, as well as comments and surrounding context, to offer intelligent suggestions which require approval.
- On-request direct code modification - by requesting specific changes, your code is modified directly by Copilot (again, requiring specific approval before it integrates the suggested changes)
All of this is integrated into the VSCode editor, so you do not need to leave your development environment.
The lifecycle of a Copilot prompt
So how does Copilot integrate with VSCode, and how does it handle data? Let’s look at how it creates a code suggestion as an example:
At a high level, the following steps are followed:
Within the Copilot-enabled IDE:
- Developer enters text into code editor, such as VSCode, gathering context from a number of sources (code before and after cursor, file name and type, other open editor tabs)
- The prompt is constructed from the amassed context and sent to the Copilot proxy
Within the Copilot proxy (within the “Cloud”):
- Filters the requests, terminating those involving toxic language, unrelated code requests, and perceived hacking attempts.
- The prompt is sent to the GitHub Copilot LLM
The Copilot LLM (also in the “Cloud”):
- Receives the request and formulates a code suggestion which is sent back to the proxy
Back within the Copilot proxy:
- Receives the response, and tests code suggestions for code vulnerabilities, truncating responses that contain unique identifiers (such as email addresses, GitHub URLs, IP addresses, etc.), and filters out those matching known public code. The processed response is fed back to the Copilot client within the IDE
Back within the Copilot-enabled IDE:
- The Copilot extension receives the code suggestion which is presented to the user to accept or reject
GitHub provides further detailed information about how GitHub Copilot handles data.
Installation in VS Code
- Install the “GitHub Copilot” extension from the marketplace
- Sign in with your GitHub account
- If you have an educational email, you may qualify for free access
Key configuration settings
Open VS Code settings (Ctrl+, or Cmd+,) and search for “Copilot”:
JSON
{
// Disable automatic suggestions (require manual trigger)
"github.copilot.enable": {
"*": true,
"markdown": false, // Disable for documentation
"plaintext": false // Disable for plain text files
},
// Require explicit trigger instead of automatic suggestions
"editor.inlineSuggest.enabled": true,
// Control which files Copilot can access
"github.copilot.advanced": {
"indentationMode": {
"python": true,
"javascript": true
}
}
}
Disabling AI assistend coding for sensitive files
Ideally, there would be an equivalent of .gitignore so
that certain files are never sent to remote end-point (e.g. secrets,
credentials, sensitive data). Some tools support this type of control,
but with GitHub copilot “Content
exclusion is available only with a GitHub Copilot Business or a GitHub
Copilot Enterprise subscriptions.”.
For a recent survey of other tools and their ignore settings, see this link.
An alternative is to run VScode inside a container so that only certain folders of the file system are visible, and secrets can be separated.
The hidden context problem
A key difference from chat-based AI is that you don’t explicitly control what context the model receives. This has implications:
Example: Unintended context sharing
flowchart TB
accTitle: {A short figure title}
accDescr: {A longer description of the figure, highlighting important elements}
A["main.py<br/>(you're here)"]
B["config.py<br/>(open tab)"]
C["secrets.env<br/>(open tab!)"]
D["All may be sent as context"]
A --> D
B --> D
C --> D
style A fill:#6f9fc2,stroke:#000,stroke-width:2px,color:#000
style B fill:#8db1ca,stroke:#000,stroke-width:2px,color:#000
style C fill:#d96666,stroke:#000,stroke-width:2px,color:#000
style D fill:none,stroke:none,color:#000,font-size:20px
The issue: You might have a secrets file open in another tab, and parts of it could be included in the context sent to the AI server.
Mitigation strategies
- Close sensitive tabs when using AI completion
- Use sandboxing / containerization to exclude sensitive files
- Consider workspace separation - keep sensitive projects in different VS Code windows
- Review your open tabs before intensive AI-assisted sessions
- Compression of the context some tools (e.g. Claude code) or some extensions can compress what goes to the context window so that not all the files need to be sent to remote for synthesising new code.
Sandboxing options for sensitive data
When sensitive data is involved, decide upfront how to isolate files and control access. The goal is to limit what an IDE assistant can read while keeping a workable development flow.
Option 1: Container-based sandbox (recommended)
Run VS Code in a container and mount only the project folder you want the assistant to access. Keep sensitive files in a separate directory that is not mounted.
[Placeholder: Add Docker-based setup steps and a minimal
devcontainer or run command.]
Option 2: Local isolation without Docker
Create a dedicated project folder that contains only the code and non-sensitive datasets. Keep the sensitive survey data in a separate location and copy in only the columns needed for analysis.
[Placeholder: Add OS-specific steps for creating a clean workspace and copying inputs.]
Checklist before you start
Before you write a single line of code, make three explicit decisions:
- Which programming language?: Python (this workshop). The most popular language for data science; enormous library ecosystem; runs everywhere.
- Where will the computation run?: Your laptop, your organisation’s cloud, or an external cloud service. See the next section.
- Where does your data live?: Local disk, institutional storage, or a public URL. This matters especially if the data is sensitive or personal.
The “where” question is more important than it first appears. It affects data confidentiality, ease of setup, and whether your workflow will still work in six months when a cloud service changes its terms.
The geography of computing
Every time you run code, the computation happens somewhere. There are three broad categories:
[Placeholder: Insert the diagram from workshop-data-viz showing local, org cloud, and external cloud trade-offs.]
| Environment | Examples | Advantages | Considerations |
|---|---|---|---|
| Local laptop | Your own machine, Python installed | Data never leaves your hands; works offline; full control | Risk if device is lost/stolen; requires manual installation; limited RAM/CPU |
| Organisation cloud | Aalto JupyterHub (jupyter.cs.aalto.fi), CSC Noppe
(noppe.csc.fi) |
Institutional data protection; software pre-installed; no personal hardware risk | Depends on institution’s uptime and quota; requires account |
| External cloud | Google Colab, Kaggle Notebooks | Zero installation; free tier available; easy to share | Unclear or unfavourable terms of service; data uploaded to third party; may not be suitable for sensitive data |
If you are working with real research data – especially personal data, clinical data, or anything covered by your institution’s data management plan – check with your data protection officer or IT security team before choosing an environment. External cloud services (including Google Colab and GenAI tools) are generally not suitable for sensitive or personal data.
Choosing a GenAI assistant
There are three categories of GenAI coding assistant, differing mainly in where the computation runs:
[Placeholder: Insert the diagram from workshop-data-viz showing local, org, and external GenAI options.]
| Option | Example | Notes |
|---|---|---|
| Local (on your machine) | llama.cpp | Fully private; no data leaves your computer; requires a capable GPU
or CPU; setup is non-trivial. See
{doc}appendix-local-llms. |
| Organisation’s GenAI | ai.aalto.fi (Aalto only) | Complies with institutional data policy; recommended for sensitive work |
| External cloud | ChatGPT, Gemini, Claude | Easy to access; generally free tier available; review the provider’s privacy terms before use |
Do not paste real personal data, clinical data, or any data covered by a confidentiality agreement into an external GenAI tool. The text you submit is typically used to improve the model or stored on the provider’s servers.
The approval gate: verification over generation
In an agentic research workflow, your role is to audit and approve code rather than write it. The standard has shifted from vibe coding to spec-driven orchestration.
The approval gate is the point where you decide AI-generated code is robust enough for research production. It separates a working prototype from validated science.
The review-first standard
The bottleneck in research is no longer writing code; it is verifying it. A high-performance workflow follows this cycle: Plan -> Agent Implementation -> Automated AI-Powered Testing -> Human Review.
Measuring efficiency: rewrite time
Rewrite time is a metric to determine if an AI workflow is actually helping your research.
- Definition: The manual effort in minutes a researcher spends making AI-generated output production-ready.
- Goal: If you spend 20 minutes prompting but then 40 minutes fixing the code, your rewrite time is too high.
Challenge: calculate your rewrite time
Look back at a script you recently generated with an AI agent. 1. How many minutes did you spend fixing or refactoring the code to make it run? 2. If this took more than 10% of the total task time, what was the likely cause? - Ambiguous specs? - AI over-confidence? - Lack of local context?
The four-layer validation stack
To minimize rewrite time and ensure research rigor, use a structured validation stack.
Layer 1: Requirement constraints (No-Go Zones)
Before the AI writes code, define requirement constraints in your
AGENTS.md. These are rules the AI is not allowed to
break.
Example: “Do not change the column names in
raw_data.csv” or “Use only base R for this visualization to
ensure compatibility.”
Layer 2: Automated unit tests
Ask the agent to write tests before the implementation. Use a prompt pattern like: “First, write five Pytest cases that define the success of this data cleaning script. I will approve the tests before you write the logic.”
Multi-model verification
We use a challenger model to audit an implementation model rather than trusting a single AI.
Challenge: orchestrate a peer review
Use Model A (such as Claude Code or Cursor) to generate a data cleaning script.
-
Provide the code to Model B (such as Gemini CLI) with the following prompt:
“Read this script. Act as a skeptical senior data scientist. Identify three potential edge cases where this script will fail, such as empty strings, NaN values, or encoding issues. Suggest specific assert statements to catch these.”
Reflect: Did the challenger model find something the implementation model missed?
Models have different blind spots. Forcing a second AI to act as an auditor helps bypass the tendency of the primary assistant to be over-confident. This process reduces your manual rewrite time.
Warn learners about approval fatigue the tendency to accept AI suggestions without reading them. The four-layer stack is designed to make the AI prove it is correct before you review the code.
Episode exercise: sensitive dataset integration
[Placeholder: Add exercise text instructing learners to expand the script to read the sensitive survey dataset and plot two scatter plots: environmental concern vs CO2 per capita (country-level), and economic concern vs GDP per capita (country-level). Include IDE assistant prompts and validation steps.]
- The approval gate separates experimental prototypes from validated research.
- Rewrite time is the primary metric for measuring AI workflow value.
- Requirement constraints prevent the AI from drifting away from research specs.
- Multi-model verification uses a second AI to act as a skeptical peer reviewer.
Content from Testing and refactoring scripts
Last updated on 2026-11-04 | Edit this page
Estimated time: 44 minutes
Overview
Questions
- How to safely extend the functionality of a working script?
- How do I make sure that my code is still working when its size grows?
- How do I restructure my code so that it is readable, modular and reusable?
Objectives
- Develop a suite of tests that checks the correct functioning of the generated code.
- Evaluate the quality of the tests.
- Extend the functionality of the generated code by devising a plan and using test driven development.
- Modify the structure of the generated code to improve its quality without breaking its functionality.
Introduction
Helen has succesfully extended her script to include her survey. Nevertheless, the original script has grown. Even though it has more functionality, it will be difficult to maintain and make sure that new changes do not break old behaviour. Consequently, Helen has decided to invest some time in writing some tests and refactoring her code.
Testing code
Start with a minimal pytest suite for the Episode 3 script. Identify the script’s core behaviors, create a small set of fixtures (sample inputs and expected outputs), and write tests that verify those behaviors. Run the tests from your IDE or the terminal to establish a reliable baseline before you make any changes.
Challenge 1: Build the first test suite
Create at least three tests for the Episode 3 script that confirm it produces the expected outputs for typical inputs and handles at least one error case. Keep the tests small and focused on behavior, not implementation.
One possible suite is: 1. a “happy path” test that checks a known input produces a known output, 2. a test that verifies the script rejects missing or malformed inputs, and 3. a test that asserts the output shape or key summary statistics remain stable.
Evaluating test quality
Good tests are specific, deterministic, and fail for the right reasons. Look for tests that are easy to understand, cover critical branches, and guard against regressions without being so brittle that they fail on harmless refactors.
Challenge 2: Evaluate test quality
Review your tests and note one improvement you could make to increase their reliability or coverage. Then update the suite to implement that improvement.
Common improvements include: 1. adding a fixture to reduce repeated setup, 2. asserting on precise outputs rather than vague checks, or 3. adding a test for a boundary case you identified during review.
Test-driven development (TDD)
With TDD, you define the behavior first, watch the test fail (red), implement the minimum code to pass (green), and then refactor while keeping the tests green.
Challenge 3: Extend the script with TDD
Choose a small feature for the Episode 3 script, such as a new command-line option or an additional summary statistic. Write a failing test first, implement the feature to make the test pass, and then refactor if needed.
A solid TDD loop includes: 1. writing a test that captures the new behavior, 2. implementing the smallest change that makes the test pass, and 3. cleaning up the code while re-running the test suite to confirm nothing regresses.
Refactoring code
Why modular development matters even more with AI
When you generate code in small, testable pieces:
- You can verify each piece works before moving on
- Errors are easier to localize and fix
- You maintain understanding of what each part does
- The AI has clearer context for each request
Refactor without breaking behavior
Refactoring is safest when you make one small change at a time and keep the tests passing. Break the script into small functions, then into modules if needed, and run the test suite after every change.
Challenge 4: Refactor with confidence
Split one large function or block of the Episode 3 script into two or more functions. After each small change, run the tests and fix any failures before moving on.
A common approach is to extract pure functions first, then move I/O into a thin wrapper. If the tests stay green at each step, the refactor preserved behavior.
Content from Guiding agents from script to codebase
Last updated on 2026-11-04 | Edit this page
Estimated time: 52 minutes
Overview
Questions
- How do agentic tools help move from a script to a shareable codebase?
- How do you supervise agent work with specs, plans, and Pull Request reviews?
- How do you reduce risk with sandboxing and permission controls?
Objectives
- Explain how agentic AI coding tools work.
- Relate identified risks of agentic methods to practical safeguards that mitigate them.
- Make use of version control by implementing Git and GitHub.
- Implement supervision strategies for AI agents in coding tasks.
- Use sandboxing and permission controls for safeguarding agent actions.
- Create a Living Spec (AGENTS.md) to guide an agent.
- Extend the functionality of the script to convert it into a structured research codebase.
Introduction
Helen has turned a growing script into multiple files with a test suite, but it still lives on her laptop. Her team wants a shareable codebase with documentation, licensing, and collaboration workflows. She now works on a remote Linux server with only a terminal, so she uses a CLI agent and Git to scale the work safely.
This episode focuses on agentic workflows: define a spec, approve a
plan, execute in small branches, and review changes before they land on
main.
A safe default for agentic work
Start with the smallest possible permissions, a clear spec, and a
plan you approve. Make changes in branches, not directly on
main.
The agentic workflow
An agent is most useful when you give it a clear target and enforce a review gate:
- Spec: Capture the goals, constraints, and data sensitivity in a Living Spec.
- Plan: Ask the agent for a plan and edit it before work begins.
- Branches: Each task is done in a small branch.
- Review: Open a pull request (PR), review changes, and merge only when checks pass.
Create a Living Spec (AGENTS.md)
A Living Spec is a short file that tells the agent what it can and cannot do. It should include purpose, scope, data constraints, and what counts as “done.”
Example outline:
# Living Spec
- Purpose: Describe the research question and expected outputs.
- Scope: List the modules/files the agent may change.
- Data sensitivity: Explain any sensitive datasets and access rules.
- Quality checks: Tests to run or outputs to verify.
- Collaboration rules: Branch + PR workflow, no direct commits to main.
Challenge 1: Draft a Living Spec
Create a short Living Spec for this project. Include at least: purpose, scope, data handling rules, and a review rule (e.g., “all changes must go through PRs”).
A good spec is brief and explicit: it names the project goals, lists the files the agent may change, explains how to handle sensitive data, and sets a review gate (branch + PR).
Plan before executing
Before you let the agent make changes, ask it to draft a plan and break the work into small tasks. You should edit the plan to make sure each task is reviewable on its own.
Challenge 2: Plan and task breakdown
Ask the agent for a plan to add a README, CONTRIBUTING guide, LICENSE, and requirements file. Edit the plan so each item is a separate task that could be reviewed in a single PR.
A clean plan typically splits into 3-5 tasks: README, LICENSE, CONTRIBUTING, environment or requirements, and a short tutorial or example. Each task maps to a branch and PR.
Branching and PR-based supervision
Git is your supervision tool. You can keep the agent productive while still controlling quality by requiring small branches and reviewable PRs.
Suggested branching pattern:
docs/readmedocs/contributingchore/licensebuild/requirementsdocs/tutorial
Challenge 3: Build a PR checklist
Write a short PR checklist you will use to review agent changes. Include at least: scope alignment, tests or checks, and documentation quality.
A minimal checklist includes: the PR matches the spec, tests (if any) pass, and the new docs are clear and consistent with the rest of the repo.
Safeguards: permissions, sandboxing, secrets hygiene
Agentic tools are powerful because they can read and change files. Keep risk low by using the smallest possible scope:
- Permissions: start read-only and expand only if needed.
- Sandboxing: keep sensitive data inside the workspace.
- Secrets hygiene: never provide tokens or credentials to the agent.
- Audit trail: use branches + PRs so every change is visible.
Challenge 4: Add a safeguard
Identify one risky agent action in your workflow and add a safeguard that prevents it.
For example, if the agent might edit files outside the project, restrict the scope to specific folders and require PR reviews before merging.
- Agentic workflows are safest with a spec, a plan, and PR-based review gates.
- Living Specs clarify goals, limits, and data constraints for the agent.
- Permission scoping, sandboxing, and secrets hygiene reduce risk without blocking progress.
Content from Reflecting and contributing
Last updated on 2026-05-09 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How do you write a lesson using Markdown and sandpaper?
Objectives
- Summarise the different generative AI tools, their scope, uses and precautions for its safe use.
- Compare your experience on the use of these tools with the experience of other users in the past.
Introduction
Reflect on what you learned and share your experience with your peers!
Content from Resources and next steps
Last updated on 2026-05-09 | Edit this page
Estimated time: 17 minutes
Overview
Questions
- What other tools are available?
Objectives
- List alternative AI coding tools.
Introduction
Design Apps Research agents