25  Working with AI in Your Workspace

Class Objectives
  1. Understand the limitations of traditional web-based chatbots (the copy-paste bottleneck and lack of context).
  2. Explore the Antigravity IDE and understand how workspace-integrated AI editors differ from basic chatbots.
  3. Configure R integration inside the Antigravity IDE, including installing extensions and specifying path configurations.
  4. Master the primary AI interaction panels: Workspace Chat (Cmd+L) and Inline Edit (Cmd+K).
  5. Learn how to select and swap models based on the programming task at hand.

25.1 The Landscape is Shifting (And So Must You)

If you had taken this class last year, this chapter would not have existed. Or rather, it would have looked like science fiction. Last year, generative artificial intelligence was largely a novelty for code generation—a fancy autocomplete that you consulted in a browser tab. Today, it is an active partner sitting right inside your editor.

And let’s be clear: by the time next year’s students read this, the landscape will have shifted yet again.

This means your goal today isn’t to memorize a specific set of button clicks or commands. The technology is moving too fast for that. Instead, you need to learn how to think about this new paradigm—how to adapt to a workspace where code, data, and intelligent assistance are fully integrated.


25.2 From Isolated Chatbots to Workspace-Integrated Partners

Let’s start by looking at where we’ve been. In the early days of generative AI, the standard way to get help writing code was the web browser chatbot. You opened a window, typed a prompt, and got some code back.

It worked, but it was incredibly inefficient. It introduced what we can call the copy-paste bottleneck.

25.2.1 The Copy-Paste Bottleneck

To debug a broken R script using a web chatbot, your workflow looked something like this:

  1. You write a script. It crashes.
  2. You select the script, copy it.
  3. You select the R console error message, copy it.
  4. You switch to your browser, paste both into the chat.
  5. You read the AI’s solution, copy the suggested fix.
  6. You switch back to your editor, paste the fix.
  7. You run it. It crashes again.
  8. You repeat the process.

This is a clunky, linear, and error-prone dance. It’s the programming equivalent of writing a letter, mailing it to a consultant across town, and waiting for a reply to fix a typo.

25.2.2 The Blind Assistant Problem

Even worse than the copy-paste bottleneck is the lack of context.

A web chatbot operates in a vacuum. It doesn’t know anything about your project unless you manually feed it. It cannot see your other project files, read the column headers of the dataset you just imported, check your .gitignore, or know which R packages are installed in your active environment.

graph TD
    subgraph Traditional Web Chatbot
        Browser[Web Browser Chat UI] -->|Copy Fixes| Editor[Local Text Editor]
        Editor -->|Copy Code & Errors| Browser
        Browser --x|❌ No access to| Filesystem[Project Filesystem & Console]
    end
    linkStyle 2 stroke:#dc3545,stroke-width:2px;


25.3 Introducing the Antigravity IDE

The Antigravity IDE is a modern, workspace-integrated development environment designed specifically to resolve these issues. Unlike standard text editors, it natively integrates a conversational AI assistant that has real-time awareness of your active files, folders, terminal, and overall project structure.

Alternative Tools & Educational AI Access

While we use the Antigravity and Antigravity IDE in this course, it is far from the only workspace agent available. Excellent alternatives include Anthropic’s Claude Code and OpenAI’s Codex.

In this class, we primarily use the Antigravity because Google’s developer ecosystem typically offers much more generous free tiers or education-friendly resource allocations for students, making it the most accessible entry point for learning workspace-integrated coding.

Rather than forcing you to act as a copy-paste courier, the assistant works beside you:

  • In-Place Edits: The assistant doesn’t just print code blocks for you to copy; it proposes direct, surgical edits to your files. You see a clear visual diff (green for additions, red for deletions) and can accept or reject them with a single click.
  • Terminal Awareness: The assistant can run tests, execute scripts, and observe the terminal output. If a test fails, the agent sees the error immediately and refactors its own solution.
  • Project Indexing: The assistant scans and indexes your entire project folder. It understands your existing functions, style, and dependencies before making suggestions.

graph TD
    subgraph Workspace-Integrated Agent
        User[Scientist] -->|Approve Actions| IDE[Antigravity IDE]
        IDE -->|Show Diffs| User[Scientist]
        IDE -->|Write Edits| Files[Project Files & Docs]
        Files -->|Read Context| IDE
        IDE -->|Execute Commands| Console[Terminal Console]
        Console -->|Read Logs| IDE
        IDE -->|Ground Context| Agent[AI Assistant]
        Agent -->|Propose Actions| IDE
    end


25.4 Setting Up R in the Antigravity IDE

To leverage the full power of the Antigravity IDE when writing code for this course, you must configure R integration. This ensures that the IDE can highlight R syntax, run interactive R consoles, and verify R script executions. For comprehensive details on setting up R in VS Code-based editors (which Antigravity IDE is based on), please refer to the VS Code R Documentation.

25.4.1 Install the R and Quarto Extensions

  1. Open the Extensions marketplace view in the IDE (by clicking the Extensions icon on the left sidebar or using the keyboard shortcut Cmd + Shift + X on macOS or Ctrl + Shift + X on Windows).
  2. Search for the extension named R and Quarto.
  3. Click Install.

If R is installed in a non-standard location, or if the extension cannot find R automatically, you must manually specify the path to your R executable:

  1. Open the Settings panel (Cmd + , on macOS or Ctrl + , on Windows).
  2. Type r.rpath in the search bar.
  3. Locate the setting corresponding to your Operating System (e.g., Rpath: Mac or Rpath: Windows).
  4. Set the value to the absolute path of your R executable:
    • macOS (Homebrew): /opt/homebrew/bin/R
    • macOS (CRAN): /usr/local/bin/R
    • Windows: C:\Program Files\R\R-4.x.x\bin\x64\R.exe (replace 4.x.x with your actual R version).
    • Linux: /usr/bin/R

25.4.2 Install the Language Server

To enable features like code completion, definition hover tooltips, and code formatting within the IDE, you should install the languageserver package:

install.packages("languageserver")

While the default R terminal works, we highly encourage you to install and use radian: a modern R console that corrects many limitations of the official R terminal and supports advanced features such as syntax highlighting, multiline editing, and auto-completion. * To install: Install radian on your system via Python (usually by running pip install -U radian or conda install -c conda-forge radian in your system terminal). * To configure: In Settings (Cmd + , or Ctrl + ,), search for r.rterm and set the path setting for your operating system to point to the radian executable path (e.g. /usr/local/bin/radian or /opt/homebrew/bin/radian on macOS).

25.4.3 Install httpgd for Interactive Plotting

httpgd is an R package designed to provide a graphics device that asynchronously serves SVG graphics via HTTP and WebSockets. This package is required by the interactive plot viewer of the R extension for VS Code to render high-quality, responsive plots directly inside your editor pane rather than opening external windows.

To install it:


25.5 Selecting and Switching Models

No single AI model is perfect for every task. The Antigravity IDE allows you to choose which model powers your Workspace Chat and Inline Edit sessions.

25.5.1 Choosing a Model in the UI

At the bottom of both the Cmd + L chat panel and the Cmd + K input box, you will find a Model Dropdown menu. Clicking it lets you switch between available models (this can change very fast!):

  • Gemini 3.1 Pro: Google’s premier reasoning model, offering a massive context window (up to 2 million tokens) and excellent logical reasoning, making it ideal for answering questions about large codebases or complex documentation.
  • Gemini 3.5 Flash: Google’s fast and highly efficient model, optimized for quick code completions, formatting, and real-time conversation.
  • Claude 3.6 Opus: Anthropic’s flagship reasoning model, highly optimized for precise syntax generation, structural refactoring, and complex programming tasks.
Connecting Local Models (via Ollama)

If you wish to run models locally on your own computer (e.g. for complete offline access or data privacy), you can run models like Google’s Gemma or Meta’s Llama using Ollama:

  1. Install Ollama and run a model in your terminal (e.g., ollama run gemma2).
  2. Open settings in the Antigravity IDE, search for Ollama, and check the box to enable local model provider integration.
  3. You can now select your local model from the model dropdown and prompt it directly.

25.6 Interacting with the Workspace AI: Chat vs. Inline Edit

The Antigravity IDE provides two primary interfaces to interact with the AI assistant. Knowing when to use which is the key to a productive workflow.

25.6.1 Workspace Chat (Cmd + L)

Pressing Cmd + L (or Ctrl + L on Windows) opens the Workspace Chat panel in the sidebar.

  • Best for: Explaining code blocks, asking conceptual questions, discussing project architecture, or writing documentation from scratch.
  • Workspace Context: The chat has access to your active file. You can also explicitly draw attention to other files or directories in your workspace by using @ references (e.g. @README.md or @R/analysis.R).

25.6.2 Inline Edit & Generation (Cmd + K)

Pressing Cmd + K (or Ctrl + K on Windows) opens a small prompt box directly above your cursor.

  • Best for: Making precise, surgical changes to a specific file in-place, or generating a new function directly in your script.
  • How it works:
    1. Highlight the block of code you want to edit (or place your cursor where you want new code generated).
    2. Press Cmd + K.
    3. Type your instructions (e.g., “Refactor this loop using purrr::map or “Add error validation to check if inputs are positive”).
    4. Press Enter. The AI will generate a visual diff directly in your file (green for additions, red for deletions).
    5. Review the diff. Click Accept (Cmd + Enter) to keep the edits, or Reject (Esc) to discard them.

