Repository navigation
Expand file tree
/
Copy pathreact.qmd
More file actions
379 lines (315 loc) · 12.3 KB
/
Copy pathreact.qmd
File metadata and controls
379 lines (315 loc) · 12.3 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
---
title: "ReActAgent"
format:
html:
toc: true
execute:
echo: true
warning: false
error: false
---
A `ReActAgent` is an `Agent` that **reasons** and **acts**. Instead of
answering in one go, it works in a loop:
1. **Think**: it states what it knows so far and what it needs next.
2. **Act**: it calls one or more of its tools.
3. **Observe**: it reads what the tools returned.
4. It repeats steps 1 to 3 until it has enough to answer, then gives a **final
answer** without calling a tool.
Use it when answering a question takes several lookups, and each one depends
on what the previous one found.
```{r}
library(mini007)
retrieve_open_ai_credential <- function() {
Sys.getenv("OPENAI_API_KEY")
}
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
credentials = retrieve_open_ai_credential,
echo = "none"
)
```
## A career advisor
A person asks: *"I'm creative and love helping people. What career paths
might be a good fit, what programs can help me get there, and how can I pay
for it?"*
Answering takes three lookups, one after the other: find careers that match,
find programs that train for those careers, then find funding for those
programs. We give the agent one tool per lookup.
### The data
Small, made-up tables stand in for real services, so the example runs anywhere:
```{r}
careers <- data.frame(
career = c("UX Designer", "Teacher", "Art Therapist", "Data Analyst"),
interests = c(
"creative design technology helping",
"helping teaching children creative",
"creative art helping psychology",
"technology math analysis"
),
median_salary_usd = c(98000, 62000, 58000, 85000)
)
programs <- data.frame(
career = c("UX Designer", "UX Designer", "Teacher", "Art Therapist", "Data Analyst"),
program = c(
"UX Design Bootcamp", "UX Online Certificate", "Teaching Certification",
"M.A. Art Therapy", "Data Analytics Bootcamp"
),
type = c("bootcamp", "online", "online", "college", "bootcamp"),
months = c(4, 6, 9, 24, 3),
cost_usd = c(14000, 300, 5000, 45000, 11000)
)
funding <- data.frame(
name = c("Pell Grant", "Creative Futures Scholarship", "TEACH Grant", "Income Share Agreement"),
program_type = c("college", "bootcamp", "online", "bootcamp"),
amount = c("up to $7,395 per year", "$2,500", "up to $4,000 per year", "paid back as a % of salary")
)
```
### The tools
Each tool is an ordinary R function wrapped with `ellmer::tool()`. Its
description tells the LLM what the tool does and when to call it:
```{r}
search_careers <- ellmer::tool(
function(interest) {
careers[grepl(tolower(interest), careers$interests), c("career", "median_salary_usd")]
},
name = "search_careers",
description = "Find careers that match one interest or trait. Call it once per interest.",
arguments = list(
interest = ellmer::type_string("One word, e.g. 'creative' or 'helping'.")
)
)
find_programs <- ellmer::tool(
function(career) {
programs[programs$career == career, c("program", "type", "months", "cost_usd")]
},
name = "find_programs",
description = "Find training programs for one career, using its exact title.",
arguments = list(
career = ellmer::type_string("Exact career title, e.g. 'UX Designer'.")
)
)
find_funding <- ellmer::tool(
function(program_type) {
funding[funding$program_type == program_type, c("name", "amount")]
},
name = "find_funding",
description = "Find scholarships, grants and loans for one type of program.",
arguments = list(
program_type = ellmer::type_enum(c("bootcamp", "online", "college"), "Program type.")
)
)
```
### The agent
`instruction` is the agent's role. The `ReActAgent` adds the
Think / Act / Observe guidance to it. `max_steps` caps how many tool-using
steps one run can take:
```{r}
advisor <- ReActAgent$new(
name = "career_advisor",
instruction = "You are a career guidance advisor. Keep your final answer under 150 words.",
llm_object = openai_4_1_mini,
tools = list(search_careers, find_programs, find_funding),
max_steps = 6
)
```
```{r}
answer <- advisor$invoke(
"I'm creative and love helping people. What career paths might be a good fit,
what programs can help me get there, and how can I pay for it?"
)
cat(answer)
```
## Following the reasoning
`$print_trace()` shows each step of the last run: what the agent thought,
which tools it called with which arguments, and what it observed:
```{r}
advisor$print_trace()
```
The same steps are available as a data frame in `$trace`, with one row per
entry:
```{r}
advisor$trace[, c("step", "type", "tool")]
```
| Column | Meaning |
|------------|---------------------------------------------------------------------|
| `step` | The step number. Several tool calls made together share a step. |
| `type` | `"think"`, `"act"`, `"observe"` or `"answer"`. |
| `tool` | The tool called (for `"act"` and `"observe"` rows). |
| `content` | The thought, the tool's arguments, its result, or the answer. |
| `is_error` | `TRUE` when a tool failed. The agent sees the error and can adapt. |
## Limiting the number of steps
When an agent reaches `max_steps`, its next tool calls are refused and it is
told to answer with the information it already has. With a single step
allowed, the advisor can search for careers but not look up programs or
funding:
```{r}
quick_advisor <- ReActAgent$new(
name = "quick_advisor",
instruction = "You are a career guidance advisor. Keep your final answer under 100 words.",
llm_object = openai_4_1_mini,
tools = list(search_careers, find_programs, find_funding),
max_steps = 1
)
answer <- quick_advisor$invoke(
"I'm creative and love helping people. Which careers fit me, and which programs should I look at?"
)
quick_advisor$print_trace()
```
If the LLM still keeps calling tools after that, the run stops with an error
of class `mini007_react_step_limit`.
## Agents as tools
`$as_tool()` wraps any agent in a tool, so that a `ReActAgent` can call it
like any other tool. The `ReActAgent` then decides as it goes which agent to
ask, how often and in what order, where a [LeadAgent](leadagent.qmd) makes
its plan up front.
Here a trip planner can ask two experts on Constantine, each with its own
notes: a historian and a food expert.
```{r}
chat_mini <- function() {
ellmer::chat(
name = "openai/gpt-4.1-mini",
credentials = retrieve_open_ai_credential,
echo = "none"
)
}
historian <- Agent$new(
name = "historian",
instruction = paste(
"You are a historian of Constantine. Answer in at most three sentences,",
"only from these notes:",
"- The Palace of Ahmed Bey, built 1826-1835, residence of the last bey.",
"- The Cirta Museum, with Numidian and Roman finds from ancient Cirta.",
"- The El Kantara bridge, of Roman origin, rebuilt in 1863.",
"- The Sidi M'Cid suspension bridge, opened in 1912, above the gorges.",
"- Tiddis, a Roman and Berber hillside town 30 km northwest of the city."
),
llm_object = chat_mini()
)
food_expert <- Agent$new(
name = "food_expert",
instruction = paste(
"You are an expert on the food of Constantine. Answer in at most three",
"sentences, only from these notes:",
"- Chakhchoukha: torn pieces of flatbread in a meat and vegetable sauce.",
"- Jari frik: a soup of green wheat, often eaten in the evening.",
"- Djouzia: Constantine's nougat of walnuts and honey."
),
llm_object = chat_mini()
)
planner <- ReActAgent$new(
name = "planner",
instruction = paste(
"You plan short trips in Algeria. Ask the experts for facts rather than",
"relying on your own knowledge. Keep the plan under 150 words."
),
llm_object = chat_mini(),
tools = list(
historian$as_tool("Answers questions about the history and monuments of Constantine."),
food_expert$as_tool("Answers questions about the dishes of Constantine.")
)
)
plan <- planner$invoke("Plan one day in Constantine for a history lover who likes to eat well.")
cat(plan)
```
The trace shows what the planner asked each expert:
```{r}
planner$print_trace(max_chars = 200)
```
Each expert is a full agent: it keeps its own conversation, cost and
budget, so the planner's cost covers its own calls only:
```{r}
c(
planner = planner$cost,
historian = historian$cost,
food_expert = food_expert$cost
)
```
A few things to know:
- The tool takes one argument, `request`, which is sent to the agent's
`$invoke()`. The agent does not see the caller's conversation, so the
caller is told to put all the context in the request.
- `description` tells the caller when to use the agent. Without it, the
description is made from the agent's name and instruction.
- An agent remembers the earlier requests, so the caller can ask follow-up
questions. With `fresh = TRUE`, its history is cleared before each call.
- When the agent fails, for example because it is over its budget, the
caller is told of the error and carries on without it.
- A `LeadAgent`, a `RouterAgent` or a whole [Workflow](workflow.qmd), through
`$as_agent()`, can be used as a tool too:
`wf$as_agent("guide_writer", "Writes visitor guides.")$as_tool()`.
## Asking the user
`ask_human_tool()` gives an agent a tool to ask you a question in the middle
of its run, for example when the request is ambiguous or when you must
choose between options. The agent decides when to ask, and carries on with
your answer:
```{r}
#| eval: false
planner <- ReActAgent$new(
name = "planner",
instruction = "You plan short trips in Algeria. If the request does not say what the traveller likes, ask them with the ask_user tool.",
llm_object = chat_mini(),
tools = list(ask_human_tool())
)
planner$invoke("Plan an afternoon in Constantine.")
```
In the console, the question comes with numbered options you can pick or
replace with your own words:
```
── What would you like to focus on during your afternoon in Constantine?
1. History and monuments
2. Local food
3. Both
Type a number, or write your own answer.
> 3
```
The answers can also come from somewhere else, such as a Shiny app or a
script: pass `ask`, a `function(question, options)` that returns the answer.
It is the same interface as the [ArchitectAgent](architect.qmd)'s questions.
Here a script answers for the traveller, and the planner also uses the two
experts from the section above:
```{r}
traveller <- function(question, options) {
answer <- "History and food. I only have the afternoon, and I don't want to drive."
cat("Planner asks:", question, "\nTraveller:", answer, "\n")
answer
}
planner <- ReActAgent$new(
name = "planner",
instruction = paste(
"You plan short trips in Algeria. If the request does not say what the",
"traveller likes, ask them with the ask_user tool. Ask the experts for",
"facts rather than relying on your own knowledge. Keep the plan under",
"120 words."
),
llm_object = chat_mini(),
tools = list(
ask_human_tool(ask = traveller),
historian$as_tool("Answers questions about the history and monuments of Constantine."),
food_expert$as_tool("Answers questions about the dishes of Constantine.")
)
)
plan <- planner$invoke("Plan an afternoon in Constantine.")
cat(plan)
```
A few things to know:
- Name the tool in the agent's instruction, as above: otherwise a model
may ask its question in its final answer, which ends the run. The tool's
name is `ask_user`; change it with `name`.
- The agent is told to ask as few questions as possible, and to assume
reasonable details. Ask for more, or less, in its instruction.
- An empty answer tells the agent to decide on its own and to say what it
assumed.
- When nobody can answer, in a non-interactive session without `ask` (a
script, a rendered document or a parallel worker), the agent is told so
and does the same. It never waits for an answer that cannot come.
- The questions and answers appear in the agent's trace, with
`$print_trace()`.
## Using it with other mini007 classes
A `ReActAgent` is an `Agent`, so everything on the [Agents](agents.qmd) page
applies to it: budgets, memory, streaming, cloning and conversation history.
It can also be registered with a [LeadAgent](leadagent.qmd) or used as a
[Workflow](workflow.qmd) station, like any other agent.
It also returns [structured output](agents.qmd#structured-output): with
`$invoke(prompt, type = ...)`, it runs its loop with its tools as usual, then
one more call, without tools, turns its answer into the structure you asked
for.