The main class for creating AI agents that can use tools to accomplish tasks. Agent wraps an ellmer Chat object and adds agentic capabilities including multi-turn execution, permission enforcement, and streaming output.
Skill Methods
The following methods manage skills:
$load_skill(skill, allow_conflicts = FALSE)Load a Skill into the agent. The
skillparameter can be a Skill object or path to a skill directory. Ifallow_conflictsis FALSE (default), an error is thrown when skill tools conflict with existing tools. Set to TRUE to allow overwriting. Returns invisible self.$skills()Get a named list of loaded Skill objects.
MCP Methods
The following methods manage MCP (Model Context Protocol) server tools:
$load_mcp(config = NULL, servers = NULL)Load tools from MCP servers. The
configparameter specifies the path to the MCP config file (defaults to~/.config/mcptools/config.json). Theserversparameter optionally filters to specific server names. Requires the mcptools package. Returns invisible self.$mcp_tools()Get names of loaded MCP tools.
Public fields
chatThe wrapped ellmer Chat object
permissionsPermission policy for the agent
working_dirWorking directory for file operations
hooksHook registry for lifecycle events
Methods
Method new()
Create a new Agent.
Arguments
chatAn ellmer Chat object created by
ellmer::chat()or provider-specific functions likeellmer::chat_openai().toolsA list of tools created with
ellmer::tool(). Seetools_file()andtools_code()for built-in tool bundles.system_promptOptional system prompt. If provided, overrides the chat object's existing system prompt.
permissionsA Permissions object controlling what the agent can do. Defaults to
permissions_standard().working_dirWorking directory for file operations. Defaults to current directory.
Method run()
Run an agentic task with streaming output.
Returns a generator that yields AgentEvent objects as the agent works. The agent will continue until the task is complete, max_turns is reached, or the cost limit is exceeded.
Arguments
taskThe task for the agent to perform
max_turnsMaximum number of turns (default: from permissions)
Returns
A generator yielding AgentEvent objects
Method run_sync()
Run an agentic task and block until completion.
Convenience wrapper around run() that collects all events and returns
an AgentResult.
Arguments
taskThe task for the agent to perform
max_turnsMaximum number of turns (default: from permissions)
Returns
An AgentResult object
Method register_tool()
Register a tool with the agent.
Arguments
toolA tool created with
ellmer::tool()
Method register_tools()
Register multiple tools with the agent.
Arguments
toolsA list of tools created with
ellmer::tool()
Method add_hook()
Add a hook to the agent.
Hooks are called at specific points during agent execution and can modify behavior (e.g., deny tool calls, log events).
Arguments
hookA HookMatcher object
Examples
\dontrun{
# Add a hook to block dangerous bash commands
agent$add_hook(hook_block_dangerous_bash())
# Add a custom PreToolUse hook
agent$add_hook(HookMatcher$new(
event = "PreToolUse",
pattern = "^write_file$",
callback = function(tool_name, tool_input, context) {
cli::cli_alert_info("Writing to: {tool_input$path}")
HookResultPreToolUse(permission = "allow")
}
))
}
Method save_session()
Save the current session to an RDS file.
Method load_session()
Load a session from an RDS file.
Method compact()
Compact the conversation history to reduce context size.
This method uses the LLM to generate a meaningful summary of older conversation turns, then replaces them with the summary appended to the system prompt. This preserves important context while reducing token usage.
Arguments
keep_lastNumber of recent turns to keep uncompacted (default: 4)
summaryOptional custom summary to use instead of auto-generating. If NULL, the LLM will generate a summary focusing on key decisions, findings, files discussed, and task progress.
Details
The compaction process:
Fires the PreCompact hook (can cancel or provide custom summary)
If no custom summary, uses LLM to summarize compacted turns
Appends summary to system prompt under "Previous Conversation Summary"
Keeps only the most recent
keep_lastturns
If LLM summarization fails (e.g., no API key), falls back to a simple text-based summary with truncated turn contents.
Method load_mcp()
Load tools from MCP (Model Context Protocol) servers.
Requires the mcptools package. Issues a warning if not installed or if tool fetching fails.
Examples
if (FALSE) { # \dontrun{
# Create an agent with file tools
agent <- Agent$new(
chat = ellmer::chat("openai/gpt-4o"),
tools = tools_file()
)
# Run a task with streaming output
for (event in agent$run("List files in the current directory")) {
if (event$type == "text") cat(event$text)
}
# Or use the blocking convenience method
result <- agent$run_sync("List files")
print(result$response)
} # }
## ------------------------------------------------
## Method `Agent$add_hook`
## ------------------------------------------------
if (FALSE) { # \dontrun{
# Add a hook to block dangerous bash commands
agent$add_hook(hook_block_dangerous_bash())
# Add a custom PreToolUse hook
agent$add_hook(HookMatcher$new(
event = "PreToolUse",
pattern = "^write_file$",
callback = function(tool_name, tool_input, context) {
cli::cli_alert_info("Writing to: {tool_input$path}")
HookResultPreToolUse(permission = "allow")
}
))
} # }