% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Agent.R
\name{Agent}
\alias{Agent}
\title{Agent: A General-Purpose LLM Agent}
\description{
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.
}
\examples{

## ------------------------------------------------
## 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`
## ------------------------------------------------

\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")
}

## ------------------------------------------------
## Method `Agent$generate_execute_r_code`
## ------------------------------------------------

\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)
}

## ------------------------------------------------
## Method `Agent$set_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$
}

## ------------------------------------------------
## Method `Agent$set_budget_policy`
## ------------------------------------------------

\dontrun{
agent$set_budget(5)
agent$set_budget_policy(on_exceed = "ask", warn_at = 0.9)
}

## ------------------------------------------------
## Method `Agent$keep_last_n_messages`
## ------------------------------------------------

\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)
}

## ------------------------------------------------
## Method `Agent$add_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!")
}

## ------------------------------------------------
## Method `Agent$share_context_with`
## ------------------------------------------------

\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
}

## ------------------------------------------------
## Method `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
}


## ------------------------------------------------
## Method `Agent$update_instruction`
## ------------------------------------------------

\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.")
}

## ------------------------------------------------
## Method `Agent$get_usage_stats`
## ------------------------------------------------

\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
}

## ------------------------------------------------
## Method `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
}

## ------------------------------------------------
## Method `Agent$export_messages_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 = "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()
}


## ------------------------------------------------
## Method `Agent$load_messages_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 = "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
}


## ------------------------------------------------
## Method `Agent$validate_response`
## ------------------------------------------------

\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)
}

## ------------------------------------------------
## Method `Agent$register_tools`
## ------------------------------------------------

\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()))
}

## ------------------------------------------------
## Method `Agent$list_tools`
## ------------------------------------------------

\dontrun{
agent$list_tools()
}

## ------------------------------------------------
## Method `Agent$remove_tools`
## ------------------------------------------------

\dontrun{
agent$remove_tools(c("change_directory", "list_files"))
}

## ------------------------------------------------
## Method `Agent$clear_tools`
## ------------------------------------------------

\dontrun{
agent$clear_tools()
}

## ------------------------------------------------
## Method `Agent$generate_and_register_tool`
## ------------------------------------------------

\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()
}

## ------------------------------------------------
## Method `Agent$clone_agent`
## ------------------------------------------------

\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()
}
}
\seealso{
[load_messages_history()] for reloading a saved message history.

[export_messages_history()] for exporting the messages object to json.
}
\section{Public fields}{
\if{html}{\out{<div class="r6-fields">}}
\describe{
\item{\code{name}}{The agent's name.}

\item{\code{instruction}}{The agent's role/system prompt.}

\item{\code{llm_object}}{The underlying `ellmer::chat_openai` object.}

\item{\code{agent_id}}{A UUID uniquely identifying the agent.}

\item{\code{model_provider}}{The name of the entity providing the model (eg. OpenAI)}

\item{\code{model_name}}{The name of the model to be used (eg. gpt-4.1-mini)}

\item{\code{broadcast_history}}{A list of all past broadcast interactions.}

\item{\code{budget}}{A budget in $ that the agent should not exceed.}

\item{\code{budget_policy}}{A list controlling budget behavior: on_exceed and warn_at.}

\item{\code{budget_warned}}{Internal flag indicating whether warn_at notice was emitted.}

\item{\code{cost}}{The current cost of the agent}

\item{\code{tools}}{A list of registered tools available to the agent}
}
\if{html}{\out{</div>}}
}
\section{Active bindings}{
\if{html}{\out{<div class="r6-active-bindings">}}
\describe{
\item{\code{messages}}{Public active binding for the conversation history.
Assignment is validated automatically.}
}
\if{html}{\out{</div>}}
}
\section{Methods}{
\subsection{Public methods}{
\itemize{
\item \href{#method-Agent-new}{\code{Agent$new()}}
\item \href{#method-Agent-invoke}{\code{Agent$invoke()}}
\item \href{#method-Agent-generate_execute_r_code}{\code{Agent$generate_execute_r_code()}}
\item \href{#method-Agent-set_budget}{\code{Agent$set_budget()}}
\item \href{#method-Agent-set_budget_policy}{\code{Agent$set_budget_policy()}}
\item \href{#method-Agent-keep_last_n_messages}{\code{Agent$keep_last_n_messages()}}
\item \href{#method-Agent-add_message}{\code{Agent$add_message()}}
\item \href{#method-Agent-share_context_with}{\code{Agent$share_context_with()}}
\item \href{#method-Agent-clear_and_summarise_messages}{\code{Agent$clear_and_summarise_messages()}}
\item \href{#method-Agent-update_instruction}{\code{Agent$update_instruction()}}
\item \href{#method-Agent-get_usage_stats}{\code{Agent$get_usage_stats()}}
\item \href{#method-Agent-reset_conversation_history}{\code{Agent$reset_conversation_history()}}
\item \href{#method-Agent-export_messages_history}{\code{Agent$export_messages_history()}}
\item \href{#method-Agent-load_messages_history}{\code{Agent$load_messages_history()}}
\item \href{#method-Agent-validate_response}{\code{Agent$validate_response()}}
\item \href{#method-Agent-register_tools}{\code{Agent$register_tools()}}
\item \href{#method-Agent-list_tools}{\code{Agent$list_tools()}}
\item \href{#method-Agent-remove_tools}{\code{Agent$remove_tools()}}
\item \href{#method-Agent-clear_tools}{\code{Agent$clear_tools()}}
\item \href{#method-Agent-generate_and_register_tool}{\code{Agent$generate_and_register_tool()}}
\item \href{#method-Agent-clone_agent}{\code{Agent$clone_agent()}}
\item \href{#method-Agent-clone}{\code{Agent$clone()}}
}
}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-new"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-new}{}}}
\subsection{Method \code{new()}}{
Initializes a new Agent with a specific role/instruction.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$new(name, instruction, llm_object, budget = NA)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{name}}{A short identifier for the agent (e.g. `"translator"`).}

\item{\code{instruction}}{The system prompt that defines the agent's role.}

\item{\code{llm_object}}{The LLM object generate by ellmer (eg. output of ellmer::chat_openai)}

\item{\code{budget}}{Numerical 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.}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{  # 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
  )

}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-invoke"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-invoke}{}}}
\subsection{Method \code{invoke()}}{
Sends a user prompt to the agent and returns the assistant's response.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$invoke(prompt)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{prompt}}{A character string prompt for the agent to respond to.}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
The LLM-generated response as a character string.
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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")
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-generate_execute_r_code"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-generate_execute_r_code}{}}}
\subsection{Method \code{generate_execute_r_code()}}{
Generate R code from natural language descriptions and optionally validate/execute it
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$generate_execute_r_code(
  code_description,
  validate = FALSE,
  execute = FALSE,
  interactive = TRUE,
  env = globalenv()
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{code_description}}{Character string describing the R code to generate}

\item{\code{validate}}{Logical indicating whether to validate the generated code syntax}

\item{\code{execute}}{Logical indicating whether to execute the generated code (use with caution)}

\item{\code{interactive}}{Logical; if TRUE, ask for user confirmation before executing generated code}

\item{\code{env}}{Environment in which to execute the code if execute = TRUE. Default to \code{globalenv}}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
A list containing the generated code and validation/execution results
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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)
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-set_budget"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-set_budget}{}}}
\subsection{Method \code{set_budget()}}{
Set a budget to a specific agent, if the budget is reached, an error will be thrown
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$set_budget(amount_in_usd)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{amount_in_usd}}{Numerical value denoting the amount to set for the budget,}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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$
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-set_budget_policy"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-set_budget_policy}{}}}
\subsection{Method \code{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.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$set_budget_policy(on_exceed = "abort", warn_at = 0.8)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{on_exceed}}{One of "abort", "warn", or "ask".}

\item{\code{warn_at}}{Numeric in (0,1); fraction of budget to warn at. Default 0.8.}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\dontrun{
agent$set_budget(5)
agent$set_budget_policy(on_exceed = "ask", warn_at = 0.9)
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-keep_last_n_messages"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-keep_last_n_messages}{}}}
\subsection{Method \code{keep_last_n_messages()}}{
Keep only the most recent `n` messages, discarding older ones while keeping
the system prompt.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$keep_last_n_messages(n = 2)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{n}}{Number of most recent messages to keep.}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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)
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-add_message"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-add_message}{}}}
\subsection{Method \code{add_message()}}{
Add a pre-formatted message to the conversation history
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$add_message(role, content)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{role}}{The role of the message ("user", "assistant", or "system")}

\item{\code{content}}{The content of the message}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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!")
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-share_context_with"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-share_context_with}{}}}
\subsection{Method \code{share_context_with()}}{
Share the most recent conversation messages with another agent.

The last \code{n} non-system messages from \code{self} are appended to the
history of an other \code{agent}. This is useful when
one agent needs to handoff context or continue a thread in a separate
agent.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$share_context_with(agent, n = 5)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{agent}}{An object of class \code{Agent} that will receive the
messages.}

\item{\code{n}}{Number of recent messages to transfer (excluding the system prompt).
Defaults to \code{5}.}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-clear_and_summarise_messages"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-clear_and_summarise_messages}{}}}
\subsection{Method \code{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.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$clear_and_summarise_messages()}\if{html}{\out{</div>}}
}

\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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
}

}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-update_instruction"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-update_instruction}{}}}
\subsection{Method \code{update_instruction()}}{
Update the system prompt/instruction
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$update_instruction(new_instruction)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{new_instruction}}{New instruction to use. Not that the new instruction
will override the old one}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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.")
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-get_usage_stats"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-get_usage_stats}{}}}
\subsection{Method \code{get_usage_stats()}}{
Get the current token count and estimated cost of the conversation
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$get_usage_stats()}\if{html}{\out{</div>}}
}

\subsection{Returns}{
A list with token counts and cost information
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-reset_conversation_history"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-reset_conversation_history}{}}}
\subsection{Method \code{reset_conversation_history()}}{
Reset the agent's conversation history while keeping the system instruction
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$reset_conversation_history()}\if{html}{\out{</div>}}
}

\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-export_messages_history"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-export_messages_history}{}}}
\subsection{Method \code{export_messages_history()}}{
Saves the agent's current conversation history as a JSON file on disk.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$export_messages_history(
  file_path = paste0(getwd(), "/", paste0(self$name, "_messages.json"))
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{file_path}}{Character 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.}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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()
}

}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-load_messages_history"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-load_messages_history}{}}}
\subsection{Method \code{load_messages_history()}}{
Load an agent's conversation history as a JSON file from disk.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$load_messages_history(
  file_path = paste0(getwd(), "/", paste0(self$name, "_messages.json"))
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{file_path}}{Character 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.}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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
}

}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-validate_response"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-validate_response}{}}}
\subsection{Method \code{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).
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$validate_response(
  prompt,
  response,
  validation_criteria,
  validation_score = 0.8
)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{prompt}}{The prompt used to generate the response.}

\item{\code{response}}{The response text to validate.}

\item{\code{validation_criteria}}{The criteria for validation.
(e.g., "The response should be accurate and complete", "The response must be under 100 words").}

\item{\code{validation_score}}{A 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.}
}
\if{html}{\out{</div>}}
}
\subsection{Returns}{
list object
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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)
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-register_tools"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-register_tools}{}}}
\subsection{Method \code{register_tools()}}{
Register one or more tools with the agent
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$register_tools(tools)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{tools}}{A list of ellmer tool objects or a single tool object}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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()))
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-list_tools"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-list_tools}{}}}
\subsection{Method \code{list_tools()}}{
List all registered tools
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$list_tools()}\if{html}{\out{</div>}}
}

\subsection{Returns}{
Character vector of tool names
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\dontrun{
agent$list_tools()
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-remove_tools"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-remove_tools}{}}}
\subsection{Method \code{remove_tools()}}{
Remove tools from the agent
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$remove_tools(tool_names)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{tool_names}}{Character vector of tool names to remove}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\dontrun{
agent$remove_tools(c("change_directory", "list_files"))
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-clear_tools"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-clear_tools}{}}}
\subsection{Method \code{clear_tools()}}{
Clear all registered tools
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$clear_tools()}\if{html}{\out{</div>}}
}

\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\dontrun{
agent$clear_tools()
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-generate_and_register_tool"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-generate_and_register_tool}{}}}
\subsection{Method \code{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.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$generate_and_register_tool(description)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{description}}{Character string describing what the tool should do}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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()
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-clone_agent"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-clone_agent}{}}}
\subsection{Method \code{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.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$clone_agent(new_name = NULL)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{new_name}}{Optional character string to assign a new name to the cloned agent.
If NULL, the cloned agent retains the original name.}
}
\if{html}{\out{</div>}}
}
\subsection{Examples}{
\if{html}{\out{<div class="r example copy">}}
\preformatted{\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()
}
}
\if{html}{\out{</div>}}

}

}
\if{html}{\out{<hr>}}
\if{html}{\out{<a id="method-Agent-clone"></a>}}
\if{latex}{\out{\hypertarget{method-Agent-clone}{}}}
\subsection{Method \code{clone()}}{
The objects of this class are cloneable with this method.
\subsection{Usage}{
\if{html}{\out{<div class="r">}}\preformatted{Agent$clone(deep = FALSE)}\if{html}{\out{</div>}}
}

\subsection{Arguments}{
\if{html}{\out{<div class="arguments">}}
\describe{
\item{\code{deep}}{Whether to make a deep clone.}
}
\if{html}{\out{</div>}}
}
}
}
