-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchores.qmd
More file actions
647 lines (476 loc) · 20.9 KB
/
Copy pathchores.qmd
File metadata and controls
647 lines (476 loc) · 20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# chores {#sec-shiny-chores}
```{r}
#| eval: true
#| echo: false
#| include: false
source("_common.R")
movies <- fst::read_fst("_assets/movies.fst")
vroom::vroom_write(movies,
file = "_assets/movies.csv",
delim = ",")
```
```{r}
#| label: co_box_review
#| echo: false
#| results: asis
#| eval: false
co_box(
color = "y",
look = "default", hsize = "1.15", size = "0.95",
header = "CAUTION",
fold = FALSE,
contents = "
This chapter is currently under review. Thank you for your patience.
"
)
```
```{r}
#| label: co_box_tldr
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "b",
look = "default", hsize = "1.05", size = "0.95",
header = "TLDR   {width='8%'}",
fold = TRUE,
contents = "
`chores` works seamlessly with RStudio {width=25} and Positron {width=25}, allowing you to select code and activate `chores` helpers for tasks like generating documentation, refactoring code, writing modules, etc.
This package was recently updated to version
"
)
```
<!-- https://simonpcouch.github.io/chores/ -->
The [`chores` package](https://simonpcouch.github.io/chores/) was developed to "*help you complete repetitive, hard-to-automate tasks quickly*". We previously covered the [`ellmer` package](https://ellmer.tidyverse.org/index.html) (see @sec-shiny-ellmer), which we’ll use to configure an LLM to use with `chores`.
```{r}
#| eval: false
#| code-fold: false
install.packages(c('ellmer', 'chores'))
# or the dev versions
pak::pak('tidyverse/ellmer')
pak::pak("simonpcouch/chores")
```
In this chapter we'll use the `chores` addin to help write `roxygen2` documentation and `testthat` tests in an updated version of the movie review application.[^chores-1]
[^chores-1]: Simon Couch also the author of the [`ensure`](https://simonpcouch.github.io/ensure/) and [`gander`](https://simonpcouch.github.io/gander/) packages.
```{r}
#| label: shinypak_apps
#| echo: false
#| results: asis
#| eval: true
shinypak_apps(regex = "^28", branch = "28_llm-chores")
```
We're going to start this chapter by going over the structure of the application, then dive into configuring chores (@sec-shiny-chores-setup), creating keyboard shortcuts (@sec-chores-helper-addin), and writing custom helpers (@sec-chores-custom-helpers). We will conclude with an example `chores` extension package (@sec-chores-ext-pkg).
## Navbar App overview {#sec-chores-navbar-app}
The application in this branch has been built around the [`page_navbar` layout from `bslib`](https://rstudio.github.io/bslib/reference/page_navbar.html), with `nav_panel()`s containing graphs and tables for **Counts**, **Distributions**, and **Awards**.
{width="100%" fig-align="center"}
### App modules {.unnumbered}
The modules in the application have the following naming convention:
[`mod_` `<tab>` `_` `<type>` `_` `ui/server`]{style="font-size: 1.25em; font-weight: bold;"}
- `<tab>` is the name of the tab (**Compare**, **Counts**, **Distributions**, **Awards**)
- **`<type>`**
- `vars`: 'variable' collection modules to return inputs
- `tbl`: table display modules
- type of display in module (i.e., `point`, `bar`, `vbox`, etc.)
Each tab's modules are organized into abstract syntax trees[^ast] in the sections below.
[^ast]: Create abstract syntax trees with the [`lobstr::ast()` function](https://lobstr.r-lib.org/reference/ast.html).
#### Compare {.unnumbered}
The **Compare** tab uses two modules:
1. `mod_compare_vars` collects the variable and aesthetic inputs.
2. `mod_compare_point` takes the inputs and builds the `plotly` point plot.
```{verbatim}
█─ ─nav_ui
│ ├─█─mod_compare_vars_ui
│ └─█─mod_compare_point_ui
└─█─nav_server
├─█─mod_compare_vars_server
└─█─mod_compare_point_server
```
#### Counts {.unnumbered}
The **Counts** tab includes five modules:
1. `mod_counts_vars` collects a grouping variable and start and end dates for the theater release year
2. `mod_counts_vbox` displays the value box
3. `mod_counts_waffle` displays the waffle plot
4. `mod_counts_bar` displays the horizontal bar plot
:::{layout="[70,30]" layout-valign="top"}
{width=400 fig-align="left"}
```{verbatim}
█─ ─nav_ui
│ ├─█─mod_counts_vars_ui
│ ├─█─mod_counts_vbox_ui
│ ├─█─mod_counts_bar_ui
│ └─█─mod_counts_waffle_ui
└─█─nav_server
├─█─mod_counts_vars_sever
├─█─mod_counts_vbox_server
├─█─mod_counts_bar_server
└─█─mod_counts_waffle_server
```
:::
5. `mod_counts_tbl` displays the data used in the counts graphs and value box.
:::{layout="[70,30]" layout-valign="top"}
{width=400 fig-align="left"}
```{verbatim}
█─ ─nav_ui
│ ├─█─mod_counts_vars_ui
│ └─█─mod_counts_tbl_ui
└─█─nav_server
├─█─mod_compare_vars_server
└─█─mod_counts_tbl_server
```
:::
#### Distributions {.unnumbered}
The **Distributions** tab uses four modules:
1. `mod_dist_vars` collects a grouping y variable, a numeric x variable, and the alpha and size aesthetics.
2. `mod_dist_box` displays the horizontal box plot.
3. `mod_dist_raincloud` displays the rain cloud plot.
:::{layout="[70,30]" layout-valign="top"}
{width=400 fig-align="left"}
```{verbatim}
█─ ─nav_ui
│ ├─█─mod_dist_vars_ui
│ ├─█─mod_dist_box_ui
│ └─█─mod_dist_raincloud_ui
└─█─nav_server
├─█─mod_dist_vars_server
├─█─mod_dist_box_server
└─█─mod_dist_raincloud_server
```
:::
4. `mod_dist_tbl` displays a table of summary statistics for the numeric variable across the levels of the grouping variable.
:::{layout="[70,30]" layout-valign="top"}
{width=400 fig-align="left"}
```{verbatim}
█─ ─nav_ui
│ ├─█─mod_dist_vars_ui
│ └─█─mod_dist_tbl_ui
└─█─nav_server
├─█─mod_dist_vars_server
└─█─mod_dist_tbl_server
```
:::
#### Awards {.unnumbered}
**Awards** has three modules:
1. `mod_awards_vars` returns the award type and start and end values for the theater release year.
2. `mod_awards_point` displays the point plot with labels for the movies or stars (actors).
:::{layout="[70,30]" layout-valign="top"}
{width=400 fig-align="left"}
```{verbatim}
█─ ─nav_ui
│ ├─█─mod_awards_vars_ui
│ └─█─mod_awards_point_ui
└─█─nav_server
├─█─mod_awards_vars_server
└─█─mod_awards_point_server
```
:::
3. `mod_awards_tbl` displays the data used in the point plot.
:::{layout="[70,30]" layout-valign="top"}
{width=400 fig-align="left"}
```{verbatim}
█─ ─nav_ui
│ ├─█─mod_awards_vars_ui
│ └─█─mod_awards_tbl_ui
└─█─nav_server
├─█─mod_awards_vars_server
└─█─mod_awards_tbl_server
```
:::
### Utility functions {.unnumbered}
Three new utility functions have been added to the application. The `display_type()` (@sec-launch-display-type) and `test_logger()` (@sec-test-logger) functions from previous sections are also included.
#### Name case {.unnumbered}
The `name_case()` function converts the column names to title case (and it's used in most of the module functions):
```{r}
#| label: name_case
#| include: false
#| eval: true
source("https://raw.githubusercontent.com/mjfrigaard/sap/refs/heads/28_llm-chores/R/name_case.R")
```
```{r}
#| code-fold: false
#| collapse: true
name_case(x = "critics_rating", case = "title")
```
```{r}
#| code-fold: false
#| collapse: true
name_case(x = "Critics Rating", case = "lower")
```
#### Variable summary {.unnumbered}
The `dist_var_summary()` function creates the summary statistics table in the **Distributions** tab using the group and numerical variables.
```{r}
#| label: dist_var_summary_and_name_case
#| include: false
#| eval: true
source("https://raw.githubusercontent.com/mjfrigaard/sap/refs/heads/28_llm-chores/R/dist_var_summary.R")
```
```{verbatim}
█─ ─nav_ui
│ └─█─mod_dist_tbl_ui
└─█─nav_server
└─█─mod_dist_tbl_server
└─█─dist_var_summary
```
```{r}
#| code-fold: false
#| collapse: true
dist_var_summary(
data = movies,
grp_var = 'critics_rating',
num_var = 'audience_score')
```
#### Movie awards {.unnumbered}
When provided an award type (Films or Stars) and start and end theater release dates, the `create_movie_awards` converts the `movies` data into the movie awards data for the graph and table the **Awards** tab:
```{r}
#| label: create_movie_awards
#| include: false
#| eval: true
source("https://raw.githubusercontent.com/mjfrigaard/sap/refs/heads/28_llm-chores/R/filter_award_wins.R")
source("https://raw.githubusercontent.com/mjfrigaard/sap/refs/heads/28_llm-chores/R/create_movie_wins.R")
source("https://raw.githubusercontent.com/mjfrigaard/sap/refs/heads/28_llm-chores/R/create_movie_awards.R")
```
```{verbatim}
█─ ─nav_ui
│ ├─█─mod_awards_point_ui
└─█─nav_server
└─█─mod_awards_point_server
└─█─create_movie_awards
```
```{r}
#| code-fold: false
#| collapse: true
#| eval: true
#| echo: true
create_movie_awards(
df = movies,
award = "Films",
start_year = 1990,
end_year = 1995)
```
## Configuration {#sec-shiny-chores-setup}
We'll use the Anthropic’s Claude model for the `chores` add-in. This can be configured following the instructions on the [package website](https://simonpcouch.github.io/chores/articles/chores.html#choosing-a-model).
Open `.Renviron` and add `ANTHROPIC_API_KEY`:
```{r}
#| eval: false
#| code-fold: false
# open .Rprofile
usethis::edit_r_environ()
```
Use the `.chores_chat` option to set the model:
```{r}
#| eval: false
#| code-fold: false
options(.chores_chat = ellmer::chat_claude())
```
You should see:[^chores-2]
[^chores-2]: At the time of this writing, this was the latest Claude model from [Anthropic.](https://www.anthropic.com/news/claude-3-7-sonnet)
```{verbatim}
Using model = "claude-3-7-sonnet-latest".
```
### Configure add-in {#sec-shiny-chores-addin}
`chores` comes with an add-in (an interface to write prompts) which I'll be demonstrating in Positron {height="25"}[^chores-3]
[^chores-3]: You can see examples using RStudio {height="25"} on the [package website](https://simonpcouch.github.io/chores/index.html#example).
After adding the JSON to `keybindings.json`, the `chores` add-in will pop-up in the **Viewer**:
{width="100%" fig-align="center"}
## Keyboard shortcut {#sec-chores-helper-addin}
`chores` comes with three helpers: `cli`, `roxygen`, `testthat`. Below is an example of the `roxygen` helper in Positron {height=25} with our `name_case()` function:
{width='100%' fig-align="center"}
`chores` doesn't write comprehensive documentation, but it will
> "*generate a subset of a complete documentation entry, to be then completed by a developer:*"
Specifically, it will write the `@title`, `@description`, any arguments (i.e., `@param`), and what the function `@returns`. The `chores` helper will also export the function by default.
The `chores` helper returned the following `roxygen2` documentation:
```{r}
#| eval: false
#| echo: true
#| code-fold: false
#' Change the case of text
#'
#' @param x A character vector.
#' @param case One of `"title"` or `"lower"`. Optional.
#'
#' @returns A character vector with the case changed according to the specified format.
#' Will error if input is not a character vector or if an unsupported case is specified.
#'
#' @export
```
The `mod_compare_vars_ui()` function is also demonstrated below:
```{r}
#| label: co_box_chores_helper
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "g",
look = "default",
hsize = "1.15",
size = "0.95",
header = "TIP: Padding",
fold = FALSE,
contents = "
I recommend placing about 10 lines of extra padding above the function you're using `chores` to document in Positron {height=30}. I've found this ensures the first few lines of the function aren't overwritten by the helper response.
"
)
```
{width='100%' fig-align="center"}
The `roxygen2` documentation for the `mod_compare_vars_ui()` function is below:
```{r}
#| eval: false
#| code-fold: false
#' UI module for comparing movie variables
#'
#' @param id A string. The module ID.
#'
#' @returns A UI element containing inputs for selecting variables to compare
#' in a scatter plot, including X and Y variables, color variable, and
#' customization controls for alpha, size, and plot title.
#'
#' @export
```
So far, all of the documentation I've generated using `chores` has been correct, *and* it puts me in a better starting place that the standard `roxygen2` skeleton produced by RStudio. You can read more about the helper prompts in the [`chores` package documentation](https://simonpcouch.github.io/chores/articles/chores.html).
Below we'll cover how to add custom helper prompts that can be used with the `chores` addin.
## Custom helpers {#sec-chores-custom-helpers}
`chores` gives users the ability to add custom helpers (prompts). These prompts can be written in markdown and must be named either `replace`, `prefix`, or `suffix`.
* `replace`: removes the highlighted text and replaces it with a response.
* `prefix`: inserts a response above the highlighted text.
* `suffix`: places the response below the highlighted text.
Below is a [`shinymod-prefix` helper prompt](https://github.com/mjfrigaard/chorrrin/blob/main/inst/prompts/shinymod-prefix.md) that has some specific instructions for documenting Shiny modules (see @sec-document-app-functions).
```{r}
#| label: co_box_chores_shinymods
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "y",
look = "default",
hsize = "1.15",
size = "0.95",
header = "`inst/prompts/shinymod-prefix.md`",
fold = TRUE,
contents = "
**[`inst/prompts/shinymod-prefix.md`](https://github.com/mjfrigaard/chorrrin/blob/main/inst/prompts/shinymod-prefix.md)**
You are an expert Shiny developer who loves providing detailed explanations of complex topics to non-technical audiences.
Follow the tidyverse style guide:
* Limit code to 80 characters per line
* Place a space before and after `=`
* Only use a single empty line when needed to separate sections
* Always use double quotes for strings
* Always use backticks for inline code
* Use double quotes, not single quotes, for quoting text
* Use base pipe `|>` (not `%>%`)
* Reference UI/server functions using brackets
Use the following documentation for the `aes()` function from `ggplot2` as an example:
\`\`\`r
#' Construct aesthetic mappings
#'
#' Aesthetic mappings describe how variables in the data are mapped to visual
#' properties (aesthetics) of geoms. Aesthetic mappings can be set in
#' [ggplot()] and in individual layers.
#'
#' This function also standardises aesthetic names by converting `color` to
#' `colour` (also in substrings, e.g., `point_color` to `point_colour`) and
#' translating old style R names to ggplot names (e.g., `pch` to `shape`
#' and `cex` to `size`).
\`\`\`
* When documenting a UI function, reference the corresponding server function (and vice versa).
* For example, `mod_vars_ui()` should reference `mod_vars_server()`.
\`\`\`r
mod_vars_ui <- function(id) {
ns <- NS(id)
tagList(
varSelectInput(
inputId = ns('chr_var'),
label = strong('Group variable'),
data = chr_data,
selected = 'Critics Rating'
)
)
}
\`\`\`
\`\`\`r
mod_vars_server <- function(id) {
moduleServer(id, function(input, output, session) {
return(
reactive({
list(
'chr_var' = input$chr_var
)
})
)
})
}
\`\`\`
Example documentation for `mod_vars_ui()`:
\`\`\`r
#' UI for count variables module
#'
#' Creates inputs for selecting a grouping variable. This function is designed
#' to work together with [mod_vars_server()].
#'
#' @param id A character string used to identify the namespace for the module.
#'
#' @return A `tagList` containing UI elements:
#' * A variable select input for the grouping variable
#'
#' @seealso [mod_vars_server()] for the server-side logic
#'
#' @examples
#' # UI implementation
#' ui <- fluidPage(
#' mod_vars_ui('vars1')
#' )
#'
#' # Server implementation
#' server <- function(input, output, session) {
#' vars <- mod_vars_server('vars1')
#' }
#'
\`\`\`
* Indicate if returned values are reactive.
* Return responses in `roxygen2` comments (no R code blocks)
* Include 5 blank lines of 'padding' after all responses
")
```
To add a custom helper to the `chores` addin, you can provide the URL to a raw markdown file on GitHub using [`chores::prompt_new()`](https://simonpcouch.github.io/chores/reference/prompt.html):
```{r}
#| eval: false
#| code-fold: false
chores::prompt_new(
"shinymod",
"prefix",
contents = "https://raw.githubusercontent.com/mjfrigaard/chorrrin/refs/heads/main/inst/prompts/shinymod-prefix.md"
)
```
### What _are_ chores helpers?
`chores` helpers have a skill-style interface (prompt-based, non-agentic) — but they are packaged for a narrow coding chore. They don't call tools or have autonomy (like agents/subagents). When code is highlighted, The *pre-written prompt* + *selected text* is sent to the LMM, and the *replacement text* is returned.
## Extension packages {#sec-chores-ext-pkg}
If you have a collection of repetitive tasks you'd like to include in the `chores` addin, you can create and install a small extension package. For example, I've created the [`chorrrin` extension package](https://github.com/mjfrigaard/chorrrin).[^chores-ext]
[^chores-ext]: Follow the [example extension package](https://github.com/simonpcouch/palpable) and instructions provided in the [`chores` documentation.](https://simonpcouch.github.io/chores/articles/custom.html#extension-packages)
```{r}
#| eval: false
#| code-fold: false
# install.packages("pak")
pak::pak("mjfrigaard/chorrrin")
library(chorrrin)
```
`chorrrin` includes a [`modlog-replace` helper](https://github.com/mjfrigaard/chorrrin/blob/main/inst/prompts/modlog-replace.md) for re-writing Shiny modules using the [`logger` package](https://daroczig.github.io/logger/) (we covered this in @sec-logging-logr_msg) and a [modtest-replace](https://github.com/mjfrigaard/chorrrin/blob/main/inst/prompts/modtest-replace.md) for writing Shiny module tests using Shiny's `testServer()` function (see [Testing modules](test_modules.qmd)).
This allows me to highlight the module function I'd like to add log messages to, hit the keyboard shortcut (<kbd>Ctrl</kbd> + <kbd>Cmd</kbd> + <kbd>C</kbd>), select my custom helper, click <kbd>Enter</kbd>, and voilà!
{width='100%' fig-align='center'}
The `chores` extension goes to work re-writing the module function with the log messages (following the helper prompt I provided).
## Recap {.unnumbered}
```{r}
#| label: co_box_recap
#| echo: false
#| results: asis
#| eval: true
co_box(
color = "g",
fold = FALSE,
look = "default", hsize = "1.15", size = "1.05",
header = "Recap: {width='8%'}",
contents = "
`chores` delivers on it's goal to '*complete repetitive, hard-to-automate tasks quickly.*' I used it to quickly generate documentation, log messages, and tests for the modules in this branch's application.
+ **Customizable Helpers:** `chores` lets you create custom helpers for your project by writing instructions in Markdown files. This flexibility allows you to tailor them to your workflow, making them ideal for specialized Shiny app development tasks.
+ **Integration with LLMs via ellmer:** `chores` uses the [`ellmer` package](https://ellmer.tidyverse.org/index.html) to connect with LLM providers like OpenAI and Anthropic, allowing for intelligent suggestions and context-specific code generation. You can set the LLM by adjusting the [`.chores_chat` option](https://simonpcouch.github.io/chores/reference/helper_options.html).
+ **Ease of Use within RStudio/Positron:** `chores` includes an RStudio/Positron addin that can be activated with a keyboard shortcut (e.g., Ctrl/Cmd+Alt+C), providing an interactive interface for selecting and applying code helpers and streamlining development.
The responses still require revisions/edits, but being able use a keyboard shortcut to quickly generate a first draft saves time (and neurons).
")
```