25.7 Managing Context: Context Windows and Prompt Caching

To make smart suggestions, an AI needs context. Modern large language models feature massive “context windows” (up to 2 million tokens).

Think of a context window as the size of the desk the AI works on. Early models had tiny desks; they could only look at one file at a time. Today’s models have massive desks where you can spread out your entire codebase, your data dictionaries, your README files, and your entire Git history.

But reading that entire desk of papers every time you ask a question is slow and computationally expensive. This is where Prompt Caching comes in. The system stores the background files in active memory. When you ask a question, the model doesn’t reread the whole desk; it only reads your new question and references the cached documents. The result is lightning-fast, highly context-aware assistance.

Going Local: Running Models on Your Own Machine

While cloud-based models are highly capable, you also have the option to run open-weight models (like Google’s Gemma or Meta’s Llama) locally on your laptop using tools like Ollama. While these local models are smaller and not yet as powerful as cloud giants, they are completely free, run offline, and keep all your code and data 100% private.


25.8 Directing Attention: Workspace Context with @ References

To get the most out of a workspace assistant, you must learn to direct its attention. You don’t need to write long paragraphs describing your file structure. Instead, you use @ references to point at exactly what the assistant should look at.

  • @filename: Embeds a specific file’s content directly into the conversation. For example: “Read @data_summary.csv and write an R script to plot the trend.”
  • @terminal: Feeds the recent console logs to the assistant. Useful when you get a cryptic compilation error and want the AI to diagnose it.
  • @folder: Supplies the structure of a directory, letting the assistant find where specific functions or datasets are located.

Or even easier, you can just drag the file or the folder to the chat panel or the inline edit box, and it will be automatically referenced.

By using these references, you keep your queries precise and prevent the AI from generating generic, irrelevant code.


25.9 Example: An R Function to Calculate Species Diversity (Hill Numbers)

To understand how a workspace AI assistant can help us write better scientific code, let’s look at a concrete ecological problem: measuring species diversity using Hill numbers.

In community ecology, species richness (the raw number of species) is often too simple a metric because it weights rare and common species equally. To unify richness, Shannon diversity, and Simpson diversity into a single framework, ecologists use Hill numbers (\(^{q}D\)), which represent the “effective number of species” of order \(q\):

\[^{q}D = \left( \sum_{i=1}^{S} p_i^q \right)^{\frac{1}{1-q}}\]

where \(p_i\) is the relative abundance (proportion) of species \(i\), and \(S\) is the species richness. The parameter \(q\) controls the sensitivity to species abundance:

  • \(q = 0\) weights all species equally (equivalent to species richness, \(S\)).
  • \(q = 1\) weights species in proportion to their abundance. The limit as \(q \to 1\) is the exponential of the Shannon index: \(^{1}D = \exp\left(-\sum p_i \ln p_i\right)\).
  • \(q = 2\) weights common species heavily (equivalent to the inverse Simpson index: \(^{2}D = 1 / \sum p_i^2\)).

Let’s walk through how to develop a robust R function for this using the workspace AI assistant, progressing from a simple implementation to a robust, documented function.

If you were writing this from scratch without considering programming details or limit cases, you might write a direct, naive mapping of the math equation:

\[\left( \sum p_i^q \right)^{\frac{1}{1-q}}\]

We begin with the simple, direct mathematical formulation. Prompt:

“Write an R function called calculate_hill that takes a numeric vector abundances and order q to calculate the Hill number. Make sure to handle the case where q = 1.”

The simple implementation is fragile. Real-world ecological data contains missing values (NA), zeros, or negative values. If we pass these, calculate_hill will return NaN or crash.

To make it robust, prompt:

“Modify calculate_hill to validate inputs: check that abundances is numeric and non-negative. Filter out NAs and zero abundances. Return 0 if the vector is empty or all abundances are 0. Be sure to cover all corner cases so it behaves well.”

Writing functions is only half the battle; we also need to ensure they remain correct as our codebase evolves. The standard framework for unit testing in R is the testthat package.

You can ask the workspace AI assistant to write tests for you by prompting:

“Write a unit test suite using the testthat package to verify the behavior of calculate_hill. Test order q = 0, q = 1, and q = 2 with simple cases, verify that it handles zeros and NAs correctly, and test that it throws an error on negative values or non-numeric input.”

We also need to document our function so others (and our future selves) can use it. Professional R packages use Roxygen2 syntax. Prompt:

“Add Roxygen2 comments to this function explaining the input parameters, default values, return types, and mathematical formulas for different q. Also add clear inline comments.”