| Agent | R Documentation |
The 'Agent' class defines a modular LLM-based agent capable of responding to prompts using a defined role/instruction. It wraps an OpenAI-compatible chat model via the ['ellmer'](https://github.com/llrs/ellmer) package.
Each agent maintains its own message history and unique identity.
nameThe agent's name.
instructionThe agent's role/system prompt.
llm_objectThe underlying 'ellmer::chat_openai' object.
agent_idA UUID uniquely identifying the agent.
model_providerThe name of the entity providing the model (eg. OpenAI)
model_nameThe name of the model to be used (eg. gpt-4.1-mini)
broadcast_historyA list of all past broadcast interactions.
budgetA budget in $ that the agent should not exceed.
budget_policyA list controlling budget behavior: on_exceed and warn_at.
budget_warnedWhether the 'warn_at' notice was already given for
the current budget. It is given once, and again after $set_budget().
costThe agent's total cost in USD so far, including what was spent on messages later removed from its history. ‘NA' when the model’s price is unknown.
toolsA list of registered tools available to the agent
memoryThe Memory attached with $set_memory(), or 'NULL'.
last_planThe last run of $plan_and_execute(): a list with
the 'prompt', a 'steps' data frame ('step', 'task', 'result'), the
final 'answer' and a 'timestamp'. 'NULL' before the first run.
code_modeWhether code mode is on, and its time limit: a list
with 'enabled' and 'timeout'. Set with $set_code_mode().
messagesPublic active binding for the conversation history. Assignment is validated automatically.
new()Initializes a new Agent with a specific role/instruction.
Agent$new(name, instruction, llm_object, budget = NA)
nameA short identifier for the agent (e.g. '"translator"').
instructionThe system prompt that defines the agent's role.
llm_objectThe LLM object generate by ellmer (eg. output of ellmer::chat_openai)
budgetNumerical value denoting the amount to set for the budget in US$ to a specific agent, if the budget is reached, an error will be thrown.
# An API KEY is required in order to invoke the Agent
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
polar_bear_researcher <- Agent$new(
name = "POLAR BEAR RESEARCHER",
instruction = paste0(
"You are an expert in polar bears, ",
"you task is to collect information about polar bears. Answer in 1 sentence max."
),
llm_object = openai_4_1_mini
)
invoke()Sends a user prompt to the agent and returns the assistant's response.
Set stream = TRUE to receive the response incrementally: token
deltas, tool calls and tool results are delivered to 'on_event' as
'mini007_event' objects while the LLM is still generating (see
mini007_event). Without 'on_event', deltas are printed to
the console and the response is returned invisibly. The returned text
is the same in both modes.
Agent$invoke(prompt, stream = FALSE, on_event = NULL, type = NULL)
promptA character string prompt for the agent to respond to.
stream'[logical(1)]' Whether to stream the response. Defaults to 'FALSE'.
on_event'[function | NULL]' Callback receiving each
'mini007_event'. Supplying it implies stream = TRUE. Raising an
error inside it cancels the run.
type'[ellmer type | NULL]' To get structured data instead of text, the shape of the answer, built with ellmer's 'type_*()' functions, eg. 'ellmer::type_object(city = ellmer::type_string())'. This uses ellmer's structured output feature, the '$chat_structured()' method of its chat objects (see ellmer's structured data article), so the agent's history, cost and budget work as usual. The answer is returned as R data: a list for an object, a vector for an array of scalars, a data frame for an array of objects. An agent with tools first answers with its tools, then a second call turns that answer into the structure. Cannot be streamed.
The LLM-generated response as a character string, or, with 'type', the structured data.
\dontrun{
# An API KEY is required in order to invoke the Agent
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "translator",
instruction = "You are an Algerian citizen",
llm_object = openai_4_1_mini
)
agent$invoke("Continue this sentence: 1 2 3 viva")
# Stream tokens to the console as they are generated
agent$invoke("Tell me a short story", stream = TRUE)
# Get structured data instead of text
agent$invoke(
"Give the three largest cities of Algeria.",
type = ellmer::type_array(ellmer::type_object(
city = ellmer::type_string(),
population = ellmer::type_integer()
))
)
}
plan_and_execute()Plans a task up front, then carries out the plan one step at a time and writes the final answer from the results.
1. **Plan**: one LLM call turns the task into an ordered list of steps, at most ‘max_steps'. The LLM sees the agent’s tools while planning, but cannot call them yet. 2. **Execute**: each step is one call to the agent, which may use its tools. Every step sees the task, the plan and the earlier results. 3. **Answer**: a last call combines the results into the final answer.
The plan is made once and not revised, which makes this cheaper and more predictable than a [ReActAgent] loop, but less adaptive when a step turns up something unexpected. It suits tasks whose steps can be described in advance.
Everything runs in the agent's own conversation, so 'messages', cost and budget work as with ‘$invoke()'. The plan, each step’s result and the answer are kept in '$last_plan'.
Agent$plan_and_execute(prompt, max_steps = 6, stream = FALSE, on_event = NULL)
promptThe task.
max_steps'[integer(1)]' The largest number of steps in the plan, not counting the final answer. Defaults to 6.
stream'[logical(1)]' Whether to stream the steps and the answer.
on_event'[function | NULL]' Callback receiving each 'mini007_event'; supplying it implies 'stream = TRUE'. Besides the usual Agent events (tagged with 'step'), it receives '"plan_created"', '"step_started"', '"step_completed"', '"answer_started"' and '"plan_completed"'.
The final answer as a character string.
\dontrun{
search_careers <- ellmer::tool(
function(interest) if (interest == "helping") "Teacher, Nurse" else "Designer",
name = "search_careers",
description = "Find careers that match one interest.",
arguments = list(interest = ellmer::type_string("One interest."))
)
advisor <- Agent$new(
name = "advisor",
instruction = "You are a career advisor.",
llm_object = ellmer::chat("openai/gpt-4.1-mini", echo = "none")
)
advisor$register_tools(list(search_careers))
advisor$plan_and_execute("I love helping people. Which careers fit me, and how do I start?")
advisor$last_plan$steps
}
generate_execute_r_code()Generate R code from natural language descriptions and optionally validate/execute it
Agent$generate_execute_r_code( code_description, validate = FALSE, execute = FALSE, interactive = TRUE, env = globalenv() )
code_descriptionCharacter string describing the R code to generate
validateLogical indicating whether to validate the generated code syntax
executeLogical indicating whether to execute the generated code (use with caution)
interactiveLogical; if TRUE, ask for user confirmation before executing generated code
envEnvironment in which to execute the code if execute = TRUE. Default to globalenv
A list containing the generated code and validation/execution results
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
r_assistant <- Agent$new(
name = "R Code Assistant",
instruction = paste("You are an expert R programmer",
llm_object = openai_4_1_mini
)
# Generate code for data manipulation
result <- r_assistant$generate_execute_r_code(
code_description = "Calculate the summary of the mtcars dataframe",
validate = TRUE,
execute = TRUE,
interactive = TRUE
)
print(result)
}
set_code_mode()Turns code mode on or off. In code mode, the agent's tools are not offered to the LLM one by one: it gets a single tool, 'run_r_code', and writes R code that calls its tools as R functions, under their own names, and combines their results with loops, conditions or data frames. A short paragraph asking for one script rather than one call per item is added to the system prompt while code mode is on. One tool call can then do the work of many (look up ten cities, compare them, keep the best three), which saves round trips and tokens.
The code runs in this R session, in an environment that is kept between calls, so variables persist. Printed output, messages and warnings are sent back to the LLM; an error is sent back with the output printed before it, so that the LLM can fix its code. A call that runs longer than 'timeout' seconds is stopped (code waiting on the network may only stop once the wait is over).
The code is not sandboxed: it can do anything R can do on this machine. Use code mode with models and prompts you trust, or ask for approval before each run (see [TaskAgent]'s 'require_approval').
Agent$set_code_mode(enabled = TRUE, timeout = 30, envir = NULL)
enabled'[logical(1)]' 'TRUE' to turn code mode on, 'FALSE' to go back to calling the tools one by one.
timeout'[numeric(1)]' Time limit of one 'run_r_code' call, in seconds. Defaults to 30.
envir'[environment | NULL]' Where the code runs. By default, a new environment whose parent is the global environment, so that the code can use attached packages and read the session's objects, while the variables it creates stay out of the global environment. Pass an environment to share objects with the code, or to read what it made.
The agent, invisibly.
\dontrun{
wilaya_population <- ellmer::tool(
function(wilaya) c(Oran = 1584607, Constantine = 938475, Annaba = 609499)[[wilaya]],
name = "wilaya_population",
description = "Population of an Algerian wilaya (2008 census).",
arguments = list(wilaya = ellmer::type_string("The wilaya, eg. 'Oran'."))
)
analyst <- ReActAgent$new(
name = "analyst",
instruction = "You answer questions about Algerian wilayas.",
llm_object = ellmer::chat("openai/gpt-4.1-mini", echo = "none"),
tools = list(wilaya_population)
)
analyst$set_code_mode()
analyst$invoke("Rank Oran, Constantine and Annaba by population.")
analyst$print_trace()
}
set_budget()Set a budget to a specific agent, if the budget is reached, an error will be thrown
Agent$set_budget(amount_in_usd)
amount_in_usdNumerical value denoting the amount to set for the budget,
\dontrun{
# An API KEY is required in order to invoke the Agent
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "translator",
instruction = "You are an Algerian citizen",
llm_object = openai_4_1_mini
)
agent$set_budget(amount_in_usd = 10.5) # this is equivalent to 10.5$
}
set_budget_policy()Configure how the agent behaves as it approaches or exceeds its budget. Use 'warn_at' (0-1) to emit a one-time warning when spending reaches the specified fraction of the budget. When the budget is exceeded, 'on_exceed' controls behavior: abort, warn and proceed, or ask interactively.
Agent$set_budget_policy(on_exceed = "abort", warn_at = 0.8)
on_exceedOne of "abort", "warn", or "ask".
warn_atNumeric in (0,1); fraction of budget to warn at. Default 0.8.
\dontrun{
agent$set_budget(5)
agent$set_budget_policy(on_exceed = "ask", warn_at = 0.9)
}
keep_last_n_messages()Keep only the most recent 'n' messages, discarding older ones while keeping the system prompt.
Agent$keep_last_n_messages(n = 2)
nNumber of most recent messages to keep.
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "capital finder",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$invoke("What is the capital of Algeria")
agent$invoke("What is the capital of Germany")
agent$invoke("What is the capital of Italy")
agent$keep_last_n_messages(n = 2)
}
add_message()Add a pre-formatted message to the conversation history
Agent$add_message(role, content)
roleThe role of the message ("user", "assistant", or "system")
contentThe content of the message
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "AI assistant",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$add_message("user", "Hello, how are you?")
agent$add_message("assistant", "I'm doing well, thank you!")
}
share_context_with()Share the most recent conversation messages with another agent.
The last n non-system messages from self are appended to the
history of an other agent. This is useful when
one agent needs to handoff context or continue a thread in a separate
agent.
Agent$share_context_with(agent, n = 5)
agentAn object of class Agent that will receive the
messages.
nNumber of recent messages to transfer (excluding the system prompt).
Defaults to 5.
\dontrun{
llm_object <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
a1 <- Agent$new("a1", "instr", llm_object)
a2 <- Agent$new("a2", "instr", llm_object)
a1$invoke("Hello")
a1$invoke("How are you?")
a1$share_context_with(a2, n = 2)
a2$messages
}
clear_and_summarise_messages()Summarises the agent's conversation history into a concise form and appends it to the system prompt. Unlike 'update_instruction()', this method does not override the existing instruction but augments it with a summary for future context.
After creating the summary, the method clears the conversation history and retains only the updated system prompt. This ensures that subsequent interactions start fresh but with the summary preserved as context.
Agent$clear_and_summarise_messages()
\dontrun{
# Requires an OpenAI-compatible LLM from `ellmer`
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "summariser",
instruction = "You are a summarising assistant",
llm_object = openai_4_1_mini
)
agent$invoke("The quick brown fox jumps over the lazy dog.")
agent$invoke("This is another example sentence.")
# Summarises and resets history
agent$summarise_messages()
# Now only the system prompt (with summary) remains
agent$messages
}
update_instruction()Update the system prompt/instruction
Agent$update_instruction(new_instruction)
new_instructionNew instruction to use. Not that the new instruction will override the old one
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "assistant",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$update_instruction("You are a concise assistant.")
}
get_usage_stats()Get the current token count and estimated cost of the conversation
Agent$get_usage_stats()
A list with token counts and cost information
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "assistant",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$set_budget(1)
agent$invoke("What is the capital of Algeria?")
stats <- agent$get_usage_stats()
stats
}
reset_conversation_history()Reset the agent's conversation history while keeping the system instruction
Agent$reset_conversation_history()
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "AI assistant",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$invoke("Hello, how are you?")
agent$invoke("Tell me about machine learning")
agent$reset_conversation_history() # Clears all messages except system prompt
}
export_messages_history()Saves the agent's current conversation history as a JSON file on disk.
Agent$export_messages_history( file_path = paste0(getwd(), "/", paste0(self$name, "_messages.json")) )
file_pathCharacter string specifying the file path where the JSON file should be saved. Defaults to a file named '"<agent_name>_messages.json"' in the current working directory.
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "capital_finder",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$invoke("What is the capital of Algeria")
agent$invoke("What is the capital of Italy")
agent$export_messages_history()
}
load_messages_history()Load an agent's conversation history as a JSON file from disk.
Agent$load_messages_history( file_path = paste0(getwd(), "/", paste0(self$name, "_messages.json")) )
file_pathCharacter string specifying the file path where the JSON file is stored. Defaults to a file named '"<agent_name>_messages.json"' in the current working directory.
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "capital_finder",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
# use the export_messages_history to save the interaction first
agent$load_messages_history("path/to/messages.json")
agent$messages
agent$llm_object
}
validate_response()Validates an agent's response against custom criteria using LLM-based validation. This method uses the agent's LLM to evaluate whether a response meets specified validation criteria (e.g., accuracy, completeness, tone, format).
Agent$validate_response( prompt, response, validation_criteria, validation_score = 0.8 )
promptThe prompt used to generate the response.
responseThe response text to validate.
validation_criteriaThe criteria for validation. (e.g., "The response should be accurate and complete", "The response must be under 100 words").
validation_scoreA numeric from 0 to 1 denoting the score to consider for the evaluation. During the evaluation, the agent will provide a score from 0 to 1, a provided score greater or equal to the 'validation_score' will result in a 'valid' response. Defaults to 0.8.
list object
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "fact_checker",
instruction = "You are a factual assistant.",
llm_object = openai_4_1_mini
)
prompt <- "What is the capital of Algeria?"
response <- agent$invoke(prompt)
validation <- agent$validate_response(
response = response,
prompt = prompt,
validation_criteria = "The response must be accurate and mention Algiers",
validation_score = 0.8
)
print(validation)
}
register_tools()Register one or more tools with the agent
Agent$register_tools(tools)
toolsA list of ellmer tool objects or a single tool object
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "file_assistant",
instruction = "You are a file management assistant.",
llm_object = openai_4_1_mini
)
# Register predefined tools
agent$register_tools(list(change_directory_tool(), list_files_tool()))
}
list_tools()List all registered tools
Agent$list_tools()
Character vector of tool names
\dontrun{
agent$list_tools()
}
remove_tools()Remove tools from the agent
Agent$remove_tools(tool_names)
tool_namesCharacter vector of tool names to remove
\dontrun{
agent$remove_tools(c("change_directory", "list_files"))
}
clear_tools()Clear all registered tools
Agent$clear_tools()
\dontrun{
agent$clear_tools()
}
generate_and_register_tool()Generate and register a tool from a natural language description. This method uses the agent's LLM to create both the R function and the ellmer tool definition based on your description, then automatically registers it.
Agent$generate_and_register_tool(description)
descriptionCharacter string describing what the tool should do
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "file_assistant",
instruction = "You are a helpful assistant.",
llm_object = openai_4_1_mini
)
# Generate and register a tool from description
agent$generate_and_register_tool(
description = "Create a tool that saves text content to a file on disk"
)
# Now the tool is available to use
agent$list_tools()
}
set_memory()Attach a Memory to the agent. Before each $invoke(),
the lessons most relevant to the prompt are retrieved from the memory
and added in front of the prompt. Use $learn() to add lessons.
On a 'LeadAgent', the memory is used differently: see
LeadAgent$set_validation().
Agent$set_memory(memory, k = 3)
memoryA 'Memory' object, or 'NULL' to detach the current one. The same memory can be shared by several agents.
k'[integerish(1)]' Maximum number of lessons added to a prompt. Default 3.
Invisibly, 'self'.
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "translator",
instruction = "You translate English to German.",
llm_object = openai_4_1_mini
)
agent$set_memory(Memory$new(path = "translator_memory.json"))
}
learn()Learn from a judged response: record the outcome in the agent's memory and store a lesson distilled from it by the agent's LLM.
Agent$learn(validation)
validationThe list returned by $validate_response().
Invisibly, the stored lesson record.
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "fact_checker",
instruction = "You are a factual assistant.",
llm_object = openai_4_1_mini
)
agent$set_memory(Memory$new())
prompt <- "What is the capital of Algeria?"
response <- agent$invoke(prompt)
validation <- agent$validate_response(
prompt = prompt,
response = response,
validation_criteria = "The response must be accurate and mention Algiers"
)
agent$learn(validation)
agent$memory$lessons
}
as_tool()Wraps the agent in an ellmer tool, so that another agent can call it.
Register the tool with an agent that has tools, usually a
[ReActAgent]: it then decides on its own when to ask this agent, how
often and in what order, unlike a [LeadAgent], which plans up front.
The tool takes one argument, 'request', which is sent to
$invoke(), and returns the agent's answer. If the call fails
(eg. the agent is over its budget), the calling agent is told of the
error and can carry on without it.
The agent keeps its own conversation history, cost and budget: what it spends is not added to the caller's cost.
Agent$as_tool(description = NULL, name = NULL, fresh = FALSE)
description'[character(1) | NULL]' What the agent can do, which the calling agent reads to decide when to use it. Defaults to a description made from the agent's name and instruction.
name'[character(1) | NULL]' The tool name. Defaults to the agent's name. Characters other than letters, digits, '_' and '-' are replaced by '_'.
fresh‘[logical(1)]' If 'TRUE', the agent’s history is cleared before each call, so that each request is answered on its own. Defaults to 'FALSE': the agent remembers the earlier requests.
An ellmer tool.
\dontrun{
chat <- function() ellmer::chat("openai/gpt-4.1-mini", echo = "none")
historian <- Agent$new("historian", "You are an expert on Algerian history.", chat())
guide <- ReActAgent$new(
name = "guide",
instruction = "You plan trips in Algeria. Ask the historian for historical facts.",
llm_object = chat(),
tools = list(historian$as_tool("Answers questions about Algerian history."))
)
guide$invoke("Plan a day in Constantine for a history lover.")
}
clone_agent()Create a copy of the agent with the same instruction and configuration but a new unique ID. Useful for creating multiple instances of the same agent type.
Agent$clone_agent(new_name = NULL)
new_nameOptional character string to assign a new name to the cloned agent. If NULL, the cloned agent retains the original name.
\dontrun{
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "translator",
instruction = "You are a translator.",
llm_object = openai_4_1_mini
)
# Clone with same name
agent_copy <- agent$clone_agent()
}
clone()The objects of this class are cloneable with this method.
Agent$clone(deep = FALSE)
deepWhether to make a deep clone.
[load_messages_history()] for reloading a saved message history.
[export_messages_history()] for exporting the messages object to json.
## ------------------------------------------------
## Method `Agent$new`
## ------------------------------------------------
# An API KEY is required in order to invoke the Agent
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
polar_bear_researcher <- Agent$new(
name = "POLAR BEAR RESEARCHER",
instruction = paste0(
"You are an expert in polar bears, ",
"you task is to collect information about polar bears. Answer in 1 sentence max."
),
llm_object = openai_4_1_mini
)
## ------------------------------------------------
## Method `Agent$invoke`
## ------------------------------------------------
## Not run:
# An API KEY is required in order to invoke the Agent
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "translator",
instruction = "You are an Algerian citizen",
llm_object = openai_4_1_mini
)
agent$invoke("Continue this sentence: 1 2 3 viva")
# Stream tokens to the console as they are generated
agent$invoke("Tell me a short story", stream = TRUE)
# Get structured data instead of text
agent$invoke(
"Give the three largest cities of Algeria.",
type = ellmer::type_array(ellmer::type_object(
city = ellmer::type_string(),
population = ellmer::type_integer()
))
)
## End(Not run)
## ------------------------------------------------
## Method `Agent$plan_and_execute`
## ------------------------------------------------
## Not run:
search_careers <- ellmer::tool(
function(interest) if (interest == "helping") "Teacher, Nurse" else "Designer",
name = "search_careers",
description = "Find careers that match one interest.",
arguments = list(interest = ellmer::type_string("One interest."))
)
advisor <- Agent$new(
name = "advisor",
instruction = "You are a career advisor.",
llm_object = ellmer::chat("openai/gpt-4.1-mini", echo = "none")
)
advisor$register_tools(list(search_careers))
advisor$plan_and_execute("I love helping people. Which careers fit me, and how do I start?")
advisor$last_plan$steps
## End(Not run)
## ------------------------------------------------
## Method `Agent$generate_execute_r_code`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
r_assistant <- Agent$new(
name = "R Code Assistant",
instruction = paste("You are an expert R programmer",
llm_object = openai_4_1_mini
)
# Generate code for data manipulation
result <- r_assistant$generate_execute_r_code(
code_description = "Calculate the summary of the mtcars dataframe",
validate = TRUE,
execute = TRUE,
interactive = TRUE
)
print(result)
## End(Not run)
## ------------------------------------------------
## Method `Agent$set_code_mode`
## ------------------------------------------------
## Not run:
wilaya_population <- ellmer::tool(
function(wilaya) c(Oran = 1584607, Constantine = 938475, Annaba = 609499)[[wilaya]],
name = "wilaya_population",
description = "Population of an Algerian wilaya (2008 census).",
arguments = list(wilaya = ellmer::type_string("The wilaya, eg. 'Oran'."))
)
analyst <- ReActAgent$new(
name = "analyst",
instruction = "You answer questions about Algerian wilayas.",
llm_object = ellmer::chat("openai/gpt-4.1-mini", echo = "none"),
tools = list(wilaya_population)
)
analyst$set_code_mode()
analyst$invoke("Rank Oran, Constantine and Annaba by population.")
analyst$print_trace()
## End(Not run)
## ------------------------------------------------
## Method `Agent$set_budget`
## ------------------------------------------------
## Not run:
# An API KEY is required in order to invoke the Agent
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "translator",
instruction = "You are an Algerian citizen",
llm_object = openai_4_1_mini
)
agent$set_budget(amount_in_usd = 10.5) # this is equivalent to 10.5$
## End(Not run)
## ------------------------------------------------
## Method `Agent$set_budget_policy`
## ------------------------------------------------
## Not run:
agent$set_budget(5)
agent$set_budget_policy(on_exceed = "ask", warn_at = 0.9)
## End(Not run)
## ------------------------------------------------
## Method `Agent$keep_last_n_messages`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "capital finder",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$invoke("What is the capital of Algeria")
agent$invoke("What is the capital of Germany")
agent$invoke("What is the capital of Italy")
agent$keep_last_n_messages(n = 2)
## End(Not run)
## ------------------------------------------------
## Method `Agent$add_message`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "AI assistant",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$add_message("user", "Hello, how are you?")
agent$add_message("assistant", "I'm doing well, thank you!")
## End(Not run)
## ------------------------------------------------
## Method `Agent$share_context_with`
## ------------------------------------------------
## Not run:
llm_object <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
a1 <- Agent$new("a1", "instr", llm_object)
a2 <- Agent$new("a2", "instr", llm_object)
a1$invoke("Hello")
a1$invoke("How are you?")
a1$share_context_with(a2, n = 2)
a2$messages
## End(Not run)
## ------------------------------------------------
## Method `Agent$clear_and_summarise_messages`
## ------------------------------------------------
## Not run:
# Requires an OpenAI-compatible LLM from `ellmer`
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "summariser",
instruction = "You are a summarising assistant",
llm_object = openai_4_1_mini
)
agent$invoke("The quick brown fox jumps over the lazy dog.")
agent$invoke("This is another example sentence.")
# Summarises and resets history
agent$summarise_messages()
# Now only the system prompt (with summary) remains
agent$messages
## End(Not run)
## ------------------------------------------------
## Method `Agent$update_instruction`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "assistant",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$update_instruction("You are a concise assistant.")
## End(Not run)
## ------------------------------------------------
## Method `Agent$get_usage_stats`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "assistant",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$set_budget(1)
agent$invoke("What is the capital of Algeria?")
stats <- agent$get_usage_stats()
stats
## End(Not run)
## ------------------------------------------------
## Method `Agent$reset_conversation_history`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "AI assistant",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$invoke("Hello, how are you?")
agent$invoke("Tell me about machine learning")
agent$reset_conversation_history() # Clears all messages except system prompt
## End(Not run)
## ------------------------------------------------
## Method `Agent$export_messages_history`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "capital_finder",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
agent$invoke("What is the capital of Algeria")
agent$invoke("What is the capital of Italy")
agent$export_messages_history()
## End(Not run)
## ------------------------------------------------
## Method `Agent$load_messages_history`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "capital_finder",
instruction = "You are an assistant.",
llm_object = openai_4_1_mini
)
# use the export_messages_history to save the interaction first
agent$load_messages_history("path/to/messages.json")
agent$messages
agent$llm_object
## End(Not run)
## ------------------------------------------------
## Method `Agent$validate_response`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "fact_checker",
instruction = "You are a factual assistant.",
llm_object = openai_4_1_mini
)
prompt <- "What is the capital of Algeria?"
response <- agent$invoke(prompt)
validation <- agent$validate_response(
response = response,
prompt = prompt,
validation_criteria = "The response must be accurate and mention Algiers",
validation_score = 0.8
)
print(validation)
## End(Not run)
## ------------------------------------------------
## Method `Agent$register_tools`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "file_assistant",
instruction = "You are a file management assistant.",
llm_object = openai_4_1_mini
)
# Register predefined tools
agent$register_tools(list(change_directory_tool(), list_files_tool()))
## End(Not run)
## ------------------------------------------------
## Method `Agent$list_tools`
## ------------------------------------------------
## Not run:
agent$list_tools()
## End(Not run)
## ------------------------------------------------
## Method `Agent$remove_tools`
## ------------------------------------------------
## Not run:
agent$remove_tools(c("change_directory", "list_files"))
## End(Not run)
## ------------------------------------------------
## Method `Agent$clear_tools`
## ------------------------------------------------
## Not run:
agent$clear_tools()
## End(Not run)
## ------------------------------------------------
## Method `Agent$generate_and_register_tool`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "file_assistant",
instruction = "You are a helpful assistant.",
llm_object = openai_4_1_mini
)
# Generate and register a tool from description
agent$generate_and_register_tool(
description = "Create a tool that saves text content to a file on disk"
)
# Now the tool is available to use
agent$list_tools()
## End(Not run)
## ------------------------------------------------
## Method `Agent$set_memory`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "translator",
instruction = "You translate English to German.",
llm_object = openai_4_1_mini
)
agent$set_memory(Memory$new(path = "translator_memory.json"))
## End(Not run)
## ------------------------------------------------
## Method `Agent$learn`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "fact_checker",
instruction = "You are a factual assistant.",
llm_object = openai_4_1_mini
)
agent$set_memory(Memory$new())
prompt <- "What is the capital of Algeria?"
response <- agent$invoke(prompt)
validation <- agent$validate_response(
prompt = prompt,
response = response,
validation_criteria = "The response must be accurate and mention Algiers"
)
agent$learn(validation)
agent$memory$lessons
## End(Not run)
## ------------------------------------------------
## Method `Agent$as_tool`
## ------------------------------------------------
## Not run:
chat <- function() ellmer::chat("openai/gpt-4.1-mini", echo = "none")
historian <- Agent$new("historian", "You are an expert on Algerian history.", chat())
guide <- ReActAgent$new(
name = "guide",
instruction = "You plan trips in Algeria. Ask the historian for historical facts.",
llm_object = chat(),
tools = list(historian$as_tool("Answers questions about Algerian history."))
)
guide$invoke("Plan a day in Constantine for a history lover.")
## End(Not run)
## ------------------------------------------------
## Method `Agent$clone_agent`
## ------------------------------------------------
## Not run:
openai_4_1_mini <- ellmer::chat(
name = "openai/gpt-4.1-mini",
api_key = Sys.getenv("OPENAI_API_KEY"),
echo = "none"
)
agent <- Agent$new(
name = "translator",
instruction = "You are a translator.",
llm_object = openai_4_1_mini
)
# Clone with same name
agent_copy <- agent$clone_agent()
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.