Skip to contents

peter() is the single entry point. Give it a quoted prompt and, optionally, the objects the agent should work on; it returns the agent session, which you can print, query ($text, $value, $usage) and continue with the pipe. Models, modes, skills, plugins, extensions and tools may be written as bare names.

Usage

peter(..., model = NULL, mode = NULL, skills = NULL, plugins = NULL,
      extensions = NULL, tools = NULL, agents = NULL, parallel = NULL,
      choices = NULL, levels = NULL, threshold = 0.5,
      min_confidence = NULL, uncertain = NULL,
      prompt = NULL, envir = parent.frame(), background = FALSE,
      budget = NULL, replay = NULL, .opts = list(), .run = TRUE,
      .stdin = FALSE)

Arguments

...

A session to continue, the prompt, and context objects. A decision model reads a named object under its name (text = x) and any other as input, so its answers and cache entries never depend on how a variable is named or subset.

model

A model name (sonnet, "anthropic/claude-sonnet-5-5", "codex/default"; an id the catalog lacks is written in, see gptr_models()), a provider or router spec such as gptr_fake_provider(), or NULL for the configured default (gptr_config()). A call made by the agent's own R code, and a team or fan-out it starts, uses the running session's model instead.

mode

One of plan, manual, edits, auto, yolo; NULL for the configured default, auto unless gptr_config() sets another (see gptr_security). The plan a plan run proposes goes once, as a <plan> block, to the next top-level peter() call from the same environment, within an hour and in another mode, whatever that call asks: a script runs the plan with peter("Go ahead.", mode = auto). Another peter() call first, or a next call inside a loop or a run, discards it; options(gptr.plan_handoff = FALSE) turns the hand-off off. Interactively a plan run then asks whether to execute the plan: a mode chosen there is the session's, and its next prompt, such as Go ahead., runs the plan.

skills, plugins, extensions

Names (bare or quoted) of skills to preload, plugins and extensions to enable for this session; extensions also takes function(gptr) factories and file paths.

tools

Tool names, "+name"/"-name" modifiers, one preset name, or gptr_tool() specs. A bare tool name adds the tool, like "+name"; to narrow the set, choose a preset such as readonly or remove tools with "-name". A name that is neither a tool nor a preset is refused.

agents

A named list of agent definitions for a team (agent() means gptr_agent()). A decision model refuses it and parallel: it answers in one call.

parallel

Fan one list-like context object out over this many concurrent sub-agents. Each child gets its element alone as .x, a named list of one attached as .x[["A"]]; .opts = list(context = "none"), which would drop it, is refused. A child that succeeds keeps only the values it returned with gptr_return(), so they must be self-contained.

choices, levels, threshold

System 1 answer shape, for a decision model ("jev", "ollama/clef-flash"; after gptr_config(system1 = "emulate:<ref>"), model = "jev" runs it through a chat model). The default is a logical gptr_decision, TRUE when P(yes) is at least threshold; choices give a gptr_choice of labels; ordered levels give a gptr_score, the expected 0-based level (0 to k - 1), whose level probabilities gptr_prob(x, "probabilities") returns. A conversational model refuses them, min_confidence and uncertain (threshold only when it is not 0.5) rather than ignore them. choices given as a factor, or .opts = list(output = "factor"), return a plain factor with those levels and no probabilities or confidence.

min_confidence

A number from 0 to 1. An answer whose confidence is below it is uncertain, as is an unknown confidence unless it is 0. A decision's confidence is abs(2 * p - 1), so 0.8 keeps only P(yes) at most 0.1 or at least 0.9. For choices and scores it is the engine's own scale, so a value tuned on Jev abstains differently on Clef (see gptr_prob()).

uncertain

What an uncertain answer becomes: NA (the default), TRUE or FALSE (yes/no only), function(state, answer) returning one replacement of the answer's type, or "stop" for a gptr_error_s1_uncertain error. It has no effect without min_confidence.

prompt

An explicit prompt; wins over positional selection.

envir

Where the agent evaluates R code and creates objects. A call made by the agent's own R code without envir evaluates in a new environment whose parent is the caller's, res$envir: it reads the caller's objects and keeps the ones it creates there. A function frame (the default inside a function, or environment()) serves only that call, so the session keeps no workspace for later turns; pass envir = new.env() to keep one.

background

Experimental: return the running session at once (needs later).

budget

list(tokens =, cost =, turns =) limits for this call. turns counts model requests, retries and sub-agents' requests included; session$turns counts prompts instead. cost counts priced requests only: a model without prices (such as Codex, or a gptr_provider() without prices) has an unknown cost that counts nothing, so the call says once that its cost limit is not enforced; the tokens and turns limits still apply.

replay

Document replay mode: "auto", "replay", "live" or "record".

.opts

Rare switches such as thinking, max_turns, context, returns, images, preset, and entries named by a plugin namespace. thinking applies to this call and to the session's later turns; max_turns caps this call's model requests.

.run

FALSE builds the session with the prompt queued and returns it (see gptr_step()). Building checks egress and replay only; gptr_step() and gptr_wait() check the model's provider and key before they start the run. A piped .run = FALSE call applies its model, mode and tools at once; a gptr_step() or gptr_wait() that then refuses leaves them, with no turn.

.stdin

Drive the console from piped standard input.

Value

A gptr_session for agent work (invisibly when its answer was streamed to the console), or a typed System 1 vector for classifier models.

Details

Conversational agents compute in memory: their R tools use the objects already loaded in envir, and later turns can reuse fitted models and intermediate results without saving and reloading the dataset. R computes on the full objects, while the model receives size-limited descriptions, previews and tool output that may include data values. Ordinary R allocations, file-backed inputs, checkpoints and worker transfers still have their usual costs. See vignette("execution-model", package = "gptr") for these boundaries.

Agent code runs in this R process: a program it starts with system() or system2() reads standard input from your terminal and prints there, out of the agent's sight, so the agent is told, except under the "minimal" preset that sub-agents run, to use peter$sh() instead.

The dots take, in order: at most one leading session to continue, the prompt (the first unnamed string literal, else the first unnamed length-1 character value), and context objects (unnamed ones are labeled by their expression, named ones by name). Conversational context bindings refer to objects where they live; descriptions are budgeted separately from in-memory R computation. Every other argument is matched by its exact name only: a named object whose name abbreviates one and whose value fits it, such as mo = "plan", or a string named as an gptr_agent() option, such as export = "fit", stays context and warns (gptr_warning_partial_name).

A literal prompt gets {name} interpolation from envir (atomic vectors of 1 to 50 values; {{ and }} are literal braces); .opts = list(interpolate = FALSE) switches it off.

Terminal statuses become conditions carrying the session as $session: error signals gptr_error_provider, blocked gptr_error_permission (gptr_error_noninteractive when the ask tool has no one to answer), budget gptr_error_budget_<kind> and max_turns gptr_error_max_turns. A team (agents =) or fan-out (parallel =) takes the status of its first member that did not end idle, with $reason naming each such member; when no member ended idle it signals that member's condition with the team as $session. A call whose model cannot be reached (no egress acknowledgment, replay mode, a disabled provider, a missing key) is refused before its run: no turn, no model or mode switch, no new gptr_last() and no $session. So is a call with an unknown plugin or skills = name, .opts$images its model does not take, or a secret-looking prompt you decline to send. A piped call loads its extensions, plugins and specs first, since they can define that model, and unloads them again when it is refused or interrupted before its turn starts; registry filters (plugins = "-x") stay on the R session only once a call is accepted. peter() with no prompt opens the console when someone can answer, and signals gptr_error_noninteractive otherwise.

A new interactive console without an explicit or configured model first offers CLI selection or manual API/Ollama instructions. Selecting an available CLI saves <route>/default, the model that CLI starts with, at user scope; cancellation (choose Cancel or press Enter) or manual setup returns without starting a session. Existing sessions, explicit or configured models and .stdin = TRUE skip setup. CLI-reported login is not proof of online access or subscription billing. See vignette("interactive-console", package = "gptr").

gptr reads as a grammar for Peter, after Peter Naur and Peter Cathcart Wason. In the spirit of Naur's readable language definitions, gptr records sessions as runnable documents; Wason's reasoning research with Jonathan Evans inspires its System 1 and System 2 roles. See vignette("why-peter", package = "gptr") for the history and sources. A user object named peter hides the gateway; call gptr::peter() then.

The interactive console

peter() without a prompt opens a console when someone can answer (interactive R or IRkernel); peter(.stdin = TRUE) reads its input from standard input, and session |> peter() opens it on session. With no explicit or configured model, the interactive console first offers Codex CLI, Claude Code CLI or API configuration instructions. Choosing an available CLI saves its default model at user scope; cancelling returns to R. Piped input skips this setup. Each input is one of:

  • a prompt, sent as session |> peter("...") with {name} interpolation; @file adds the head of a file (at most 40 lines; the files of one prompt share about 2,000 tokens) and @object attaches an object by name;

  • !code: R code run in the session's environment; the code and its output go with the next prompt (at most 300 estimated tokens). !!code omits that note. Both execute your own R immediately, without the model's permission gate or a model request. Workspace changes remain visible to later calls, and enabled transcripts can record the code; !! is not a privacy boundary. A fenced block marked r, R, {r} or unmarked works like !code (other fences are prompt text), a """ block is a multi-line prompt, and a trailing backslash continues a line;

  • a slash command such as /model, /mode, /cost or /exit; /help lists them all.

Each tool call shows as one row: the tool, the first line of its code and (+N more lines), then what changed (an edit's added and removed lines, an error's message in up to six wrapped rows); what R code prints shows at most 5 rows a call, then (+N more lines); what the model receives is unchanged. An approval shows the code it asks about. /calls [n] prints this session's last n tool calls whole (default 1): all their code, and what an edit or a write changes, including the calls a CLI route makes to gptr's tools; a sub-agent's calls and the steps a CLI route runs itself, such as Codex's shell, are not among them. gptr_config(compact_calls = FALSE) shows every call's code as it runs (at most 20 rows) and all its output.

In CRAN's R for macOS in a terminal a pasted block is one input: its lines join the first one and ... waits for Enter (text typed there is added); a pasted fence or """ block is read up to its closer at once, a block pasted at an approval or a choice is kept in the console history and the question asked again, and one pasted at the pause menu's steer> or next> is the whole text. A last pasted line without a newline waits for Enter at the next prompt, so a two-line paste without a final newline answers a question with its first line. Elsewhere (Homebrew or conda R, Linux terminals, RStudio, R.app, Positron, Windows) pasted lines arrive one at a time, as typed lines do (at a question the first one answers it); wrap a multi-line paste in """. Lines typed, pasted or run from a script before a question (an approval, a choice) appeared never answer it: while an answer runs they are queued for the agent as type_ahead says (below; a /command or !code line waits for the next prompt), otherwise they go to the console history. Answer after the prompt, which is indented two columns under the question: only what you send to the agent starts at the left edge, as peter> , steer> or next> .

What you type while peter works, and the key that pauses it, depend on the console:

ConsoleTyped while peter worksPause
Terminal R on macOS or Linux, an IDE's Terminal taba draft: Enter steers, Tab sends a follow-upCtrl-C
TERM=dumb, Emacs shell, ESSeach line, as type_ahead saysCtrl-C
RStudio, R.appthe next prompt, unless a question reads itEsc
PositronR code, run after peter() returnsCtrl-C
Windows Rtermthe next prompt, unless a question reads itCtrl-C
Windows Rgui, Jupyterthe next inputnone: Esc or interrupt stops
Rscript, pipes, knitrnothing; .stdin = TRUE reads the pipenone

In terminal R and an IDE's Terminal tab what you type while peter works is a draft on the bottom row, under the transcript, so it never mixes into the answer; a block pasted there is one message where the terminal supports bracketed paste. Enter sends it as a steer and writes it into the transcript at once, as steer> <text>: the agent reads it at its next step boundary, when the response in flight ends after the results of all its tool calls (an answer about to end gets one more request). Tab sends it as a follow-up, written as next> <text>: the next prompt, sent as its own run once the answer ends. type_ahead = "follow_up" (gptr_config()) swaps the two keys. A draft that starts with / or ! is always a follow-up, so /command and !code lines run at the next prompt, in the order typed. The bottom row counts what is queued (1 steer queued); Up on an empty draft takes back the newest message not yet delivered, to edit and send again, and Ctrl-U clears the draft. A question (an approval, a choice) waits until typing pauses for a second, or three while the draft has text, and the draft stays: through questions, Ctrl-C and the pause menu, and to the next prompt, where Enter sends it. Keys typed while R code runs in this process (the r tool) show when it returns. Such code that reads the terminal through readline() or menu() inside another function shows only that read's prompt (the text printed before it shows when the code returns, the typed answer never), and Ctrl-C at that read aborts the answer instead of pausing it. A steer the answer did not take (it ended first) is the next prompt; after an abort or an error nothing queued is sent: the queued text and the draft go to the console history, and Up recalls them. Under TERM=dumb or in ESS a line typed with Enter is queued as type_ahead says. On the CLI routes (claude-cli, codex) the agent reads a steer after the CLI's answer, which is often the whole run: once the run has sent its request, the receipt says so, (after the CLI's answer); a steer sent before the first request goes with it.

RStudio, R.app, Positron and Windows consoles hold what is typed until R reads again. In RStudio, R.app and Windows consoles a line typed while peter works is the next prompt, one prompt per line, unless a question comes first: it reads the line, queues it as type_ahead says and asks again. Positron's console keeps typed text as R code, which runs after peter() returns, and clears it at Ctrl-C. To steer in these consoles, pause and press s (Windows' Rgui cannot pause), as their banner says: esc, then s, to steer in RStudio and R.app, ctrl-c, then s, to steer in Positron and Windows' Rterm. In RStudio an Esc first closes RStudio's own completion list, if open, then clears a line being typed, so the menu comes at the next Esc. During peter("...") at R's prompt, outside the chat, typed lines stay R's next input.

Tab completes only after @ (objects, then files), @obj$ (its members), peter$, a leading / (commands) and on a ! or !! line (R code), never in plain text: in terminal R, R in an IDE's Terminal tab, Windows' Rgui and Rterm, and RStudio's console, which completes only what its popup inserts as offered (the commands after / and R code after !, not words holding @ or $, which it would wrap in backticks). In a terminal Tab completes the draft the same way while peter works, and on such a word never sends it. R.app, radian and Positron's console keep their own completion. gptr never changes RStudio's preferences: as you type in its console, RStudio adds closing brackets and quotes unless insert_matching is off, and opens completions unless console_code_completion is off (Tools > Global Options > Code).

The pause key opens a pause menu while an answer runs, with the keys s steer, f follow-up, c continue, a abort and, for a foreground call (a chat turn included) when available, b background. s and f read the text at steer> and next> and queue it as Enter and Tab do; in a peter("...") call a follow-up is sent when the agent would otherwise stop. A key typed right after the pause key answers the menu. Continuing leaves the work as if it had not paused, and pressing the pause key again aborts. Abort keeps the partial session; what you queued and the draft go to the history, unsent. Background returns to the chat prompt and keeps the run: what was queued for after the answer and the draft go to the history, unsent, as after an abort, and another prompt steers the running session. Nothing runs it while the chat waits for input: use !!gptr::gptr_wait(gptr::gptr_last()) there to continue it, its answer then shown as a prompt's and Enter steering it. Under Rscript, background runs advance only inside blocking gptr calls. Where an interrupt cannot be resumed (Windows' Rgui, Jupyter) the key stops the answer instead.

/exit, two consecutive interrupts at the prompt or the end of piped input return the session invisibly, so session = peter() keeps the conversation. In a terminal the chat reads keys with the terminal's echo off and restores it on return, on an error, at an interrupt and at q(); if R is killed or crashes while peter works, type reset and press Enter to get the terminal back.

Options: gptr.verbose (0 silent, 1 progress, 2 streamed console, 3 debug; default 0 in knitr and testthat, 1 under Rscript, 2 at the console), gptr.max_turns_console (turns per console prompt, default 200) and gptr.history (console inputs to R's history, default TRUE). Ordinary progress uses normal output; actual errors use stderr. vignette("interactive-console", package = "gptr") gives input examples and the complete built-in command table.

Sessions and results

A pipe such as session |> peter("Explain the result.") adds work to the same session and kept workspace. Use gptr_fork() to branch explicitly. The last turn's answer is session$text; session$value is the newest R value selected by gptr_return() in any turn, so a turn that selects none keeps it. Agent-created objects remain in envir.

Finding APIs

Inside agent R code, peter$search("provider setup") searches callable members, skills, tools and gptr's public APIs and help topics; API rows follow the members, skills and tools it finds and fill the rows they leave free. peter$help("gptr") lists the functions and topics; peter$help("gptr::gptr_mcp_add") reads installed help. Add source = TRUE for bounded function-definition text, without executing it. Private source requires an explicit name such as peter$help("gptr:::member_help", source = TRUE); private functions are not supported APIs. Documentation and source are loaded on demand rather than added to every prompt.

See also

Examples

fake = gptr_fake_provider(list("The data has 32 rows.", "The data has 11 columns."))
session = peter("How many rows does the data have?", mtcars, model = fake)
#> gptr: thinking
#> gptr: done · fake-1 · 1 request · 1.6k tokens · 99% context left
session$text
#> [1] "The data has 32 rows."
session |> peter("And how many columns?")
#> gptr: thinking
#> gptr: done · fake-1 · 1 request · 1.6k tokens · 99% context left
#> The data has 11 columns.
#> idle · fake/fake-1 · 2 turns · 3.2k tokens · $0.0000 · s1b5e29fe4f
identical(gptr_last(), session)
#> [1] TRUE