agent() creates an ellmer::Chat subclass with tools and prompting that
allow the agent to navigate the data sources, semantic layer, and context
layer gathered by commons(). Depending on the agent's choice of tools,
responses can be deterministically classified as based on a trusted
calculation, cited, or untrusted.
Arguments
- client
An ellmer::Chat giving the provider and model to use, e.g.
ellmer::chat_anthropic(). For best results, enable thinking when supported by the selected provider and model. A system prompt already set on the client is ignored, with a warning; use theinstructionsargument ofcommons()to add to commons' prompt.- commons
A
commons()object holding the agent's data sources, semantic layer, context layer, and instructions.- ...
These dots are for future extensions and must be empty.
- mode
Which analysis paths the agent may take. One of:
"normal"(the default): the agent prefers trusted calculations and, when none answers the question, falls back to writing its own SQL and R code."trusted only": the agent answers only with trusted calculations: measures, governed metrics, and exact trusted queries. When none answers the question, it says so rather than writing its own code. The agent can still search context and inspect table schemas. Because every answer comes from a trusted calculation, answers carry no provenance markers, and the agent needs no sandboxed R session. The agent must have at least one trusted calculation.
- network
Whether the agent's R session has network access. One of
"none"(the default) or"full". Must be"none"whenmode = "trusted only", since that mode has no R session. The session uses OS sandboxing on Linux and macOS. On unsupported hosts, local development can opt in to best-effort R guardrails withoptions(commons.allow_unsafe_fallback = TRUE). These guardrails are not a security boundary.- log
Whether to request conversation trajectory capture with OpenTelemetry (default
FALSE). WhenTRUE, commons checks the tracing setup and warns with setup steps when it is incomplete. This feature requires Connect >= 2026.09.0.When deploying to Posit Connect, include
"OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"in theenvVarsargument torsconnect::deployApp()so ellmer includes message content. A server administrator must also setOpenTelemetry.Enabled = trueandOpenTelemetry.AllowContentInstrumentation = true.Once the agent is deployed and serving traffic, you can read conversation histories back into R with
trajectory_read(). Logging also records the authenticated Shiny session user, when supplied by Connect, for attribution.An optional character vector of Connect usernames granted access to this content's trajectories when running on Posit Connect. Reading traces requires editor-level access, so named users are added as collaborators on the content. Named users must have at least a publisher account.
Value
An ellmer::Chat subclass.
Details
The provider and model come from client; commons sets its own system prompt
and tools. Use agent$chat() to ask questions, commons_theme() and
commons_server() to embed the agent in Shiny, and vitals::generate()
to use the agent as a vitals solver.
Cache pre-warming
A commons agent builds its context search index and downloads uncached pins
the first time it needs them. commons_server() and commons_app() call the
agent's prewarm() method automatically during post-startup idle time.
To warm the caches before deployment, call agent$prewarm() in a
pre-deploy script. The context index is cached on disk once per version of
the context documents; pin downloads populate the local pins cache.
To ship a pre-built context index with an app, configure a directory inside the app in both the pre-deploy script and the deployed app, then prewarm the agent before deploying:
options(commons.context_cache = "commons-cache")
agent <- agent(
ellmer::chat_anthropic(),
commons = commons(data_sources = data_source(sales = sales))
)
agent$prewarm()Do not use app_cache/ for this workflow because rsconnect excludes it from
deployed bundles. Without explicit configuration, commons uses Connect's
persistent content data directory when available, an app_cache/ directory
beside hosted apps, or the per-user cache directory. Set the cache directory
with options(commons.context_cache = "path/to/dir") or the
COMMONS_CONTEXT_CACHE environment variable. Set the option to FALSE to
disable persistence. The cache is capped at 256 MB with least-recently-used
eviction; change the cap with options(commons.context_cache_max_size).
Agent tools
Depending on its semantic layer, context layer, data sources, and mode, a
commons agent receives some combination of these tools:
search_poolsearches trusted calculations and semantic models.search_catalogsearches a warehouse catalog.call_measureinvokes an R measure.call_metricsinvokes governed or warehouse-native metrics.call_calculationinvokes an exact trusted query.search_contextretrieves relevant business context.load_skillloads instructions for a task, such as explaining how commons determines and displays answer trust.describe_tableinspects a table or semantic model.run_sqlexecutes a read-only SQL query.run_rexecutes R code to analyze results and render plots in the agent's R session.edit_artifactedits a document the agent wrote.
With mode = "trusted only", the agent never receives run_sql, run_r,
or edit_artifact.
Documents
When a user asks for a report, the agent writes a Quarto document instead
of a chat reply. In commons_server(), the document streams into the chat's
drawer as it's written, with each R cell knitted as soon as it arrives;
outside Shiny, agent$chat() knits it and reports where it wrote the
result.
A document gets its data by calling the commons() object's
$measure(), $metrics(), $calculation(), and $run_sql() methods in its
code. The code runs in a fresh sandboxed R session, with the same
restrictions as run_r, where commons is a stand-in that asks the app to
run each call and returns the result; the data sources never enter the
sandbox. The saved source keeps its commons$ calls, so it renders
wherever a commons object is defined. Quarto isn't needed to show
documents, only to render the saved source elsewhere. A trusted-only agent doesn't write
documents, since their code is the agent's own.
These model-facing tools should be considered private. Their constructors
are intentionally not exported, and their names, arguments, availability,
and behavior may change without notice. Application code should configure
an agent through agent(), commons(), and the layer constructors rather
than depend on individual tools.
Examples
if (FALSE) { # \dontrun{
# A measure over local data computes directly in R.
sem <- semantic_layer(
measure(
"order_count",
"Count of orders.",
function() nrow(my_sales),
arguments = list()
)
)
agent <- agent(
ellmer::chat_anthropic(),
commons = commons(
data_sources = data_source(sales = my_sales),
semantic_layer = sem
)
)
agent$chat("How many orders are there?")
# A measure takes a connection as an argument named after a data source.
# `warehouse` isn't in `arguments`, so the model never sees it; commons
# supplies it when the measure runs. Bind model-supplied arguments through
# DBI so they're quoted safely.
con <- DBI::dbConnect(duckdb::duckdb())
sem <- semantic_layer(
measure(
"revenue_by_region",
"Total revenue for a region.",
function(region, warehouse) {
DBI::dbGetQuery(
warehouse,
"SELECT sum(revenue) AS revenue FROM sales WHERE region = ?",
params = list(region)
)
},
arguments = list(region = ellmer::type_string("Sales region."))
)
)
agent <- agent(
ellmer::chat_anthropic(),
commons = commons(
data_sources = list(warehouse = data_source(con)),
semantic_layer = sem
)
)
# Objects that aren't data sources (a pins board, an API client) come from
# argument defaults in the measure, e.g. `board = pins::board_connect()`.
# See ?semantic_layer.
} # }
