Skip to content

Conversation

@gadenbuie
Copy link
Collaborator

@gadenbuie gadenbuie commented Jul 2, 2025

Example: Researcher Agent

researcher <- btw_agent_researcher_r_task(
  ellmer::chat_aws_bedrock(
    model = "us.anthropic.claude-3-5-haiku-20241022-v1:0"
  )
)

# Chat with a higher-powered LLM that delegates research tasks
# to a smaller, faster model
client <- btw_client(
  client = ellmer::chat_aws_bedrock(
    model = "us.anthropic.claude-sonnet-4-20250514-v1:0"
  ),
  tools = list(researcher)
)

shinychat::chat_app(client)

Then give the chat this prompt:

I have EV purchasing data (date of purchase, county, make and model of EV car) for Oregon and want to show aggregated purchasing data on an interactive map. How can I do this? Can you show me a few options? Don't actually tell me the answer. Instead, do the research and then tell me when you're done with the research

Example: Summarizer Agent

I haven't fully worked out how this will be exposed as a tool, but the task helper is useful. You can take a full chat and request a summary:

client <- btw_client(tools = btw_tools())

client$chat(
  paste(
    "Read the R package documentation to research how can I use leaflet package in R",  
    "to create choropleth maps with county-level aggregated data.",
    "Read all relevant help documentation to perform the initial research,",
    "but do not summarize the results until I ask you to."
  )
)
#> I'll help you research the leaflet package documentation to understand how to create choropleth maps...
#> [... many tools calls later ...]
#>
#> Perfect! I've now thoroughly researched the leaflet package documentation for creating choropleth maps
#> with county-level aggregated data. I've gathered comprehensive information from the help pages covering:
#> 
#> 1. The main `leaflet()` function for creating map widgets
#> 2. `addPolygons()` for adding polygon layers (essential for choropleth maps)
#> 3. Color mapping functions (`colorNumeric`, `colorBin`, `colorQuantile`, `colorFactor`)
#> 4. `addLegend()` for adding color legends
#> 5. `highlightOptions()` for interactive features
#> 6. `pathOptions()` for styling polygons
#> 7. `previewColors()` for testing color schemes
#> 8. Example spatial data format (`gadmCHE`)
#> 
#> The research is complete and I have all the necessary information about using leaflet for choropleth maps
#>  with county-level data. I'm ready to provide a comprehensive summary when you ask for it.

client |> btw_task_summarize_chat()
# Leaflet Package Research for County-Level Choropleth Maps

## Objective
Research the R leaflet package documentation to understand how to create choropleth maps with county-level aggregated data.

## Key Findings

### Core Functions for Choropleth Maps
- **`leaflet()`**: Creates the base map widget, accepts spatial data objects (sf, sp, SpatialPolygonsDataFrame)
- **`addPolygons()`**: Primary function for adding polygon layers with styling options
- **`addGeoJSON()`/`addTopoJSON()`**: Alternative functions for JSON-based spatial data

### Color Mapping Functions
Four specialized functions for mapping data values to colors:
- **`colorNumeric()`**: Linear mapping for continuous data
- **`colorBin()`**: Binned mapping using cut() function intervals
- **`colorQuantile()`**: Quantile-based binning for equal-size groups
- **`colorFactor()`**: Categorical data mapping

### Essential Styling Parameters for Polygons
```r
addPolygons(
  map,
  fillColor = ~colorFunction(data_column),  # Choropleth colors
  fillOpacity = 0.7,                        # Fill transparency
  color = "white",                          # Border color
  weight = 1,                               # Border width
  popup = ~paste("County:", county_name),   # Interactive popups
  highlightOptions = highlightOptions(      # Hover effects
    weight = 3,
    bringToFront = TRUE
  )
)
```

### Legend Creation
- **`addLegend()`**: Automatically generates legends from color palette functions
- **`labelFormat()`**: Customizes legend label formatting (prefixes, suffixes, digits)
- Legends can be positioned and styled with CSS classes

### Data Structure Requirements
- Spatial data must contain polygon geometries for county boundaries
- Aggregated data should be joined to spatial data before mapping
- Functions support formula notation (`~column_name`) for referencing data columns

### Base Map Integration
- **`addProviderTiles()`**: Access to numerous tile providers (Stamen, CartoDB, etc.)
- **`addTiles()`**: Default OpenStreetMap tiles or custom tile services

### Interactive Features
- **Popups**: Display data on click using `popup` parameter
- **Labels**: Show data on hover using `label` parameter  
- **Highlighting**: Interactive hover effects with `highlightOptions()`
- **Layer Controls**: Toggle different data layers with `addLayersControl()`

## Final Approach Pattern
```r
# Basic choropleth workflow
pal <- colorNumeric("YlOrRd", domain = county_data$values)

leaflet(county_spatial_data) %>%
  addProviderTiles("CartoDB.Positron") %>%
  addPolygons(
    fillColor = ~pal(data_column),
    fillOpacity = 0.7,
    color = "white",
    weight = 1,
    popup = ~paste("County:", name, "<br>Value:", data_column),
    highlightOptions = highlightOptions(weight = 3, bringToFront = TRUE)
  ) %>%
  addLegend(
    position = "bottomright",
    pal = pal,
    values = ~data_column,
    title = "Legend Title"
  )
```

## Important Context
- Package supports multiple spatial data formats (sf preferred for modern workflows)
- Color functions handle NA values automatically with customizable na.color parameter
- All styling follows CSS conventions for web-based visualization
- Interactive features work seamlessly in RMarkdown, Shiny, and standalone HTML output
- `previewColors()` utility function available for testing color palettes before mapping

## Outcome
Comprehensive understanding of leaflet package capabilities for county-level choropleth mapping, including data preparation requirements, styling options, interactivity features, and complete workflow patterns.

Example: Define agents in btw.md

---
client:
  provider: aws_bedrock
  model: us.anthropic.claude-sonnet-4-20250514-v1:0
tools: false
agents:
  - name: r_package_researcher
    title: R Package Researcher
    client:
      model: us.anthropic.claude-3-5-haiku-20241022-v1:0
    tools: [session, docs]
    description: |
      Use this agent to perform research into the best R packages and functions to use for a specific task.
    system_prompt: |
      You are an expert R programmer and research assistant. Your task is to help users find and understand R packages that can solve their problems.

      When a user asks for help completing a task, you should:
      - Search for relevant packages on CRAN
      - Determine which packages are most suitable for the task
      - Determine if any packages are already installed
      - Provide a brief description of relevant packages
      - Suggest how to install any missing packages
      - Provide example code using installed packages to complete the task
---

Follow these important style rules when writing R code:

* Prefer solutions that use {tidyverse}
* Always use `<-` for assignment
* Always use the native base-R pipe `|>` for piped expressions

@gadenbuie gadenbuie changed the base branch from feat/sidechat-tool to main July 2, 2025 20:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant