| Title: | Unified Interface for AI Model Providers |
|---|---|
| Description: | A production-grade AI toolkit for R featuring a layered architecture (Specification, Utilities, Providers, Core), request interception support, robust error handling with exponential retry delays, support for multiple AI model providers ('OpenAI', 'Anthropic', etc.), local small language model inference, distributed 'MCP' ecosystem, multi-agent orchestration, progressive knowledge loading through skills, and a global skill store for sharing AI capabilities. |
| Authors: | Yonghe Xia [aut, cre] |
| Maintainer: | Yonghe Xia <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.4.12 |
| Built: | 2026-06-02 18:53:56 UTC |
| Source: | https://github.com/cran/aisdk |
A production-grade AI SDK for R featuring a layered architecture, middleware support, robust error handling, and support for multiple AI model providers.
The SDK uses a 4-layer architecture:
Specification Layer: Abstract interfaces (LanguageModelV1, EmbeddingModelV1)
Utilities Layer: Shared tools (HTTP, retry, registry, middleware)
Provider Layer: Concrete implementations (OpenAIProvider, etc.)
Core Layer: High-level API (generate_text, stream_text, embed)
library(aisdk)
# Create an OpenAI provider
openai <- create_openai()
# Generate text
result <- generate_text(
model = openai$language_model("gpt-4o"),
prompt = "Explain R in one sentence."
)
print(result$text)
# Or use the registry for cleaner syntax
get_default_registry()$register("openai", openai)
result <- generate_text("openai:gpt-4o", "Hello!")
Maintainer: Yonghe Xia [email protected]
Useful links:
Report bugs at https://github.com/YuLab-SMU/aisdk/issues
R6 class representing an AI agent. Agents are the worker units in the multi-agent architecture. Each agent has a name, description (for semantic routing), system prompt (persona), and a set of tools it can use.
Key design principle: Agents are stateless regarding conversation history. The ChatSession holds the shared state (history, memory, environment).
nameUnique identifier for this agent.
descriptionDescription of the agent's capability. This is the "API" that the LLM Manager uses for semantic routing.
system_promptThe agent's persona/instructions.
toolsList of Tool objects this agent can use.
skill_registryOptional registry of local skills available to the agent.
modelDefault model ID for this agent.
capability_modelsOptional capability-specific model routes.
new()
Initialize a new Agent.
Agent$new( name, description, system_prompt = NULL, tools = NULL, skills = NULL, model = NULL, capability_models = NULL )
nameUnique name for this agent (e.g., "DataCleaner", "Visualizer").
descriptionA clear description of what this agent does. This is used by the Manager LLM to decide which agent to delegate to.
system_promptOptional system prompt defining the agent's persona.
toolsOptional list of Tool objects the agent can use.
skillsOptional character vector of skill paths or "auto" to discover skills. When provided, this automatically loads skills, creates tools, and updates the system prompt.
modelOptional default model ID for this agent.
capability_modelsOptional named list of capability-specific model routes.
An Agent object.
run()
Run the agent with a given task.
Agent$run( task, session = NULL, context = NULL, model = NULL, max_steps = 10, ... )
taskThe task instruction (natural language).
sessionOptional ChatSession for shared state. If NULL, a temporary session is created.
contextOptional additional context to inject (e.g., from parent agent).
modelOptional model override. Uses session's model if not provided.
max_stepsMaximum ReAct loop iterations. Default 10.
...Additional arguments passed to generate_text.
A GenerateResult object from generate_text.
stream()
Run the agent with streaming output.
Agent$stream( task, callback = NULL, session = NULL, context = NULL, model = NULL, max_steps = 10, ... )
taskThe task instruction (natural language).
callbackFunction to handle streaming chunks: callback(text, done).
sessionOptional ChatSession for shared state.
contextOptional additional context to inject.
modelOptional model override.
max_stepsMaximum ReAct loop iterations. Default 10.
...Additional arguments passed to stream_text.
A GenerateResult object (accumulated).
as_tool()
Convert this agent to a Tool.
Agent$as_tool()
This allows the agent to be used as a delegate target by a Manager agent. The tool wraps the agent's run() method and uses the agent's description for semantic routing.
A Tool object that wraps this agent.
create_session()
Create a stateful ChatSession from this agent.
Agent$create_session(model = NULL, ...)
modelOptional model override.
...Additional arguments passed to ChatSession$new.
A ChatSession object initialized with this agent's config.
print()
Print method for Agent.
Agent$print()
clone()
The objects of this class are cloneable with this method.
Agent$clone(deep = FALSE)
deepWhether to make a deep clone.
Testing infrastructure for LLM-powered code. Provides testthat integration with custom expectations for evaluating AI agent performance, tool accuracy, and hallucination rates.
Factory functions for creating standard library agents for common tasks. These agents are pre-configured with appropriate system prompts and tools for their respective specializations.
AgentRegistry R6 class for storing and retrieving Agent instances. Used by the Flow system for agent delegation.
R6 class for managing a collection of Agent objects. Provides storage, lookup, and automatic delegation tool generation for multi-agent systems.
new()
Initialize a new AgentRegistry.
AgentRegistry$new(agents = NULL)
agentsOptional list of Agent objects to register immediately.
register()
Register an agent.
AgentRegistry$register(agent)
agentAn Agent object to register.
Invisible self for chaining.
get()
Get an agent by name.
AgentRegistry$get(name)
nameThe agent name.
The Agent object, or NULL if not found.
has()
Check if an agent is registered.
AgentRegistry$has(name)
nameThe agent name.
TRUE if registered, FALSE otherwise.
list_agents()
List all registered agent names.
AgentRegistry$list_agents()
Character vector of agent names.
get_all()
Get all registered agents.
AgentRegistry$get_all()
List of Agent objects.
unregister()
Unregister an agent.
AgentRegistry$unregister(name)
nameThe agent name to remove.
Invisible self for chaining.
generate_delegate_tools()
Generate delegation tools for all registered agents.
AgentRegistry$generate_delegate_tools( flow = NULL, session = NULL, model = NULL )
flowOptional Flow object for context-aware execution.
sessionOptional ChatSession for shared state.
modelOptional model ID for agent execution.
Creates a list of Tool objects that wrap each agent's run() method. These tools can be given to a Manager agent for semantic routing.
A list of Tool objects.
generate_prompt_section()
Generate a prompt section describing available agents.
AgentRegistry$generate_prompt_section()
Creates a formatted string listing all agents and their descriptions. Useful for injecting into a Manager's system prompt.
A character string.
print()
Print method for AgentRegistry.
AgentRegistry$print()
clone()
The objects of this class are cloneable with this method.
AgentRegistry$clone(deep = FALSE)
deepWhether to make a deep clone.
Analyze an image with a multimodal language model.
analyze_image(model, image, prompt, system = NULL, registry = NULL, ...)analyze_image(model, image, prompt, system = NULL, registry = NULL, ...)
model |
A |
image |
Image source accepted by |
prompt |
Prompt describing the analysis task. |
system |
Optional system prompt. |
registry |
Optional provider registry. |
... |
Additional arguments passed to |
A GenerateResult.
Provider class for Anthropic. Can create language models.
specification_versionProvider spec version.
new()
Initialize the Anthropic provider.
AnthropicProvider$new( api_key = NULL, base_url = NULL, api_version = NULL, headers = NULL, name = NULL, timeout_seconds = NULL, total_timeout_seconds = NULL, first_byte_timeout_seconds = NULL, connect_timeout_seconds = NULL, idle_timeout_seconds = NULL )
api_keyAnthropic API key. Defaults to ANTHROPIC_API_KEY env var.
base_urlBase URL for API calls. Defaults to https://api.anthropic.com/v1.
api_versionAnthropic API version header. Defaults to "2023-06-01".
headersOptional additional headers.
nameOptional provider name override.
timeout_secondsLegacy alias for total_timeout_seconds.
total_timeout_secondsOptional total request timeout in seconds for API calls.
first_byte_timeout_secondsOptional time-to-first-byte timeout in seconds for API calls.
connect_timeout_secondsOptional connection-establishment timeout in seconds for API calls.
idle_timeout_secondsOptional stall timeout in seconds for API calls.
enable_caching()
Enable or disable prompt caching.
AnthropicProvider$enable_caching(enable = TRUE)
enableLogical.
language_model()
Create a language model.
AnthropicProvider$language_model(model_id = "claude-sonnet-4-20250514")
model_idThe model ID (e.g., "claude-sonnet-4-20250514", "claude-3-5-sonnet-20241022").
An AnthropicLanguageModel object.
clone()
The objects of this class are cloneable with this method.
AnthropicProvider$clone(deep = FALSE)
deepWhether to make a deep clone.
Provides diagnostic tools to test internet connectivity, DNS resolution, and API reachability.
Convert common vector-like and tabular objects into a short text preview for summaries and inspection output.
as_preview_text(x, max_items = 5)as_preview_text(x, max_items = 5)
x |
Object to preview. |
max_items |
Maximum number of items or rows to include. |
A character string preview or NULL when no preview is available.
Collect recent R error context, active script context, session information,
and workspace object summaries, then open console_chat() with that context
as the initial prompt.
Collects the recent R error/session context and opens console_chat() with
that context as the first user message. In RStudio, this function also reads
the active source document when available, making it suitable as an Addin
binding.
ask_ai( prompt = NULL, model = NULL, skills = "auto", skill = NULL, context = NULL, startup_dir = getwd(), working_dir = tempdir(), sandbox_mode = "permissive", stream = TRUE, verbose = FALSE, show_context = FALSE, max_context_chars = Inf, max_error_age_secs = 300, confirm_stale_errors = TRUE, ... )ask_ai( prompt = NULL, model = NULL, skills = "auto", skill = NULL, context = NULL, startup_dir = getwd(), working_dir = tempdir(), sandbox_mode = "permissive", stream = TRUE, verbose = FALSE, show_context = FALSE, max_context_chars = Inf, max_error_age_secs = 300, confirm_stale_errors = TRUE, ... )
prompt |
Optional user instruction to add above the collected context. |
model |
Optional model string, |
skills |
Skill paths, |
skill |
Optional skill name to force for the initial turn. |
context |
Optional additional context text, or an |
startup_dir |
R session startup directory for project-aware context. |
working_dir |
Working directory for sandboxed console tools. |
sandbox_mode |
Sandbox mode for the console agent. |
stream |
Whether to stream model output. |
verbose |
Whether to show debug console output. |
show_context |
If |
max_context_chars |
Maximum formatted context characters. Defaults to
|
max_error_age_secs |
Maximum age in seconds for errors/warnings to be
included. Defaults to 300 (5 minutes). Set to |
confirm_stale_errors |
If |
... |
Additional arguments passed to |
Invisibly returns the ChatSession from console_chat(), or a
preview list when show_context = TRUE.
Provides dynamic authorization hooks to pause Agent execution and request user permission for elevated risk operations.
Self-healing runtime for R code execution. Implements a "Hypothesis-Fix-Verify" loop that feeds error messages, stack traces, and context back to an LLM for automatic error correction.
Execute R code with automatic error recovery using LLM assistance. When code fails, the error is analyzed and a fix is attempted automatically.
auto_fix( expr, model = NULL, max_attempts = 3, context = NULL, verbose = TRUE, memory = NULL )auto_fix( expr, model = NULL, max_attempts = 3, context = NULL, verbose = TRUE, memory = NULL )
expr |
The R expression to execute. |
model |
The LLM model to use for error analysis (default: from options). |
max_attempts |
Maximum number of fix attempts (default: 3). |
context |
Optional additional context about the code's purpose. |
verbose |
Print progress messages (default: TRUE). |
memory |
Optional ProjectMemory object for learning from past fixes. |
The result of successful execution, or an error if all attempts fail.
## Not run: # Simple usage - auto-fix a data transformation result <- auto_fix({ df <- read.csv("data.csv") df %>% filter(value > 100) %>% summarize(mean = mean(value)) }) # With context for better error understanding result <- auto_fix( expr = { model <- lm(y ~ x, data = df) }, context = "Fitting a linear regression model to predict sales" ) ## End(Not run)## Not run: # Simple usage - auto-fix a data transformation result <- auto_fix({ df <- read.csv("data.csv") df %>% filter(value > 100) %>% summarize(mean = mean(value)) }) # With context for better error understanding result <- auto_fix( expr = { model <- lm(y ~ x, data = df) }, context = "Fitting a linear regression model to predict sales" ) ## End(Not run)
Utilities for caching tool execution results and other expensive operations.
Wrap a tool with caching capabilities using the memoise package.
cache_tool(tool, cache = NULL)cache_tool(tool, cache = NULL)
tool |
The Tool object to cache. |
cache |
An optional memoise cache configuration (e.g., cache_memory() or cache_filesystem()).
Defaults to |
A new Tool object that caches its execution.
Try accessor functions in order and return the first successful result. Useful for extension authors who need compatibility across optional dependency APIs.
call_object_accessor( obj, fun_names, default = NULL, package = NULL, args = list() )call_object_accessor( obj, fun_names, default = NULL, package = NULL, args = list() )
obj |
Object passed as the first argument to the accessor. |
fun_names |
Character vector of accessor function names to try. |
default |
Value returned when no accessor can be called successfully. |
package |
Optional package name to resolve accessors from first. |
args |
Optional named list of additional arguments passed to accessor. |
The accessor result or default.
Configure model routes for task capabilities such as vision inspection, image generation, or code review. These routes let a session keep one default chat model while specific capabilities use better-suited models.
R6 class representing a stateful chat session. Automatically manages conversation history, supports tool execution, and provides persistence.
new()
Initialize a new ChatSession.
ChatSession$new( model = NULL, system_prompt = NULL, tools = NULL, hooks = NULL, history = NULL, max_steps = 10, registry = NULL, memory = NULL, metadata = NULL, envir = NULL, agent = NULL )
modelA LanguageModelV1 object or model string ID (e.g., "openai:gpt-4o").
system_promptOptional system prompt for the conversation.
toolsOptional list of Tool objects for function calling.
hooksOptional HookHandler object for event hooks.
historyOptional initial message history (list of message objects).
max_stepsMaximum steps for tool execution loops. Default 10.
registryOptional ProviderRegistry for model resolution.
memoryOptional initial shared memory (list). For multi-agent state sharing.
metadataOptional session metadata (list). Used for channel/runtime state.
envirOptional shared R environment. For multi-agent data sharing.
agentOptional Agent object. If provided, the session inherits the agent's tools and system prompt.
send()
Send a message and get a response.
ChatSession$send(prompt, ...)
promptThe user message to send.
...Additional arguments passed to generate_text.
The GenerateResult object from the model.
send_stream()
Send a message with streaming output.
ChatSession$send_stream(prompt, callback, ...)
promptThe user message to send.
callbackFunction called for each chunk: callback(text, done).
...Additional arguments passed to stream_text.
The GenerateResult object invisibly (output is via callback).
continue_run()
Inject a manual continuation instruction into the current task.
ChatSession$continue_run( action = "continue", guidance = NULL, stream = TRUE, callback = NULL, ... )
actionOne of "continue", "give_up", "avoid_tool", "explain", or "manual".
guidanceOptional operator guidance to include in the continuation.
streamWhether to use streaming generation.
callbackStreaming callback when stream = TRUE.
...Additional arguments passed to send/send_stream.
The GenerateResult object, or an invisible waiting-user result for manual action.
append_message()
Append a message to the history.
ChatSession$append_message(role, content, reasoning = NULL)
roleMessage role: "user", "assistant", "system", or "tool".
contentMessage content.
reasoningOptional reasoning text to attach to the message.
get_history()
Get the conversation history.
ChatSession$get_history()
A list of message objects.
get_last_response()
Get the last response from the assistant.
ChatSession$get_last_response()
The content of the last assistant message, or NULL.
clear_history()
Clear the conversation history.
ChatSession$clear_history(keep_system = TRUE)
keep_systemIf TRUE, keeps the system prompt. Default TRUE.
switch_model()
Switch to a different model.
ChatSession$switch_model(model)
modelA LanguageModelV1 object or model string ID.
get_model_options()
Get model runtime options for this session.
ChatSession$get_model_options()
A list with context overrides and call options.
get_model_call_options()
Get generation options applied to every model call.
ChatSession$get_model_call_options()
A named list of call options.
set_model_options()
Set runtime options for this session's model.
ChatSession$set_model_options( context_window = NULL, max_output_tokens = NULL, max_tokens = NULL, thinking = NULL, thinking_budget = NULL, reasoning_effort = NULL, reset = FALSE )
context_windowOptional context-window override.
max_output_tokensOptional maximum output-token metadata override.
max_tokensOptional default generation token limit.
thinkingOptional default thinking-mode value.
thinking_budgetOptional default thinking budget.
reasoning_effortOptional default reasoning effort.
resetLogical. If TRUE, clears all model runtime options first.
Invisible self for chaining.
clear_model_options()
Clear model runtime options for this session.
ChatSession$clear_model_options(keys = NULL)
keysOptional option names to clear. If NULL, clears all.
Invisible self for chaining.
set_capability_model()
Set a model route for a session capability.
ChatSession$set_capability_model( capability, model, type = "auto", required_model_capabilities = NULL )
capabilityCapability route name, such as "vision.inspect".
modelModel ID string or model object. Passing NULL clears the route.
typeModel type: "auto", "language", "embedding", or "image".
required_model_capabilitiesOptional required model capability flags.
Invisible self for chaining.
get_capability_model()
Get the configured model for a session capability.
ChatSession$get_capability_model(capability, default = NULL)
capabilityCapability route name.
defaultValue returned when no route is configured.
A model ID string, model object, or default.
list_capability_models()
List session capability model routes.
ChatSession$list_capability_models()
A data frame of configured session routes.
clear_capability_model()
Clear one or all session capability model routes.
ChatSession$clear_capability_model(capability = NULL)
capabilityOptional route name. If NULL, clears all routes.
Invisible self for chaining.
get_model_id()
Get current model identifier.
ChatSession$get_model_id()
Model ID string.
get_model()
Get the resolved language model for this session.
ChatSession$get_model()
A LanguageModelV1 object.
get_tools()
Get tools configured on this session.
ChatSession$get_tools()
A list of Tool objects.
stats()
Get token usage statistics.
ChatSession$stats()
A list with token counts and message stats.
save()
Save session to a file.
ChatSession$save(path, format = NULL)
pathFile path (supports .rds or .json extension).
formatOptional format override: "rds" or "json". Auto-detected from path.
as_list()
Export session state as a list (for serialization).
ChatSession$as_list()
A list containing session state.
restore()
Restore session from a file.
ChatSession$restore(path, format = NULL)
pathFile path (supports .rds or .json extension).
formatOptional format override: "rds" or "json". Auto-detected from path.
restore_from_list()
Restore session state from a list.
ChatSession$restore_from_list(data)
dataA list exported by as_list().
print()
Print method for ChatSession.
ChatSession$print()
get_memory()
Get a value from shared memory.
ChatSession$get_memory(key, default = NULL)
keyThe key to retrieve.
defaultDefault value if key not found. Default NULL.
The stored value or default.
get_run_state()
Return the most recent structured run state.
ChatSession$get_run_state()
A run state list.
set_run_state()
Store the current structured run state.
ChatSession$set_run_state(run_state)
run_stateA run state list.
Invisible self.
set_memory()
Set a value in shared memory.
ChatSession$set_memory(key, value)
keyThe key to store.
valueThe value to store.
Invisible self for chaining.
list_memory()
List all keys in shared memory.
ChatSession$list_memory()
Character vector of memory keys.
get_metadata()
Get a value from session metadata.
ChatSession$get_metadata(key, default = NULL)
keyThe metadata key to retrieve.
defaultDefault value if key is not present.
The stored metadata value or default.
set_metadata()
Set a value in session metadata.
ChatSession$set_metadata(key, value)
keyThe metadata key to set.
valueThe value to store.
Invisible self for chaining.
merge_metadata()
Merge a named list into session metadata.
ChatSession$merge_metadata(values)
valuesNamed list of metadata values.
Invisible self for chaining.
list_metadata()
List metadata keys.
ChatSession$list_metadata()
Character vector of metadata keys.
get_context_state()
Get the adaptive context state for this session.
ChatSession$get_context_state()
A normalized context state list.
set_context_state()
Store adaptive context state for this session.
ChatSession$set_context_state(state)
stateContext state list.
Invisible self for chaining.
clear_context_state()
Clear adaptive context state back to defaults.
ChatSession$clear_context_state()
Invisible self for chaining.
get_context_management_mode()
Get the context management mode for this session.
ChatSession$get_context_management_mode()
One of "off", "basic", or "adaptive".
get_context_management_config()
Get the full adaptive context-management configuration.
ChatSession$get_context_management_config()
A normalized context-management configuration list.
set_context_management_mode()
Override the context management mode for this session.
ChatSession$set_context_management_mode(mode)
modeOne of "off", "basic", or "adaptive".
Invisible self for chaining.
set_context_management_config()
Apply adaptive context-management configuration to this session.
ChatSession$set_context_management_config(config = NULL, ...)
configOptional config list created by create_context_management_config().
...Optional overrides forwarded to set_context_management_config().
Invisible self for chaining.
get_context_metrics()
Estimate current context metrics for this session.
ChatSession$get_context_metrics(turn_system_prompt = NULL)
turn_system_promptOptional turn-specific system prompt to include in the estimate.
A list of context metrics, or NULL if no model metadata is available.
assemble_messages()
Build a budget-aware prompt payload from current session history.
ChatSession$assemble_messages(turn_system_prompt = NULL)
turn_system_promptOptional turn-specific system prompt.
A list with messages, system, metrics, and state.
refresh_context_state()
Refresh the adaptive context state from current history.
ChatSession$refresh_context_state( generation_result = NULL, turn_system_prompt = NULL )
generation_resultOptional GenerateResult used to update tool/artifact digests.
turn_system_promptOptional turn-specific system prompt for the snapshot.
The normalized context state list.
list_context_handles()
List compact context handles available to this session.
ChatSession$list_context_handles()
A list of context handle records.
create_context_query_tools()
Create context query tools bound to this session.
ChatSession$create_context_query_tools()
A list of Tool objects.
sub_session_query()
Run a bounded child session for a focused query.
ChatSession$sub_session_query(...)
...Arguments passed to sub_session_query().
A compact sub-session result list.
clear_memory()
Clear shared memory.
ChatSession$clear_memory(keys = NULL)
keysOptional specific keys to clear. If NULL, clears all.
Invisible self for chaining.
get_envir()
Get the shared R environment.
ChatSession$get_envir()
This environment is shared across all agents using this session. Agents can store and retrieve data frames, models, and other R objects.
An environment object.
eval_in_session()
Evaluate an expression in the session environment.
ChatSession$eval_in_session(expr)
exprAn expression to evaluate.
The result of the evaluation.
list_envir()
List objects in the session environment.
ChatSession$list_envir()
Character vector of object names.
checkpoint()
Save a memory snapshot to a file (checkpoint for Mission resume).
ChatSession$checkpoint(path = NULL)
pathFile path (.rds). If NULL, uses a temp file and returns the path.
Invisible file path.
restore_checkpoint()
Restore memory and history from a checkpoint file.
ChatSession$restore_checkpoint(path)
pathFile path to a checkpoint created by checkpoint().
Invisible self for chaining.
clone()
The objects of this class are cloneable with this method.
ChatSession$clone(deep = FALSE)
deepWhether to make a deep clone.
Tests connectivity to a specific LLM, provider, or URL. This is helpful for diagnosing network issues, DNS failures, or SSL problems.
check_api(model = NULL, url = NULL, registry = NULL)check_api(model = NULL, url = NULL, registry = NULL)
model |
Optional. A |
url |
Optional. A specific URL to test. |
registry |
Optional ProviderRegistry to use if |
A list containing diagnostic results (invisible).
if (interactive()) { # Test by passing a URL directly check_api(url = "https://api.openai.com/v1") # Test a model directly model <- create_openai()$language_model("gpt-4o") check_api(model) }if (interactive()) { # Test by passing a URL directly check_api(url = "https://api.openai.com/v1") # Test a model directly model <- create_openai()$language_model("gpt-4o") check_api(model) }
Analyze R code for unsafe function calls or operations before execution.
check_ast_safety(code_str)check_ast_safety(code_str)
code_str |
Character string containing R code. |
The parsed AST if safe. Throws an error if unsafe.
Check if code is compatible with the current SDK version and suggest migration steps if needed.
check_sdk_compatibility(code_version)check_sdk_compatibility(code_version)
code_version |
Version string the code was written for. |
A list with compatible (logical) and suggestions (character vector).
if (interactive()) { result <- check_sdk_compatibility("0.8.0") if (!result$compatible) { cat("Migration needed:\n") cat(paste(result$suggestions, collapse = "\n")) } }if (interactive()) { result <- check_sdk_compatibility("0.8.0") if (!result$compatible) { cat("Migration needed:\n") cat(paste(result$suggestions, collapse = "\n")) } }
Clear one or all configured capability model routes.
clear_capability_model(capability = NULL)clear_capability_model(capability = NULL)
capability |
Optional capability route name. If |
Invisibly returns the previous route list.
Clears the tracked error and warning context used by ask_ai(). This is
useful when you want to start a fresh debugging session without stale
error messages from previous operations.
clear_error_context()clear_error_context()
Invisibly returns TRUE.
## Not run: # Clear stale errors before starting a new debugging session clear_error_context() ask_ai() ## End(Not run)## Not run: # Clear stale errors before starting a new debugging session clear_error_context() ask_ai() ## End(Not run)
ask_ai()
Collect recent error details, traceback output, warnings, active script context, session information, and lightweight workspace object summaries.
collect_ai_context( script = NULL, error = NULL, traceback = NULL, warnings = NULL, include = c("error", "traceback", "warnings", "script", "session", "objects", "history"), max_context_chars = Inf, max_error_age_secs = 300, include_history = TRUE, max_history_lines = 10 )collect_ai_context( script = NULL, error = NULL, traceback = NULL, warnings = NULL, include = c("error", "traceback", "warnings", "script", "session", "objects", "history"), max_context_chars = Inf, max_error_age_secs = 300, include_history = TRUE, max_history_lines = 10 )
script |
Optional script text or path. If |
error |
Optional error message. Defaults to |
traceback |
Optional traceback text. Defaults to |
warnings |
Optional warning text or warning object. Defaults to
R's |
include |
Character vector of sections to include. |
max_context_chars |
Maximum formatted context characters. Defaults to
|
max_error_age_secs |
Maximum age in seconds for errors/warnings to be
included. Defaults to 300 (5 minutes). Set to |
include_history |
Whether to include recent command history. Defaults to
|
max_history_lines |
Maximum number of recent command history lines to include. Defaults to 10. |
A structured context list with class aisdk_ai_context.
Provides feature flags, compatibility shims, and migration utilities for controlled breaking changes in the agent SDK.
R6 class providing computer abstraction with atomic tools for file operations, bash execution, and R code execution.
working_dirCurrent working directory
sandbox_modeSandbox mode: "strict", "permissive", or "none"
execution_logLog of executed commands
new()
Initialize computer abstraction
Computer$new(working_dir = tempdir(), sandbox_mode = "permissive")
working_dirWorking directory. Defaults to tempdir().
sandbox_modeSandbox mode: "strict", "permissive", or "none"
bash()
Execute bash command
Computer$bash(command, timeout_ms = 30000, capture_output = TRUE)
commandBash command to execute
timeout_msTimeout in milliseconds (default: 30000)
capture_outputWhether to capture output (default: TRUE)
List with stdout, stderr, exit_code
read_file()
Read file contents
Computer$read_file(path, encoding = "UTF-8")
pathFile path (relative to working_dir or absolute)
encodingFile encoding (default: "UTF-8")
File contents as character string
write_file()
Write file contents
Computer$write_file(path, content, encoding = "UTF-8")
pathFile path (relative to working_dir or absolute)
contentContent to write
encodingFile encoding (default: "UTF-8")
Success status
edit_file()
Edit a file by replacing an exact text pattern.
Computer$edit_file(path, pattern, replacement, all = FALSE, encoding = "UTF-8")
pathFile path (relative to working_dir or absolute)
patternExact text to replace
replacementReplacement text
allWhether to replace all occurrences. Default FALSE.
encodingFile encoding (default: "UTF-8")
Success status
execute_r_code()
Execute R code in an isolated callr process
Computer$execute_r_code(code, timeout_ms = 30000, capture_output = TRUE)
codeR code to execute
timeout_msTimeout in milliseconds (default: 30000)
capture_outputWhether to capture output (default: TRUE)
List with result, output, error, and execution_mode.
execution_mode is always "sandbox_exec" for this computer-layer path,
which does not persist values into a live ChatSession$get_envir().
get_log()
Get execution log
Computer$get_log()
List of logged executions
clear_log()
Clear execution log Check bash command for sandbox violations Log execution Resolve path (relative to working_dir or absolute) Check write path for sandbox violations Check R code for sandbox violations
Computer$clear_log()
clone()
The objects of this class are cloneable with this method.
Computer$clone(deep = FALSE)
deepWhether to make a deep clone.
Helpers for reading project/global aisdk.yaml model configuration files.
Interactive terminal chat interface for ChatSession. Provides a REPL (Read-Eval-Print Loop) for conversing with LLMs. By default, enables an intelligent terminal agent that can execute commands, manage files, and run R code through natural language.
Creates a default agent for console_chat() that enables natural language interaction with the terminal. Users can ask the agent to run commands, execute R code, read/write files, and more through conversational language.
Launch an interactive chat session in the R console. Supports streaming output, slash commands, and colorful display using the cli package.
The console UI has three presentation modes:
clean: compact default output with a stable status bar
inspect: keeps the compact transcript but adds a per-turn tool timeline
and an overlay-backed inspector
debug: shows detailed tool logs and thinking output for troubleshooting
In agent mode, console_chat() can execute shell and R tools, summarize tool
progress inline, and open an inspector overlay for the latest turn or a
specific tool. The current implementation uses a shared frame builder for the
status bar, tool timeline, and overlay surfaces, while preserving an
append-only terminal fallback.
By default, the console operates in minimal agent mode with four tools:
bash, read_file, write_file, and edit_file. Set
profile = "legacy" to restore the previous broad all-in-one agent, or
agent = NULL for simple chat without tools.
console_chat( session = NULL, system_prompt = NULL, tools = NULL, hooks = NULL, stream = TRUE, verbose = FALSE, agent = "auto", skills = NULL, working_dir = tempdir(), sandbox_mode = "permissive", show_thinking = verbose, startup_dir = getwd(), initial_prompt = NULL, profile = c("minimal", "legacy"), extensions = "auto" )console_chat( session = NULL, system_prompt = NULL, tools = NULL, hooks = NULL, stream = TRUE, verbose = FALSE, agent = "auto", skills = NULL, working_dir = tempdir(), sandbox_mode = "permissive", show_thinking = verbose, startup_dir = getwd(), initial_prompt = NULL, profile = c("minimal", "legacy"), extensions = "auto" )
session |
A ChatSession object, a LanguageModelV1 object, or a model string ID to create a new session. |
system_prompt |
Optional system prompt (merged with agent prompt if agent is used). |
tools |
Optional list of additional Tool objects. |
hooks |
Optional HookHandler object. |
stream |
Whether to use streaming output. Default TRUE. |
verbose |
Logical. If |
agent |
Agent configuration. Options:
|
skills |
Optional skill paths, |
working_dir |
Working directory for sandboxed console tools. Defaults to |
sandbox_mode |
Sandbox mode for the console agent: "strict", "permissive" (default), or "none". |
show_thinking |
Logical. Whether to show model thinking blocks when the
provider exposes them. Defaults to |
startup_dir |
R session startup directory used for project-aware context. Defaults to |
initial_prompt |
Optional user prompt to send automatically before entering the interactive REPL. |
profile |
Console profile. |
extensions |
Extension loading mode. Defaults to |
The ChatSession object (invisibly) when chat ends.
if (interactive()) { # Start with default agent (intelligent terminal mode) console_chat("openai:gpt-4o") # Start in debug mode with full tool logs console_chat("openai:gpt-4o", verbose = TRUE) # Simple chat mode without tools console_chat("openai:gpt-4o", agent = NULL) # Start with an existing session chat <- create_chat_session("anthropic:claude-3-5-sonnet-latest") console_chat(chat) # Start with a custom agent agent <- create_agent("MathAgent", "Does math", system_prompt = "You are a math wizard.") console_chat("openai:gpt-4o", agent = agent) # Available commands in the chat: # /quit or /exit - End the chat # /save [path] - Save session to file # /load [path] - Load session from file # /model - Open the provider/model chooser # /model [id] - Switch to a different model # /model current - Show the active model # /history - Show conversation history # /stats - Show token usage statistics # /clear - Clear conversation history # /stream [on|off] - Toggle streaming mode # /inspect [on|off] - Toggle inspect mode # /inspect turn - Open overlay for the latest turn # /inspect tool <index> - Open overlay for a tool in the latest turn # /inspect next - Move inspector overlay to the next tool # /inspect prev - Move inspector overlay to the previous tool # /inspect close - Close the active inspect overlay # /debug [on|off] - Toggle detailed tool/thinking output # /local [on|off]- Toggle local execution mode (Global Environment) # /help - Show available commands # /agent [on|off] - Toggle agent mode }if (interactive()) { # Start with default agent (intelligent terminal mode) console_chat("openai:gpt-4o") # Start in debug mode with full tool logs console_chat("openai:gpt-4o", verbose = TRUE) # Simple chat mode without tools console_chat("openai:gpt-4o", agent = NULL) # Start with an existing session chat <- create_chat_session("anthropic:claude-3-5-sonnet-latest") console_chat(chat) # Start with a custom agent agent <- create_agent("MathAgent", "Does math", system_prompt = "You are a math wizard.") console_chat("openai:gpt-4o", agent = agent) # Available commands in the chat: # /quit or /exit - End the chat # /save [path] - Save session to file # /load [path] - Load session from file # /model - Open the provider/model chooser # /model [id] - Switch to a different model # /model current - Show the active model # /history - Show conversation history # /stats - Show token usage statistics # /clear - Clear conversation history # /stream [on|off] - Toggle streaming mode # /inspect [on|off] - Toggle inspect mode # /inspect turn - Open overlay for the latest turn # /inspect tool <index> - Open overlay for a tool in the latest turn # /inspect next - Move inspector overlay to the next tool # /inspect prev - Move inspector overlay to the previous tool # /inspect close - Close the active inspect overlay # /debug [on|off] - Toggle detailed tool/thinking output # /local [on|off]- Toggle local execution mode (Global Environment) # /help - Show available commands # /agent [on|off] - Toggle agent mode }
Ask a yes/no question with numbered choices. Returns TRUE for yes,
FALSE for no, or NULL if cancelled.
console_confirm(question)console_confirm(question)
question |
The question to display. |
TRUE if user selects Yes, FALSE for No, NULL
if cancelled.
if (interactive()) { if (isTRUE(console_confirm("Overwrite existing file?"))) { message("Overwriting...") } }if (interactive()) { if (isTRUE(console_confirm("Overwrite existing file?"))) { message("Overwriting...") } }
Prompt the user for free-text input with optional default value.
console_input(prompt, default = NULL)console_input(prompt, default = NULL)
prompt |
The prompt message to display. |
default |
Optional default value shown in brackets. Returned if user presses Enter without typing. |
The user's input string, default if empty input and default
is set, or NULL if empty input with no default.
if (interactive()) { name <- console_input("Project name", default = "my-project") api_key <- console_input("API key") }if (interactive()) { name <- console_input("Project name", default = "my-project") api_key <- console_input("API key") }
Helpers for constructing and validating provider-neutral multimodal content blocks that can later be translated into provider-specific payloads.
Creates an image content object for a multimodal message. Automatically handles URLs, data URIs, raw bytes, and local files. This is kept for backward compatibility and returns the provider-neutral image block used by multimodal providers.
content_image(image_path, media_type = "auto", detail = "auto")content_image(image_path, media_type = "auto", detail = "auto")
image_path |
Path to a local file or a URL. |
media_type |
MIME type of the image (e.g., "image/jpeg", "image/png"). If NULL, attempts to guess from the file extension. |
detail |
Image detail suitable for some models (e.g., "auto", "low", "high"). |
A provider-neutral image block.
Creates a text content object for a multimodal message. This is kept for backward compatibility and returns the provider-neutral text block used by multimodal providers.
content_text(text)content_text(text)
text |
The text string. |
A list representing the text content.
Internal helpers for estimating prompt occupancy, classifying context budget regimes, storing compact session-side context state, and assembling a budget-aware prompt view from raw session history.
Internal helpers for collecting execution monitoring, system/device info, and R runtime state signals to populate context state fields.
Resolve a compact context handle to either its summary metadata or a bounded detailed representation.
context_get(session, handle_id, detail = c("summary", "full"))context_get(session, handle_id, detail = c("summary", "full"))
session |
A |
handle_id |
Context handle ID. |
detail |
One of |
A list with handle metadata and optional bounded content.
Public helpers for configuring adaptive context management on ChatSession
objects without reaching into internal metadata keys.
Search compact handles for live objects, memory entries, transcript segments, retrieval hits, and artifacts.
context_search(session, query, kinds = NULL, limit = 5L)context_search(session, query, kinds = NULL, limit = 5L)
session |
A |
query |
Search query. |
kinds |
Optional character vector of handle kinds to include. |
limit |
Maximum number of handles to return. |
A list of matching context handles.
User-facing high-level API functions for interacting with AI models.
Functions for generating structured objects from LLMs using schemas.
Generate a structured R object (list) from a language model based on a schema. The model is instructed to output valid JSON matching the schema, which is then parsed and returned as an R list.
generate_object( model = NULL, prompt, schema, schema_name = "result", system = NULL, temperature = 0.3, max_tokens = NULL, mode = c("json", "tool"), registry = NULL, ... )generate_object( model = NULL, prompt, schema, schema_name = "result", system = NULL, temperature = 0.3, max_tokens = NULL, mode = c("json", "tool"), registry = NULL, ... )
model |
Either a LanguageModelV1 object, or a string ID like "openai:gpt-4o". |
prompt |
A character string prompt describing what to generate. |
schema |
A schema object created by |
schema_name |
Optional human-readable name for the schema (default: "result"). |
system |
Optional system prompt. |
temperature |
Sampling temperature (0-2). Default 0.3 (lower for structured output). |
max_tokens |
Maximum tokens to generate. |
mode |
Output mode: "json" (prompt-based) or "tool" (function calling). Currently, only "json" mode is implemented. |
registry |
Optional ProviderRegistry to use (defaults to global registry). |
... |
Additional arguments passed to the model. |
A GenerateObjectResult with:
object: The parsed R object (list)
usage: Token usage information
raw_text: The raw text output from the LLM
finish_reason: The reason the generation stopped
if (interactive()) { # Define a schema for the expected output schema <- z_object( title = z_string(description = "Title of the article"), keywords = z_array(z_string()), sentiment = z_enum(c("positive", "negative", "neutral")) ) # Generate structured object result <- generate_object( model = "openai:gpt-4o", prompt = "Analyze this article: 'R programming is great for data science!'", schema = schema ) print(result$object$title) print(result$object$sentiment) }if (interactive()) { # Define a schema for the expected output schema <- z_object( title = z_string(description = "Title of the article"), keywords = z_array(z_string()), sentiment = z_enum(c("positive", "negative", "neutral")) ) # Generate structured object result <- generate_object( model = "openai:gpt-4o", prompt = "Analyze this article: 'R programming is great for data science!'", schema = schema ) print(result$object$title) print(result$object$sentiment) }
Factory function to create a new Agent object.
create_agent( name, description, system_prompt = NULL, tools = NULL, skills = NULL, model = NULL, capability_models = NULL )create_agent( name, description, system_prompt = NULL, tools = NULL, skills = NULL, model = NULL, capability_models = NULL )
name |
Unique name for this agent. |
description |
A clear description of what this agent does. |
system_prompt |
Optional system prompt defining the agent's persona. |
tools |
Optional list of Tool objects the agent can use. |
skills |
Optional character vector of skill paths or "auto". |
model |
Optional default model ID for this agent. |
capability_models |
Optional named list of capability-specific model routes. |
An Agent object.
if (interactive()) { # Create a simple math agent math_agent <- create_agent( name = "MathAgent", description = "Performs arithmetic calculations", system_prompt = "You are a math assistant. Return only numerical results." ) # Run the agent result <- math_agent$run("Calculate 2 + 2", model = "openai:gpt-4o") # Create an agent with skills stock_agent <- create_agent( name = "StockAnalyst", description = "Stock analysis agent", skills = "auto" ) }if (interactive()) { # Create a simple math agent math_agent <- create_agent( name = "MathAgent", description = "Performs arithmetic calculations", system_prompt = "You are a math assistant. Return only numerical results." ) # Run the agent result <- math_agent$run("Calculate 2 + 2", model = "openai:gpt-4o") # Create an agent with skills stock_agent <- create_agent( name = "StockAnalyst", description = "Stock analysis agent", skills = "auto" ) }
Factory function to create a new AgentRegistry.
create_agent_registry(agents = NULL)create_agent_registry(agents = NULL)
agents |
Optional list of Agent objects to register immediately. |
An AgentRegistry object.
if (interactive()) { # Create registry with agents cleaner <- create_agent("Cleaner", "Cleans data") plotter <- create_agent("Plotter", "Creates visualizations") registry <- create_agent_registry(list(cleaner, plotter)) print(registry$list_agents()) # "Cleaner", "Plotter" }if (interactive()) { # Create registry with agents cleaner <- create_agent("Cleaner", "Cleans data") plotter <- create_agent("Plotter", "Creates visualizations") registry <- create_agent_registry(list(cleaner, plotter)) print(registry$list_agents()) # "Cleaner", "Plotter" }
Factory function to create an Anthropic provider.
create_anthropic( api_key = NULL, base_url = NULL, api_version = NULL, headers = NULL, name = NULL, timeout_seconds = NULL, total_timeout_seconds = NULL, first_byte_timeout_seconds = NULL, connect_timeout_seconds = NULL, idle_timeout_seconds = NULL )create_anthropic( api_key = NULL, base_url = NULL, api_version = NULL, headers = NULL, name = NULL, timeout_seconds = NULL, total_timeout_seconds = NULL, first_byte_timeout_seconds = NULL, connect_timeout_seconds = NULL, idle_timeout_seconds = NULL )
api_key |
Anthropic API key. Defaults to ANTHROPIC_API_KEY env var. |
base_url |
Base URL for API calls. Defaults to https://api.anthropic.com/v1. |
api_version |
Anthropic API version header. Defaults to "2023-06-01". |
headers |
Optional additional headers. |
name |
Optional provider name override. |
timeout_seconds |
Legacy alias for |
total_timeout_seconds |
Optional total request timeout in seconds for API calls. |
first_byte_timeout_seconds |
Optional time-to-first-byte timeout in seconds for API calls. |
connect_timeout_seconds |
Optional connection-establishment timeout in seconds for API calls. |
idle_timeout_seconds |
Optional stall timeout in seconds for API calls. |
An AnthropicProvider object.
claude-opus-4-7: Anthropic's most capable model for complex reasoning and coding. (Reasoning, Vision, Tools, Structured) | ctx: 1000k
claude-opus-4-6: Previous generation of Claude Opus with 1M context. (Reasoning, Vision, Tools, Structured) | ctx: 1000k
claude-opus-4-5: Claude Opus 4.5 with 200K context. (Reasoning, Vision, Tools, Structured) | ctx: 200k
claude-sonnet-4-6: Balanced model for coding and agentic workflows with 1M context. (Reasoning, Vision, Tools, Structured) | ctx: 1000k
claude-sonnet-4-5: Claude Sonnet 4.5 with 200K context. (Reasoning, Vision, Tools, Structured) | ctx: 200k
claude-sonnet-4: Original Claude Sonnet 4 with 200K context. (Reasoning, Vision, Tools, Structured) | ctx: 200k
claude-haiku-4-5: Fast and cost-effective model for simple tasks and chatbots. (Vision, Tools, Structured) | ctx: 200k
if (interactive()) { anthropic <- create_anthropic(api_key = "sk-ant-...") model <- anthropic$language_model("claude-sonnet-4-20250514") }if (interactive()) { anthropic <- create_anthropic(api_key = "sk-ant-...") model <- anthropic$language_model("claude-sonnet-4-20250514") }
Creates a tool that allows an agent to pause execution and ask the user for help, clarification, or guidance. This is reserved for real user decisions such as destructive actions, credentials, cost/permission gates, ambiguous requirements, or information only the user can provide.
create_ask_user_tool()create_ask_user_tool()
The ask_user tool lets agents pause for genuine user decisions instead of guessing through risks or missing requirements.
The tool accepts:
question: The main question or explanation to show the user (required)
context: Optional context about why the agent is asking (what was tried, what failed)
options: Optional list of suggested responses for the user to choose from
When options are provided, the user can either select a numbered option or type their own custom response.
A Tool object that can be used with agents
## Not run: # Create the tool ask_tool <- create_ask_user_tool() # Use in an agent agent <- Agent$new( name = "helper", tools = list(ask_tool, other_tools...) ) # The agent can then use it when user input is required: # ask_user( # question = "This will overwrite report.html. Should I continue?", # context = "The target file already exists in the project directory.", # options = ["Overwrite it", "Choose another path", "Cancel"] # ) ## End(Not run)## Not run: # Create the tool ask_tool <- create_ask_user_tool() # Use in an agent agent <- Agent$new( name = "helper", tools = list(ask_tool, other_tools...) ) # The agent can then use it when user input is required: # ask_user( # question = "This will overwrite report.html. Should I continue?", # context = "The target file already exists in the project directory.", # options = ["Overwrite it", "Choose another path", "Cancel"] # ) ## End(Not run)
Returns a CaptureRenderer that records agent-output events instead of
displaying them. Call its events() method to retrieve the recorded events.
create_capture_renderer()create_capture_renderer()
Factory function to create a new ChatSession object.
create_chat_session( model = NULL, system_prompt = NULL, tools = NULL, hooks = NULL, max_steps = 10, metadata = NULL, agent = NULL )create_chat_session( model = NULL, system_prompt = NULL, tools = NULL, hooks = NULL, max_steps = 10, metadata = NULL, agent = NULL )
model |
A LanguageModelV1 object or model string ID. |
system_prompt |
Optional system prompt. |
tools |
Optional list of Tool objects. |
hooks |
Optional HookHandler object. |
max_steps |
Maximum tool execution steps. Default 10. |
metadata |
Optional session metadata (list). |
agent |
Optional Agent object to initialize from. |
A ChatSession object.
if (interactive()) { # Create a chat session chat <- create_chat_session( model = "openai:gpt-4o", system_prompt = "You are a helpful R programming assistant." ) # Create from an existing agent agent <- create_agent("MathAgent", "Does math", system_prompt = "You are a math wizard.") chat <- create_chat_session(model = "openai:gpt-4o", agent = agent) # Send messages response <- chat$send("How do I read a CSV file?") print(response$text) # Continue the conversation (history is maintained) response <- chat$send("What about Excel files?") # Check stats print(chat$stats()) # Save session chat$save("my_session.rds") }if (interactive()) { # Create a chat session chat <- create_chat_session( model = "openai:gpt-4o", system_prompt = "You are a helpful R programming assistant." ) # Create from an existing agent agent <- create_agent("MathAgent", "Does math", system_prompt = "You are a math wizard.") chat <- create_chat_session(model = "openai:gpt-4o", agent = agent) # Send messages response <- chat$send("How do I read a CSV file?") print(response$text) # Continue the conversation (history is maintained) response <- chat$send("What about Excel files?") # Check stats print(chat$stats()) # Save session chat$save("my_session.rds") }
Creates an agent specialized in writing and executing R code. The agent can execute R code in the session environment, making results available to other agents. Enhanced version with better safety controls and debugging support.
create_coder_agent( name = "CoderAgent", safe_mode = TRUE, timeout_ms = 30000, max_output_lines = 200 )create_coder_agent( name = "CoderAgent", safe_mode = TRUE, timeout_ms = 30000, max_output_lines = 200 )
name |
Agent name. Default "CoderAgent". |
safe_mode |
If TRUE (default), restricts file system and network access. |
timeout_ms |
Code execution timeout in milliseconds. Default 30000. |
max_output_lines |
Maximum output lines to return. Default 50. |
An Agent object configured for R code execution.
if (interactive()) { coder <- create_coder_agent() session <- create_shared_session(model = "openai:gpt-4o") result <- coder$run( "Create a data frame with 3 rows and calculate the mean", session = session, model = "openai:gpt-4o" ) }if (interactive()) { coder <- create_coder_agent() session <- create_shared_session(model = "openai:gpt-4o") result <- coder$run( "Create a data frame with 3 rows and calculate the mean", session = session, model = "openai:gpt-4o" ) }
Create atomic tools for computer abstraction layer. These tools provide a small set of primitives that agents can use to perform complex actions.
create_computer_tools( computer = NULL, working_dir = tempdir(), sandbox_mode = "permissive" )create_computer_tools( computer = NULL, working_dir = tempdir(), sandbox_mode = "permissive" )
computer |
Computer instance (default: create new) |
working_dir |
Working directory. Defaults to |
sandbox_mode |
Sandbox mode: "strict", "permissive", or "none" |
List of Tool objects
Create the default intelligent terminal agent for console_chat(). This agent can execute commands, manage files, and run R code through natural language interaction.
create_console_agent( working_dir = tempdir(), sandbox_mode = "permissive", additional_tools = NULL, language = "auto", startup_dir = working_dir, skills = "auto", profile = c("minimal", "legacy"), extensions = "auto" )create_console_agent( working_dir = tempdir(), sandbox_mode = "permissive", additional_tools = NULL, language = "auto", startup_dir = working_dir, skills = "auto", profile = c("minimal", "legacy"), extensions = "auto" )
working_dir |
Working directory for sandboxed tool execution. Defaults to |
sandbox_mode |
Sandbox mode: "strict", "permissive", or "none" (default: "permissive"). |
additional_tools |
Optional list of additional Tool objects to include. |
language |
Language for responses: "auto", "en", or "zh" (default: "auto"). |
startup_dir |
R session startup directory used for project-aware context. Defaults to |
skills |
Optional skill paths, |
profile |
Console profile. |
extensions |
Extension loading mode. Defaults to |
An Agent object configured for console interaction.
if (interactive()) { # Create default console agent agent <- create_console_agent() # Create with custom working directory agent <- create_console_agent(working_dir = "~/projects/myapp") # Use with console_chat console_chat("openai:gpt-4o", agent = agent) }if (interactive()) { # Create default console agent agent <- create_console_agent() # Create with custom working directory agent <- create_console_agent(working_dir = "~/projects/myapp") # Use with console_chat console_chat("openai:gpt-4o", agent = agent) }
Create a set of tools optimized for console/terminal interaction.
The default "minimal" profile exposes only bash, read_file,
write_file, and edit_file. Use profile = "legacy" for the prior
broad tool surface including R, image, Feishu, skill, and inspection tools.
create_console_tools( working_dir = tempdir(), sandbox_mode = "permissive", startup_dir = working_dir, profile = c("minimal", "legacy"), extensions = "auto" )create_console_tools( working_dir = tempdir(), sandbox_mode = "permissive", startup_dir = working_dir, profile = c("minimal", "legacy"), extensions = "auto" )
working_dir |
Working directory for sandboxed tool execution. Defaults to |
sandbox_mode |
Sandbox mode: "strict", "permissive", or "none" (default: "permissive"). |
startup_dir |
R session startup directory used for project-aware context. Defaults to |
profile |
Console profile. |
extensions |
Extension loading mode. Defaults to |
A list of Tool objects.
if (interactive()) { tools <- create_console_tools() # Use with an agent or session session <- create_chat_session(model = "openai:gpt-4o", tools = tools) }if (interactive()) { tools <- create_console_tools() # Use with an agent or session session <- create_chat_session(model = "openai:gpt-4o", tools = tools) }
Build a normalized context-management configuration list.
create_context_management_config( mode = NULL, llm_synthesis = FALSE, synthesis_model = NULL, llm_synthesis_policy = NULL, context_window_override = NULL, max_output_tokens_override = NULL, project_memory_root = NULL, retrieval_providers = NULL, retrieval_provider_order = NULL, retrieval_provider_limits = NULL, retrieval_min_hits = NULL, retrieval_scoring_policy = NULL, retrieval_reranking = FALSE, retrieval_reranking_model = NULL, retrieval_reranking_policy = NULL )create_context_management_config( mode = NULL, llm_synthesis = FALSE, synthesis_model = NULL, llm_synthesis_policy = NULL, context_window_override = NULL, max_output_tokens_override = NULL, project_memory_root = NULL, retrieval_providers = NULL, retrieval_provider_order = NULL, retrieval_provider_limits = NULL, retrieval_min_hits = NULL, retrieval_scoring_policy = NULL, retrieval_reranking = FALSE, retrieval_reranking_model = NULL, retrieval_reranking_policy = NULL )
mode |
One of |
llm_synthesis |
Logical; whether to enable optional LLM enrichment for working-memory synthesis. |
synthesis_model |
Optional model reference used for LLM synthesis. |
llm_synthesis_policy |
Optional named list controlling LLM synthesis
behavior. Supported fields are |
context_window_override |
Optional numeric context-window override. |
max_output_tokens_override |
Optional numeric max-output override. |
project_memory_root |
Optional project root used for |
retrieval_providers |
Optional retrieval-provider selection. Accepts either a character vector of enabled providers or a named logical/list map. |
retrieval_provider_order |
Optional character vector controlling render and ranking priority across retrieval providers. |
retrieval_provider_limits |
Optional named list of per-provider result limits. |
retrieval_min_hits |
Optional named list of per-provider matching thresholds. |
retrieval_scoring_policy |
Optional named list controlling cross-provider
retrieval scoring. Supported fields are |
retrieval_reranking |
Logical; whether to enable optional learned reranking on top of deterministic retrieval scoring. |
retrieval_reranking_model |
Optional model reference used for reranking. |
retrieval_reranking_policy |
Optional named list controlling reranking.
Supported fields are |
A normalized configuration list.
Create ordinary Tool objects for searching handles, resolving handles,
peeking live R objects, and launching bounded child sessions.
create_context_query_tools(session = NULL)create_context_query_tools(session = NULL)
session |
Optional |
A list of Tool objects.
Creates a dynamic wrapper around existing model classes (OpenAI, Anthropic)
based on user-provided configuration. The returned provider can be registered
in the global ProviderRegistry.
create_custom_provider( provider_name, base_url, api_key = NULL, api_format = c("chat_completions", "responses", "anthropic_messages"), use_max_completion_tokens = FALSE, disable_stream_options = TRUE, supports_native_tools = FALSE )create_custom_provider( provider_name, base_url, api_key = NULL, api_format = c("chat_completions", "responses", "anthropic_messages"), use_max_completion_tokens = FALSE, disable_stream_options = TRUE, supports_native_tools = FALSE )
provider_name |
The identifier name for this custom provider (e.g. "my_custom_openai_proxy"). |
base_url |
The base URL for the API endpoint. |
api_key |
The API key for authentication. If NULL, defaults to checking environmental variables. |
api_format |
The underlying API format to use. Supports "chat_completions" (OpenAI default), "responses" (OpenAI Responses API), and "anthropic_messages" (Anthropic Messages API). |
use_max_completion_tokens |
A boolean flag. If TRUE, injects the |
disable_stream_options |
A boolean flag. If TRUE, omit OpenAI-style
|
supports_native_tools |
A boolean flag. If FALSE, do not send native
OpenAI/Anthropic tool definitions or tool-result message formats. The SDK
will fall back to text-embedded |
A custom provider object with a language_model(model_id) method.
Creates an agent specialized in data manipulation using dplyr and tidyr. The agent can filter, transform, summarize, and reshape data frames in the session environment.
create_data_agent(name = "DataAgent", safe_mode = TRUE)create_data_agent(name = "DataAgent", safe_mode = TRUE)
name |
Agent name. Default "DataAgent". |
safe_mode |
If TRUE (default), restricts operations to data manipulation only. |
An Agent object configured for data manipulation.
if (interactive()) { data_agent <- create_data_agent() session <- create_shared_session(model = "openai:gpt-4o") session$set_var("sales", data.frame( product = c("A", "B", "C"), revenue = c(100, 200, 150) )) result <- data_agent$run( "Calculate total revenue and find the top product", session = session, model = "openai:gpt-4o" ) }if (interactive()) { data_agent <- create_data_agent() session <- create_shared_session(model = "openai:gpt-4o") session$set_var("sales", data.frame( product = c("A", "B", "C"), revenue = c(100, 200, 150) )) result <- data_agent$run( "Calculate total revenue and find the top product", session = session, model = "openai:gpt-4o" ) }
Build the package default semantic adapter registry used for semantic object inspection. The default registry includes built-in generic adapters and can optionally apply extension registrars.
create_default_semantic_adapter_registry( include_workflow_hints = TRUE, extension_registrars = NULL )create_default_semantic_adapter_registry( include_workflow_hints = TRUE, extension_registrars = NULL )
include_workflow_hints |
Logical; whether extension registrars should register workflow hints. |
extension_registrars |
Optional list of registrar functions. Each
registrar is called with |
This function is safe for extension packages that want the standard aisdk
registry baseline before registering additional adapters.
A SemanticAdapterRegistry object.
Generate embeddings for text using an embedding model.
create_embeddings(model, value, registry = NULL)create_embeddings(model, value, registry = NULL)
model |
Either an EmbeddingModelV1 object, or a string ID like "openai:text-embedding-3-small". |
value |
A character string or vector to embed. |
registry |
Optional ProviderRegistry to use. |
A list with embeddings and usage information.
if (interactive()) { model <- create_openai()$embedding_model("text-embedding-3-small") result <- create_embeddings(model, "Hello, world!") print(length(result$embeddings[[1]])) }if (interactive()) { model <- create_openai()$embedding_model("text-embedding-3-small") result <- create_embeddings(model, "Hello, world!") print(length(result$embeddings[[1]])) }
Creates an agent specialized in R environment and package management. The agent can check, install, and manage R packages with safety controls.
create_env_agent( name = "EnvAgent", allow_install = FALSE, allowed_repos = "https://cloud.r-project.org" )create_env_agent( name = "EnvAgent", allow_install = FALSE, allowed_repos = "https://cloud.r-project.org" )
name |
Agent name. Default "EnvAgent". |
allow_install |
Allow package installation. Default FALSE. |
allowed_repos |
CRAN mirror URLs for installation. |
An Agent object configured for environment management.
if (interactive()) { env_agent <- create_env_agent(allow_install = TRUE) result <- env_agent$run( "Check if tidyverse is installed and load it", session = session, model = "openai:gpt-4o" ) }if (interactive()) { env_agent <- create_env_agent(allow_install = TRUE) result <- env_agent$run( "Check if tidyverse is installed and load it", session = session, model = "openai:gpt-4o" ) }
Creates an agent specialized in file system operations using fs and readr. The agent can read, write, and manage files with safety guardrails.
create_file_agent( name = "FileAgent", allowed_dirs = ".", allowed_extensions = c("csv", "tsv", "txt", "json", "rds", "rda", "xlsx", "xls") )create_file_agent( name = "FileAgent", allowed_dirs = ".", allowed_extensions = c("csv", "tsv", "txt", "json", "rds", "rda", "xlsx", "xls") )
name |
Agent name. Default "FileAgent". |
allowed_dirs |
Character vector of allowed directories. Default current dir. |
allowed_extensions |
Character vector of allowed file extensions. |
An Agent object configured for file operations.
if (interactive()) { file_agent <- create_file_agent( allowed_dirs = c("./data", "./output"), allowed_extensions = c("csv", "json", "txt", "rds") ) result <- file_agent$run( "Read the sales.csv file and store it as 'sales_data'", session = session, model = "openai:gpt-4o" ) }if (interactive()) { file_agent <- create_file_agent( allowed_dirs = c("./data", "./output"), allowed_extensions = c("csv", "json", "txt", "rds") ) result <- file_agent$run( "Read the sales.csv file and store it as 'sales_data'", session = session, model = "openai:gpt-4o" ) }
Factory function to create a Gemini provider.
create_gemini( api_key = NULL, base_url = NULL, headers = NULL, name = NULL, timeout_seconds = NULL, total_timeout_seconds = NULL, first_byte_timeout_seconds = NULL, connect_timeout_seconds = NULL, idle_timeout_seconds = NULL )create_gemini( api_key = NULL, base_url = NULL, headers = NULL, name = NULL, timeout_seconds = NULL, total_timeout_seconds = NULL, first_byte_timeout_seconds = NULL, connect_timeout_seconds = NULL, idle_timeout_seconds = NULL )
api_key |
Gemini API key. Defaults to GEMINI_API_KEY env var. |
base_url |
Base URL for API calls. Defaults to https://generativelanguage.googleapis.com/v1beta/models. |
headers |
Optional additional headers. |
name |
Optional provider name override. |
timeout_seconds |
Legacy alias for |
total_timeout_seconds |
Optional total request timeout in seconds for API calls. |
first_byte_timeout_seconds |
Optional time-to-first-byte timeout in seconds for API calls. |
connect_timeout_seconds |
Optional connection-establishment timeout in seconds for API calls. |
idle_timeout_seconds |
Optional stall timeout in seconds for API calls. |
A GeminiProvider object.
gemini-3-pro-preview: Preview Gemini 3 Pro model for advanced reasoning, coding, multimodal understanding, and agentic workflows. (Reasoning, Vision, Tools, Audio, Structured, Search) | ctx: 1049k
gemini-3-pro-preview-customtools: Gemini 3 Pro Preview endpoint tuned for agentic workflows that combine bash-like and custom tools. (Reasoning, Vision, Tools, Audio, Structured, Search) | ctx: 1049k
gemini-3-flash-preview: Preview Gemini 3 Flash model for frontier-class performance at lower latency and cost. (Reasoning, Vision, Tools, Audio, Structured, Search) | ctx: 1049k
gemini-2.5-pro: Stable Gemini 2.5 Pro model for complex reasoning, coding, STEM, and long-context analysis. (Reasoning, Vision, Tools, Audio, Structured, Search) | ctx: 1049k
gemini-2.5-flash: Stable Gemini 2.5 Flash model for price-performance, low-latency, high-volume, and agentic tasks. (Reasoning, Vision, Tools, Audio, Structured, Search) | ctx: 1049k
gemini-2.5-flash-lite: Stable Gemini 2.5 Flash-Lite model for cost-efficient high-throughput multimodal tasks. (Reasoning, Vision, Tools, Audio, Structured, Search) | ctx: 1049k
gemini-2.0-flash: Deprecated Gemini 2.0 Flash model with 1M context; migrate to Gemini 3 Flash Preview or a newer model. (Vision, Tools, Audio, Structured, Search) | ctx: 1049k
gemini-2.0-flash-lite: Deprecated Gemini 2.0 Flash-Lite model; migrate to Gemini 2.5 Flash-Lite or a newer model. (Vision, Tools, Audio, Structured) | ctx: 1049k
gemini-3-pro-image-preview: Preview Gemini 3 Pro image generation and editing model for professional-grade visuals and accurate text rendering. (Reasoning, Vision, Image-Out, Image-Edit, Structured, Search) | ctx: 66k
gemini-2.5-flash-image: Stable Gemini 2.5 Flash image generation and conversational editing model for high-volume creative workflows. (Vision, Image-Out, Image-Edit, Structured) | ctx: 66k
if (interactive()) { gemini <- create_gemini(api_key = "AIza...") model <- gemini$language_model("gemini-2.5-flash") }if (interactive()) { gemini <- create_gemini(api_key = "AIza...") model <- gemini$language_model("gemini-2.5-flash") }
Helper to create a HookHandler from a list of functions.
create_hooks(...)create_hooks(...)
... |
Named arguments matching supported hook names. |
A HookHandler object.
Returns a Renderer that discards every event. Use it for headless or library contexts where agent output should not be displayed.
create_null_renderer()create_null_renderer()
A Renderer.
Factory function to create an OpenAI provider.
create_openai( api_key = NULL, base_url = NULL, organization = NULL, project = NULL, headers = NULL, name = NULL, timeout_seconds = NULL, total_timeout_seconds = NULL, first_byte_timeout_seconds = NULL, connect_timeout_seconds = NULL, idle_timeout_seconds = NULL, disable_stream_options = FALSE, api_format = c("auto", "chat", "responses") )create_openai( api_key = NULL, base_url = NULL, organization = NULL, project = NULL, headers = NULL, name = NULL, timeout_seconds = NULL, total_timeout_seconds = NULL, first_byte_timeout_seconds = NULL, connect_timeout_seconds = NULL, idle_timeout_seconds = NULL, disable_stream_options = FALSE, api_format = c("auto", "chat", "responses") )
api_key |
OpenAI API key. Defaults to OPENAI_API_KEY env var. |
base_url |
Base URL for API calls. Defaults to https://api.openai.com/v1. |
organization |
Optional OpenAI organization ID. |
project |
Optional OpenAI project ID. |
headers |
Optional additional headers. |
name |
Optional provider name override (for compatible APIs). |
timeout_seconds |
Legacy alias for |
total_timeout_seconds |
Optional total request timeout in seconds for API calls. |
first_byte_timeout_seconds |
Optional time-to-first-byte timeout in seconds for API calls. |
connect_timeout_seconds |
Optional connection-establishment timeout in seconds for API calls. |
idle_timeout_seconds |
Optional stall timeout in seconds for API calls. |
disable_stream_options |
Disable stream_options parameter (for providers like Volcengine that don't support it). |
api_format |
Default API surface for |
An OpenAIProvider object.
gpt-5.5: Latest OpenAI frontier model for complex reasoning, coding, and professional workflows. (Reasoning, Vision, Tools, Structured) | ctx: 1050k
gpt-5.5-pro: Higher-compute GPT-5.5 variant for the hardest professional and reasoning tasks. (Reasoning, Vision, Tools, Structured) | ctx: 1050k
gpt-5.4: Frontier model for coding and professional work with 1.05M context. (Reasoning, Vision, Tools, Structured) | ctx: 1050k
gpt-5.4-pro: Higher-compute GPT-5.4 variant for more precise responses on difficult tasks. (Reasoning, Vision, Tools, Structured) | ctx: 1050k
gpt-5.4-mini: Strong mini model for coding, computer use, and subagents. (Reasoning, Vision, Tools, Structured) | ctx: 400k
gpt-5.4-nano: Lowest-cost GPT-5.4-class model for high-volume classification, extraction, ranking, and subagents. (Reasoning, Vision, Tools, Structured) | ctx: 400k
gpt-5.3-codex: Agentic coding model optimized for Codex-like environments. (Reasoning, Vision, Tools, Structured) | ctx: 400k
gpt-5: Reasoning model for coding and agentic tasks across domains. (Reasoning, Vision, Tools, Structured) | ctx: 400k
gpt-5-mini: Cost-sensitive, low-latency GPT-5 model for well-defined tasks and precise prompts. (Reasoning, Vision, Tools, Structured) | ctx: 400k
gpt-5-nano: Fastest and lowest-cost GPT-5 model for summarization, classification, and routing. (Reasoning, Vision, Tools, Structured) | ctx: 400k
gpt-4.1: Smart non-reasoning model with strong instruction following and tool calling. (Vision, Tools, Structured) | ctx: 1048k
gpt-4.1-mini: Smaller, faster GPT-4.1 model with long-context support. (Vision, Tools, Structured) | ctx: 1048k
gpt-4.1-nano: Fastest and lowest-cost GPT-4.1 model for simple tasks. (Vision, Tools, Structured) | ctx: 1048k
gpt-4o: Legacy multimodal GPT model with broad ecosystem support. (Vision, Tools, Structured) | ctx: 128k
gpt-4o-mini: Fast, affordable GPT-4o model for focused tasks. (Vision, Tools, Structured) | ctx: 128k
... and 6 more models. Use list_models("openai") to see all.
The SDK provides a unified max_tokens parameter that automatically maps to the
correct API field based on the model and API type:
Chat API (standard models): max_tokens -> max_tokens
Chat API (o1/o3 models): max_tokens -> max_completion_tokens
Responses API: max_tokens -> max_output_tokens (total: reasoning + answer)
For advanced users who need fine-grained control:
max_completion_tokens: Explicitly set completion tokens (Chat API, o1/o3)
max_output_tokens: Explicitly set total output limit (Responses API)
max_answer_tokens: Limit answer only, excluding reasoning (Responses API, Volcengine-specific)
if (interactive()) { # Basic usage with Chat Completions API openai <- create_openai(api_key = "sk-...") model <- openai$language_model("gpt-4o") result <- generate_text(model, "Hello!") # Using Responses API for reasoning models openai <- create_openai() model <- openai$responses_model("o1") result <- generate_text(model, "Solve this math problem...") print(result$reasoning) # Access chain-of-thought # Smart model selection (auto-detects best API) model <- openai$smart_model("o3-mini") # Uses Responses API model <- openai$smart_model("gpt-4o") # Uses Chat Completions API # Token limits - unified interface # For standard models: limits generated content result <- model$generate(messages = msgs, max_tokens = 1000) # For o1/o3 models: automatically maps to max_completion_tokens model_o1 <- openai$language_model("o1") result <- model_o1$generate(messages = msgs, max_tokens = 2000) # For Responses API: automatically maps to max_output_tokens (total limit) model_resp <- openai$responses_model("o1") result <- model_resp$generate(messages = msgs, max_tokens = 2000) # Advanced: explicitly control answer-only limit (Volcengine Responses API) result <- model_resp$generate(messages = msgs, max_answer_tokens = 500) # Multi-turn conversation with Responses API model <- openai$responses_model("o1") result1 <- generate_text(model, "What is 2+2?") result2 <- generate_text(model, "Now multiply that by 3") # Remembers context model$reset() # Start fresh conversation }if (interactive()) { # Basic usage with Chat Completions API openai <- create_openai(api_key = "sk-...") model <- openai$language_model("gpt-4o") result <- generate_text(model, "Hello!") # Using Responses API for reasoning models openai <- create_openai() model <- openai$responses_model("o1") result <- generate_text(model, "Solve this math problem...") print(result$reasoning) # Access chain-of-thought # Smart model selection (auto-detects best API) model <- openai$smart_model("o3-mini") # Uses Responses API model <- openai$smart_model("gpt-4o") # Uses Chat Completions API # Token limits - unified interface # For standard models: limits generated content result <- model$generate(messages = msgs, max_tokens = 1000) # For o1/o3 models: automatically maps to max_completion_tokens model_o1 <- openai$language_model("o1") result <- model_o1$generate(messages = msgs, max_tokens = 2000) # For Responses API: automatically maps to max_output_tokens (total limit) model_resp <- openai$responses_model("o1") result <- model_resp$generate(messages = msgs, max_tokens = 2000) # Advanced: explicitly control answer-only limit (Volcengine Responses API) result <- model_resp$generate(messages = msgs, max_answer_tokens = 500) # Multi-turn conversation with Responses API model <- openai$responses_model("o1") result1 <- generate_text(model, "What is 2+2?") result2 <- generate_text(model, "Now multiply that by 3") # Remembers context model$reset() # Start fresh conversation }
Create a hook that enforces a permission mode for tool execution.
create_permission_hook( mode = c("implicit", "explicit", "escalate"), allowlist = c("search_web", "read_resource", "read_file") )create_permission_hook( mode = c("implicit", "explicit", "escalate"), allowlist = c("search_web", "read_resource", "read_file") )
mode |
Permission mode:
|
allowlist |
List of tool names that are auto-approved in "escalate" mode. Default includes read-only tools like "search_web", "read_file". |
A HookHandler object.
Creates an agent specialized in breaking down complex tasks into steps using chain-of-thought reasoning. The planner helps decompose problems and create action plans.
create_planner_agent(name = "PlannerAgent")create_planner_agent(name = "PlannerAgent")
name |
Agent name. Default "PlannerAgent". |
An Agent object configured for planning and reasoning.
if (interactive()) { planner <- create_planner_agent() result <- planner$run( "How should I approach building a machine learning model for customer churn?", model = "openai:gpt-4o" ) }if (interactive()) { planner <- create_planner_agent() result <- planner$run( "How should I approach building a machine learning model for customer churn?", model = "openai:gpt-4o" ) }
Creates a meta-tool (execute_r_code) backed by a SandboxManager.
This single tool replaces all individual tools for the LLM, enabling
batch execution, data filtering, and local computation.
create_r_code_tool(sandbox)create_r_code_tool(sandbox)
sandbox |
A SandboxManager object. |
A Tool object named execute_r_code.
Create built-in read-only tools for live R context inspection.
create_r_context_tools()create_r_context_tools()
A list of Tool objects.
Build Tool objects that let an Agent enrich diagnostic context on its own.
create_r_introspect_tools()create_r_introspect_tools()
A list of two Tool objects: r_eval and r_session_state.
## Not run: tools <- create_r_introspect_tools() agent <- create_agent( name = "Diagnostician", tools = tools, model = "openai:gpt-4o" ) ## End(Not run)## Not run: tools <- create_r_introspect_tools() agent <- create_agent( name = "Diagnostician", tools = tools, model = "openai:gpt-4o" ) ## End(Not run)
Generates a system prompt section that instructs the LLM how to use the R code sandbox effectively.
create_sandbox_system_prompt(sandbox)create_sandbox_system_prompt(sandbox)
sandbox |
A SandboxManager object. |
A character string to append to the system prompt.
Inspects an R function and generates a z_object schema based on its arguments and default values.
create_schema_from_func( func, include_args = NULL, exclude_args = NULL, params = NULL, func_name = NULL, type_mode = c("infer", "any") )create_schema_from_func( func, include_args = NULL, exclude_args = NULL, params = NULL, func_name = NULL, type_mode = c("infer", "any") )
func |
The R function to inspect. |
include_args |
Optional character vector of argument names to include. If provided, only these arguments will be included in the schema. |
exclude_args |
Optional character vector of argument names to exclude. |
params |
Optional named list of parameter values to use as defaults. This allows overriding the function's default values (e.g., with values extracted from an existing plot layer). |
func_name |
Optional string of the function name to look up documentation. If not provided, attempts to infer from 'func' symbol. |
type_mode |
How to assign parameter types. "infer" (default) uses default values to infer types. "any" uses z_any() for all parameters. |
A z_object schema.
if (interactive()) { my_func <- function(a = 1, b = "text", c = TRUE) {} schema <- create_schema_from_func(my_func) print(schema) # Override defaults schema_override <- create_schema_from_func(my_func, params = list(a = 99)) }if (interactive()) { my_func <- function(a = 1, b = "text", c = TRUE) {} schema <- create_schema_from_func(my_func) print(schema) # Override defaults schema_override <- create_schema_from_func(my_func, params = list(a = 99)) }
Build a semantic adapter that can describe and inspect domain-specific R objects.
Adapters are registered into a semantic adapter registry and selected by
supports(obj) predicates at runtime.
create_semantic_adapter( name, supports, capabilities = character(0), priority = 0, describe_identity = NULL, describe_schema = NULL, describe_semantics = NULL, peek = NULL, slice = NULL, list_accessors = NULL, estimate_cost = NULL, provenance = NULL, validate_action = NULL, render_summary = NULL, render_inspection = NULL )create_semantic_adapter( name, supports, capabilities = character(0), priority = 0, describe_identity = NULL, describe_schema = NULL, describe_semantics = NULL, peek = NULL, slice = NULL, list_accessors = NULL, estimate_cost = NULL, provenance = NULL, validate_action = NULL, render_summary = NULL, render_inspection = NULL )
name |
Adapter name. |
supports |
Function that returns |
capabilities |
Character vector of supported capabilities. |
priority |
Numeric priority; higher values win during dispatch. |
describe_identity |
Optional function returning identity metadata. |
describe_schema |
Optional function returning schema metadata. |
describe_semantics |
Optional function returning semantic summary metadata. |
peek |
Optional function for budget-aware preview generation. |
slice |
Optional function for budget-aware slicing. |
list_accessors |
Optional function returning recommended accessors. |
estimate_cost |
Optional function returning compute/token/I/O estimates. |
provenance |
Optional function returning provenance metadata. |
validate_action |
Optional function for safety validation. |
render_summary |
Optional function returning a human-readable summary. |
render_inspection |
Optional function returning a human-readable inspection. |
This constructor is part of the public semantic adapter authoring API for extension packages.
Adapter callbacks are optional unless noted otherwise.
supports(obj) should return a single TRUE or FALSE value and must not
error for unsupported objects.
The structured callbacks describe_identity(), describe_schema(),
describe_semantics(), estimate_cost(), and provenance() should return
named lists when supplied.
list_accessors() should return a character vector of recommended accessors.
validate_action() should return a named list with fields such as status,
reason, category, and expensive.
render_summary() and render_inspection() should return single character
strings suitable for user-facing output.
A SemanticAdapter object.
Create a registry for semantic adapters. The registry resolves the highest
priority adapter whose supports(obj) predicate matches an object.
create_semantic_adapter_registry(adapters = list())create_semantic_adapter_registry(adapters = list())
adapters |
Optional list of adapters to register on creation. |
This constructor is part of the public semantic adapter authoring API for extension packages.
The returned registry exposes register(), unregister(),
get_adapter(), list_adapters(), register_workflow_hint(),
list_workflow_hints(), resolve_workflow_hint(), and resolve()
methods.
A SemanticAdapterRegistry object.
Creates a session using either the new SharedSession or legacy ChatSession based on feature flags. This provides a migration path for existing code.
create_session( model = NULL, system_prompt = NULL, tools = NULL, hooks = NULL, max_steps = 10, ... )create_session( model = NULL, system_prompt = NULL, tools = NULL, hooks = NULL, max_steps = 10, ... )
model |
A LanguageModelV1 object or model string ID. |
system_prompt |
Optional system prompt. |
tools |
Optional list of Tool objects. |
hooks |
Optional HookHandler object. |
max_steps |
Maximum tool execution steps. Default 10. |
... |
Additional arguments passed to session constructor. |
A SharedSession or ChatSession object.
if (interactive()) { # Automatically uses SharedSession if feature enabled session <- create_session(model = "openai:gpt-4o") # Force legacy session sdk_set_feature("use_shared_session", FALSE) session <- create_session(model = "openai:gpt-4o") }if (interactive()) { # Automatically uses SharedSession if feature enabled session <- create_session(model = "openai:gpt-4o") # Force legacy session sdk_set_feature("use_shared_session", FALSE) session <- create_session(model = "openai:gpt-4o") }
Creates an advanced agent specialized in creating, testing, and refining new skills. It follows a rigorous "Ingest -> Design -> Implement -> Verify" workflow.
create_skill_architect_agent( name = "SkillArchitect", registry = NULL, model = NULL )create_skill_architect_agent( name = "SkillArchitect", registry = NULL, model = NULL )
name |
Agent name. Default "SkillArchitect". |
registry |
Optional SkillRegistry object (defaults to creating one from inst/skills). |
model |
The model object to use for verification (spawning a tester agent). |
An Agent object configured for skill architecture.
Convenience function to create and populate a SkillRegistry.
create_skill_registry(path, recursive = FALSE)create_skill_registry(path, recursive = FALSE)
path |
Path to scan for skills. |
recursive |
Whether to scan subdirectories. Default FALSE. |
A populated SkillRegistry object.
if (interactive()) { # Scan a skills directory registry <- create_skill_registry(".aimd/skills") # List available skills registry$list_skills() # Get a specific skill skill <- registry$get_skill("seurat_analysis") }if (interactive()) { # Scan a skills directory registry <- create_skill_registry(".aimd/skills") # List available skills registry$list_skills() # Get a specific skill skill <- registry$get_skill("seurat_analysis") }
Create the built-in tools for interacting with skills.
create_skill_tools(registry)create_skill_tools(registry)
registry |
A SkillRegistry object. |
A list of Tool objects.
Creates an AgentRegistry pre-populated with standard library agents based on feature flags.
create_standard_registry( include_data = TRUE, include_file = TRUE, include_env = TRUE, include_coder = TRUE, include_visualizer = TRUE, include_planner = TRUE, file_allowed_dirs = ".", env_allow_install = FALSE )create_standard_registry( include_data = TRUE, include_file = TRUE, include_env = TRUE, include_coder = TRUE, include_visualizer = TRUE, include_planner = TRUE, file_allowed_dirs = ".", env_allow_install = FALSE )
include_data |
Include DataAgent. Default TRUE. |
include_file |
Include FileAgent. Default TRUE. |
include_env |
Include EnvAgent. Default TRUE. |
include_coder |
Include CoderAgent. Default TRUE. |
include_visualizer |
Include VisualizerAgent. Default TRUE. |
include_planner |
Include PlannerAgent. Default TRUE. |
file_allowed_dirs |
Allowed directories for FileAgent. |
env_allow_install |
Allow package installation for EnvAgent. |
An AgentRegistry object.
if (interactive()) { # Create registry with all standard agents registry <- create_standard_registry() # Create registry with only data and visualization agents registry <- create_standard_registry( include_file = FALSE, include_env = FALSE, include_planner = FALSE ) }if (interactive()) { # Create registry with all standard agents registry <- create_standard_registry() # Create registry with only data and visualization agents registry <- create_standard_registry( include_file = FALSE, include_env = FALSE, include_planner = FALSE ) }
Create Telemetry
create_telemetry(trace_id = NULL, emit = TRUE)create_telemetry(trace_id = NULL, emit = TRUE)
trace_id |
Optional trace ID. |
emit |
Logical; when TRUE, events are printed as JSON lines. |
A Telemetry object.
Creates an agent specialized in creating data visualizations using ggplot2. Enhanced version with plot type recommendations, theme support, and automatic data inspection.
create_visualizer_agent( name = "VisualizerAgent", output_dir = NULL, default_theme = "theme_minimal", default_width = 8, default_height = 6 )create_visualizer_agent( name = "VisualizerAgent", output_dir = NULL, default_theme = "theme_minimal", default_width = 8, default_height = 6 )
name |
Agent name. Default "VisualizerAgent". |
output_dir |
Optional directory to save plots. If NULL, plots are stored in the session environment. |
default_theme |
Default ggplot2 theme. Default "theme_minimal". |
default_width |
Default plot width in inches. Default 8. |
default_height |
Default plot height in inches. Default 6. |
An Agent object configured for data visualization.
if (interactive()) { visualizer <- create_visualizer_agent() session <- create_shared_session(model = "openai:gpt-4o") session$set_var("df", data.frame(x = 1:10, y = (1:10)^2)) result <- visualizer$run( "Create a scatter plot of df showing the relationship between x and y", session = session, model = "openai:gpt-4o" ) }if (interactive()) { visualizer <- create_visualizer_agent() session <- create_shared_session(model = "openai:gpt-4o") session$set_var("df", data.frame(x = 1:10, y = (1:10)^2)) result <- visualizer$run( "Create a scatter plot of df showing the relationship between x and y", session = session, model = "openai:gpt-4o" ) }
Specialized wrapper around create_schema_from_func for ggtree/ggplot2 functions. Handles common mapping and data arguments specifically.
create_z_ggtree(func, layer = NULL)create_z_ggtree(func, layer = NULL)
func |
The R function (e.g., geom_tiplab). |
layer |
Optional ggplot2 Layer object. If provided, its parameters (aes_params and geom_params) will be used to override the schema defaults. This is useful for creating "Edit Mode" forms for existing plot layers. |
A z_object schema.
Return the standard skill search roots in increasing priority order: bundled package skills, installed user skills, project skills, then explicitly configured roots.
default_skill_roots(project_dir = getwd(), include_missing = FALSE)default_skill_roots(project_dir = getwd(), include_missing = FALSE)
project_dir |
Project directory used for project-local skill roots. |
include_missing |
If |
Character vector of skill root directories.
Edit images using an image editing model.
edit_image( model, image, prompt = NULL, mask = NULL, output_dir = tempdir(), registry = NULL, ... )edit_image( model, image, prompt = NULL, mask = NULL, output_dir = tempdir(), registry = NULL, ... )
model |
An |
image |
Image source or provider-specific image input. |
prompt |
Editing instructions. |
mask |
Optional mask image. |
output_dir |
Directory where edited images should be written. Defaults to |
registry |
Optional provider registry. |
... |
Additional arguments passed to the model implementation. |
A GenerateImageResult.
Abstract interface for embedding models.
specification_versionThe version of this specification.
providerThe provider identifier.
model_idThe model identifier.
new()
Initialize the embedding model.
EmbeddingModelV1$new(provider, model_id)
providerProvider name.
model_idModel ID.
do_embed()
Generate embeddings for a value. Abstract method.
EmbeddingModelV1$do_embed(value)
valueA character string or vector to embed.
A provider-specific embedding result.
clone()
The objects of this class are cloneable with this method.
EmbeddingModelV1$clone(deep = FALSE)
deepWhether to make a deep clone.
Check if API tests should be enabled
enable_api_tests()enable_api_tests()
TRUE if API tests are enabled and keys are available, FALSE otherwise
Execute a list of tool calls returned by an LLM. This function safely executes each tool, handling errors gracefully and returning a standardized result format.
Implements multi-layer defense strategy:
Tool name repair (case fixing, snake_case conversion, fuzzy matching)
Invalid tool routing for graceful degradation
Argument parsing with JSON repair
Error capture and structured error responses
execute_tool_calls( tool_calls, tools, hooks = NULL, envir = NULL, repair_enabled = TRUE )execute_tool_calls( tool_calls, tools, hooks = NULL, envir = NULL, repair_enabled = TRUE )
tool_calls |
A list of tool call objects, each with id, name, and arguments. |
tools |
A list of Tool objects to search for matching tools. |
hooks |
Optional HookHandler object. |
envir |
Optional environment in which to execute tools. When provided, tool functions can access and modify variables in this environment, enabling cross-agent data sharing through a shared session environment. |
repair_enabled |
Whether to attempt tool call repair (default TRUE). |
A list of execution results, each containing:
id: The tool call ID
name: The tool name
result: The execution result (or error message)
is_error: TRUE if an error occurred during execution
Custom testthat expectation that evaluates whether an LLM response meets specified criteria. Uses an LLM judge to assess the response.
expect_llm_pass(response, criteria, model = NULL, threshold = 0.7, info = NULL)expect_llm_pass(response, criteria, model = NULL, threshold = 0.7, info = NULL)
response |
The LLM response to evaluate (text or GenerateResult object). |
criteria |
Character string describing what constitutes a passing response. |
model |
Model to use for judging (default: same as response or gpt-4o). |
threshold |
Minimum score (0-1) to pass (default: 0.7). |
info |
Additional information to include in failure message. |
Invisibly returns the evaluation result.
if (interactive()) { test_that("agent answers math questions correctly", { result <- generate_text( model = "openai:gpt-4o", prompt = "What is 2 + 2?" ) expect_llm_pass(result, "The response should contain the number 4") }) }if (interactive()) { test_that("agent answers math questions correctly", { result <- generate_text( model = "openai:gpt-4o", prompt = "What is 2 + 2?" ) expect_llm_pass(result, "The response should contain the number 4") }) }
Test that an LLM response does not contain hallucinated information when compared against ground truth.
expect_no_hallucination( response, ground_truth, model = NULL, tolerance = 0.1, info = NULL )expect_no_hallucination( response, ground_truth, model = NULL, tolerance = 0.1, info = NULL )
response |
The LLM response to check. |
ground_truth |
The factual information to check against. |
model |
Model to use for checking. |
tolerance |
Allowed deviation (0 = strict, 1 = lenient). |
info |
Additional information for failure message. |
Test that an agent selects the correct tool(s) for a given task.
expect_tool_selection(result, expected_tools, exact = FALSE, info = NULL)expect_tool_selection(result, expected_tools, exact = FALSE, info = NULL)
result |
A GenerateResult object from generate_text with tools. |
expected_tools |
Character vector of expected tool names. |
exact |
If TRUE, require exactly these tools (no more, no less). |
info |
Additional information for failure message. |
Lightweight extension registry for console slash commands and optional tools.
Extract schema-constrained structured data from an image using a multimodal language model.
extract_from_image( model, image, schema, prompt = "Extract the requested structured information from this image.", system = NULL, registry = NULL, ... )extract_from_image( model, image, schema, prompt = "Extract the requested structured information from this image.", system = NULL, registry = NULL, ... )
model |
A |
image |
Image source accepted by |
schema |
A |
prompt |
Prompt describing the extraction task. |
system |
Optional system prompt. |
registry |
Optional provider registry. |
... |
Additional arguments passed to |
A GenerateResult.
Fetch available models from API provider
fetch_api_models(provider, api_key = NULL, base_url = NULL)fetch_api_models(provider, api_key = NULL, base_url = NULL)
provider |
Provider name ("openai", "nvidia", "anthropic", etc.) |
api_key |
API key |
base_url |
Base URL |
A data frame with 'id' column and capability flag columns
Provider class for Google Gemini.
specification_versionProvider spec version.
new()
Initialize the Gemini provider.
GeminiProvider$new( api_key = NULL, base_url = NULL, headers = NULL, name = NULL, timeout_seconds = NULL, total_timeout_seconds = NULL, first_byte_timeout_seconds = NULL, connect_timeout_seconds = NULL, idle_timeout_seconds = NULL )
api_keyGemini API key. Defaults to GEMINI_API_KEY env var.
base_urlBase URL for API calls. Defaults to https://generativelanguage.googleapis.com/v1beta/models.
headersOptional additional headers.
nameOptional provider name override.
timeout_secondsLegacy alias for total_timeout_seconds.
total_timeout_secondsOptional total request timeout in seconds for API calls.
first_byte_timeout_secondsOptional time-to-first-byte timeout in seconds for API calls.
connect_timeout_secondsOptional connection-establishment timeout in seconds for API calls.
idle_timeout_secondsOptional stall timeout in seconds for API calls.
language_model()
Create a language model.
GeminiProvider$language_model(
model_id = Sys.getenv("GEMINI_MODEL", "gemini-2.5-flash")
)model_idThe model ID (e.g., "gemini-1.5-pro", "gemini-1.5-flash", "gemini-2.0-flash").
A GeminiLanguageModel object.
image_model()
Create an image model.
GeminiProvider$image_model(
model_id = Sys.getenv("GEMINI_IMAGE_MODEL", "gemini-2.5-flash-image")
)model_idThe model ID for image generation.
A GeminiImageModel object.
clone()
The objects of this class are cloneable with this method.
GeminiProvider$clone(deep = FALSE)
deepWhether to make a deep clone.
Generate images using an image generation model.
generate_image(model, prompt, output_dir = tempdir(), registry = NULL, ...)generate_image(model, prompt, output_dir = tempdir(), registry = NULL, ...)
model |
An |
prompt |
Prompt describing the desired image. |
output_dir |
Directory where generated images should be written. Defaults to |
registry |
Optional provider registry. |
... |
Additional arguments passed to the model implementation. |
A GenerateImageResult.
Generate text using a language model. This is the primary high-level function for non-streaming text generation.
When tools are provided, the function automatically executes tool calls and
feeds results back to the LLM in a task-state driven runtime. max_steps
controls one execution window; the runtime may open another window or
finalize from tool observations instead of silently stopping at the boundary.
generate_text( model = NULL, prompt, system = NULL, temperature = 0.7, max_tokens = NULL, tools = NULL, max_steps = 1, max_tool_result_errors = 2, require_post_tool_protocol = FALSE, sandbox = FALSE, skills = NULL, session = NULL, hooks = NULL, registry = NULL, ... )generate_text( model = NULL, prompt, system = NULL, temperature = 0.7, max_tokens = NULL, tools = NULL, max_steps = 1, max_tool_result_errors = 2, require_post_tool_protocol = FALSE, sandbox = FALSE, skills = NULL, session = NULL, hooks = NULL, registry = NULL, ... )
model |
Either a LanguageModelV1 object, or a string ID like "openai:gpt-4o". |
prompt |
A character string prompt, or a list of messages. |
system |
Optional system prompt. |
temperature |
Sampling temperature (0-2). Default 0.7. |
max_tokens |
Maximum tokens to generate. |
tools |
Optional list of Tool objects for function calling. |
max_steps |
Number of model/tool steps in one execution window. Default 1. The runtime treats this as a budget checkpoint, not as a hard task stop. |
max_tool_result_errors |
Historical compatibility option. Tool result errors are recorded as task observations; runtime policy decides whether to continue, finalize, ask the user, or block. |
require_post_tool_protocol |
Logical. If TRUE, after any tool results
are returned the model must either make another tool call or wrap its final
answer in a |
sandbox |
Logical. If TRUE, enables R-native programmatic sandbox mode.
All tools are bound into an isolated R environment and replaced by a single
|
skills |
Optional path to skills directory, or a SkillRegistry object. When provided, skill tools are auto-injected and skill summaries are added to the system prompt. |
session |
Optional ChatSession object. When provided, tool executions run in the session's environment, enabling cross-agent data sharing. |
hooks |
Optional HookHandler object for intercepting events. |
registry |
Optional ProviderRegistry to use (defaults to global registry). |
... |
Additional arguments passed to the model. |
A GenerateResult object with text and optionally tool_calls. When max_steps > 1 and tools are used, the result includes:
steps: Number of steps taken
all_tool_calls: List of all tool calls made across all steps
if (interactive()) { # Using hooks my_hooks <- create_hooks( on_generation_start = function(model, prompt, tools) message("Starting..."), on_tool_start = function(tool, args) message("Calling tool ", tool$name) ) result <- generate_text(model, "...", hooks = my_hooks) }if (interactive()) { # Using hooks my_hooks <- create_hooks( on_generation_start = function(model, prompt, tools) message("Starting..."), on_tool_start = function(tool, args) message("Calling tool ", tool$name) ) result <- generate_text(model, "...", hooks = my_hooks) }
Result object returned by image generation and editing models.
imagesGenerated image artifacts.
textOptional textual companion output.
usageUsage information from the provider.
finish_reasonReason the model stopped generating.
warningsAny warnings from the model.
raw_responseThe raw response from the provider API.
new()
Initialize a GenerateImageResult object.
GenerateImageResult$new( images = NULL, text = NULL, usage = NULL, finish_reason = NULL, warnings = NULL, raw_response = NULL )
imagesGenerated image artifacts.
textOptional text output.
usageUsage information.
finish_reasonFinish reason.
warningsWarnings.
raw_responseRaw provider response.
print()
Print method for GenerateImageResult.
GenerateImageResult$print()
clone()
The objects of this class are cloneable with this method.
GenerateImageResult$clone(deep = FALSE)
deepWhether to make a deep clone.
Result object returned by model generation.
This class uses lock_objects = FALSE to allow dynamic field addition.
This enables the ReAct loop and other components to attach additional
metadata (like steps, all_tool_calls) without modifying the class.
For models that support reasoning/thinking (like OpenAI o1/o3, DeepSeek, Claude with extended thinking),
the reasoning field contains the model's chain-of-thought content.
For Responses API models, response_id contains the server-side response ID
which can be used for multi-turn conversations without sending full history.
textThe generated text content.
usageToken usage information.
finish_reasonReason the model stopped generating.
warningsAny warnings from the model.
raw_responseThe raw response from the provider API.
tool_callsList of tool calls requested by the model.
stepsNumber of ReAct loop steps taken.
all_tool_callsAccumulated list of all tool calls across steps.
reasoningOptional chain-of-thought or reasoning content.
response_idServer-side response ID for Responses-style APIs.
new()
Initialize a GenerateResult object.
GenerateResult$new( text = NULL, usage = NULL, finish_reason = NULL, warnings = NULL, raw_response = NULL, tool_calls = NULL, steps = NULL, all_tool_calls = NULL, reasoning = NULL, response_id = NULL )
textGenerated text.
usageToken usage.
finish_reasonReason for stopping.
warningsWarnings.
raw_responseRaw API response.
tool_callsTool calls requested by the model.
stepsNumber of ReAct steps taken.
all_tool_callsAll tool calls across steps.
reasoningChain-of-thought content.
response_idServer-side response ID for Responses-style APIs.
print()
Print method for GenerateResult.
GenerateResult$print()
clone()
The objects of this class are cloneable with this method.
GenerateResult$clone(deep = FALSE)
deepWhether to make a deep clone.
Get Anthropic base URL from environment
get_anthropic_base_url()get_anthropic_base_url()
Base URL for Anthropic API (default: official)
Get Anthropic model name from environment
get_anthropic_model()get_anthropic_model()
Model name (default: claude-sonnet-4-20250514)
Get Anthropic model ID from environment
get_anthropic_model_id()get_anthropic_model_id()
Model ID (default: anthropic:claude-sonnet-4-20250514)
Return the configured model for a capability route.
get_capability_model(capability, default = NULL)get_capability_model(capability, default = NULL)
capability |
Capability route name. |
default |
Value returned when no route is configured. |
A model ID string, model object, or default.
Resolve the active context-management configuration for a session.
get_context_management_config(session)get_context_management_config(session)
session |
A |
A normalized configuration list.
Returns the global default provider registry, creating it if necessary.
get_default_registry()get_default_registry()
A ProviderRegistry object.
Get the global project memory instance, creating it if necessary.
get_memory()get_memory()
A ProjectMemory object.
Returns the current package-wide default language model. This is used by
high-level helpers when model = NULL. If no explicit default has been set,
get_model() falls back to getOption("aisdk.default_model"), then to
default_model in aisdk.yaml, and then to "openai:gpt-4o".
get_model(default = "openai:gpt-4o")get_model(default = "openai:gpt-4o")
default |
Fallback model identifier when no explicit default has been set. |
A model identifier string or a LanguageModelV1 object.
get_model()get_model()
Returns the full metadata for a single model as a list. Useful for framework internals to auto-configure parameters (e.g., max_tokens, context_window).
get_model_info(provider, model_id)get_model_info(provider, model_id)
provider |
The name of the provider. |
model_id |
The model ID string. |
A list containing all available metadata for the model, or NULL if not found.
Returns runtime options configured with set_model(), including context
overrides and default generation options such as thinking settings.
get_model_options()get_model_options()
A list with optional context_window, max_output_tokens, and
call_options entries.
Get OpenAI Base URL from environment
get_openai_base_url()get_openai_base_url()
Base URL string
Get OpenAI Embedding Model from environment
get_openai_embedding_model()get_openai_embedding_model()
Model name string
Get OpenAI Model from environment
get_openai_model()get_openai_model()
Model name string
Get OpenAI Model ID from environment
get_openai_model_id()get_openai_model_id()
Model ID string
Resolve the semantic adapter registry from an environment, or create and cache a default registry when one is not already present.
get_or_create_semantic_adapter_registry(envir = NULL)get_or_create_semantic_adapter_registry(envir = NULL)
envir |
Optional environment that stores |
This helper is safe for extension packages that need to share the active semantic registry through a session or custom environment.
A SemanticAdapterRegistry object.
Generates a text summary of R objects to be used as context for the LLM.
get_r_context(vars, envir = parent.frame())get_r_context(vars, envir = parent.frame())
vars |
Character vector of variable names to include. |
envir |
The environment to look for variables in. Default is parent.frame(). |
A single string containing the summaries of the requested variables.
if (interactive()) { df <- data.frame(x = 1:10, y = rnorm(10)) context <- get_r_context("df") cat(context) }if (interactive()) { df <- data.frame(x = 1:10, y = rnorm(10)) context <- get_r_context("df") cat(context) }
Resolve an Rd topic and return a selected section.
get_r_documentation( name, package = NULL, section = c("summary", "usage", "arguments", "details", "value", "examples", "full"), session = NULL, envir = NULL, max_chars = 4000L )get_r_documentation( name, package = NULL, section = c("summary", "usage", "arguments", "details", "value", "examples", "full"), session = NULL, envir = NULL, max_chars = 4000L )
name |
Topic or function name. |
package |
Optional package/namespace name. |
section |
One of |
session |
Optional |
envir |
Optional environment. Ignored when |
max_chars |
Maximum characters to return. |
A character string with the requested documentation.
Resolve function source text for a closure or method when available.
get_r_source( name, package = NULL, method = NULL, session = NULL, envir = NULL, max_lines = 120L )get_r_source( name, package = NULL, method = NULL, session = NULL, envir = NULL, max_lines = 120L )
name |
Function or generic name. |
package |
Optional package/namespace name. |
method |
Optional S3 method class name. |
session |
Optional |
envir |
Optional environment. Ignored when |
max_lines |
Maximum lines to return. |
A character string source preview or structured fallback message.
Check if specific provider key is available
has_api_key(provider)has_api_key(provider)
provider |
Provider name ("openai" or "anthropic") |
TRUE if key is available and valid
R6 class to manage and execute hooks.
hooksList of hook functions.
new()
Initialize HookHandler
HookHandler$new(hooks_list = list())
hooks_listA list of hook functions. Supported hooks:
on_generation_start(model, prompt, tools)
on_generation_end(result)
on_tool_start(tool, args)
on_tool_end(tool, result)
on_tool_approval(tool, args) - Return TRUE to approve, FALSE to deny.
trigger_generation_start()
Trigger on_generation_start
HookHandler$trigger_generation_start(model, prompt, tools)
modelThe language model object.
promptThe prompt being sent.
toolsThe list of tools provided.
trigger_generation_end()
Trigger on_generation_end
HookHandler$trigger_generation_end(result)
resultThe generation result object.
trigger_tool_start()
Trigger on_tool_start
HookHandler$trigger_tool_start(tool, args)
toolThe tool object.
argsThe arguments for the tool.
trigger_tool_end()
Trigger on_tool_end
HookHandler$trigger_tool_end( tool, result, success = TRUE, error = NULL, args = NULL )
toolThe tool object.
resultThe result from the tool execution.
successLogical indicating whether execution succeeded.
errorOptional error message when execution failed.
argsOptional tool arguments for downstream telemetry.
clone()
The objects of this class are cloneable with this method.
HookHandler$clone(deep = FALSE)
deepWhether to make a deep clone.
A system for intercepting and monitoring AI SDK events. Allows implementation of "Human-in-the-loop", logging, and validation.
Advanced self-healing execution that generates hypotheses about errors, attempts fixes, and verifies the results.
hypothesis_fix_verify( code, model = NULL, test_fn = NULL, max_iterations = 5, verbose = TRUE )hypothesis_fix_verify( code, model = NULL, test_fn = NULL, max_iterations = 5, verbose = TRUE )
code |
Character string of R code to execute. |
model |
LLM model for analysis. |
test_fn |
Optional function to verify the result is correct. |
max_iterations |
Maximum fix iterations. |
verbose |
Print progress. |
List with result, fix history, and verification status.
Abstract interface for image generation and editing models.
specification_versionThe version of this specification.
providerThe provider identifier.
model_idThe model identifier.
capabilitiesModel capability flags.
new()
Initialize the image model.
ImageModelV1$new(provider, model_id, capabilities = list())
providerProvider name.
model_idModel ID.
capabilitiesOptional list of capability flags.
has_capability()
Check if the image model has a specific capability.
ImageModelV1$has_capability(cap)
capCapability name.
Logical.
generate_image()
Public image generation method.
ImageModelV1$generate_image(...)
...Call options passed to do_generate_image().
A GenerateImageResult object.
edit_image()
Public image editing method.
ImageModelV1$edit_image(...)
...Call options passed to do_edit_image().
A GenerateImageResult object.
do_generate_image()
Generate images. Abstract method.
ImageModelV1$do_generate_image(params)
paramsA list of call options.
A GenerateImageResult object.
do_edit_image()
Edit images. Abstract method.
ImageModelV1$do_edit_image(params)
paramsA list of call options.
A GenerateImageResult object.
do_stream_image()
Stream image generation with partial-image previews.
Optional — subclasses that support it override. Default raises an
informative error so stream_image() callers can fall back to
generate_image() on providers without streaming support.
ImageModelV1$do_stream_image(params, callback)
paramsA list of call options.
callbackA function called with each event list.
A GenerateImageResult object with the final image.
stream_image()
Public image streaming method.
ImageModelV1$stream_image(callback, ...)
callbackA function receiving each event list.
...Call options passed to do_stream_image().
A GenerateImageResult object.
clone()
The objects of this class are cloneable with this method.
ImageModelV1$clone(deep = FALSE)
deepWhether to make a deep clone.
Create a provider-neutral image block for multimodal message content. Supports local files, remote URLs, and data URIs.
input_image(x, media_type = "auto", detail = "auto")input_image(x, media_type = "auto", detail = "auto")
x |
Image source as a local file path, remote URL, or data URI. |
media_type |
MIME type of the image. If |
detail |
Optional image detail hint for providers that support it. |
A list representing an input image block.
Create a provider-neutral text block for multimodal message content.
input_text(text)input_text(text)
text |
Text content. |
A list representing an input text block.
Inspect function signature and provenance without dumping full source by default.
inspect_r_function( name, package = NULL, detail = c("summary", "full"), include_methods = FALSE, session = NULL, envir = NULL )inspect_r_function( name, package = NULL, detail = c("summary", "full"), include_methods = FALSE, session = NULL, envir = NULL )
name |
Function name. |
package |
Optional package/namespace name. |
detail |
One of |
include_methods |
Logical; whether to include S3/S4 method previews. |
session |
Optional |
envir |
Optional environment. Ignored when |
A character string inspection.
Inspect a symbol resolved from the live session environment.
inspect_r_object( name, detail = c("summary", "full", "structured"), session = NULL, envir = NULL, head_rows = 6L, scope = c("all", "session", "workspace") )inspect_r_object( name, detail = c("summary", "full", "structured"), session = NULL, envir = NULL, head_rows = 6L, scope = c("all", "session", "workspace") )
name |
Symbol-like object name. |
detail |
One of |
session |
Optional |
envir |
Optional environment. Ignored when |
head_rows |
Maximum preview rows for inspection renderers. |
scope |
Where to resolve the object. Defaults to |
A character string for "summary"/"full" or a structured list for
"structured".
Test class membership using S3 inherits() and S4 methods::is() fallback.
This helper is intended for robust adapter supports() predicates.
is_semantic_class(obj, class_name)is_semantic_class(obj, class_name)
obj |
Object to test. |
class_name |
Class name to check. |
TRUE if obj matches class_name; otherwise FALSE.
Abstract interface for language models. All LLM providers must implement this class.
Uses do_ prefix for internal methods to prevent direct usage by end-users.
specification_versionThe version of this specification.
providerThe provider identifier (e.g., "openai").
model_idThe model identifier (e.g., "gpt-4o").
capabilitiesModel capability flags.
new()
Initialize the model with provider and model ID.
LanguageModelV1$new(provider, model_id, capabilities = list())
providerProvider name.
model_idModel ID.
capabilitiesOptional list of capability flags.
has_capability()
Check if the model has a specific capability.
LanguageModelV1$has_capability(cap)
capCapability name.
Logical.
generate()
Public generation method.
LanguageModelV1$generate(...)
...Call options passed to do_generate().
A GenerateResult object.
stream()
Public streaming method.
LanguageModelV1$stream(callback, ...)
callbackCallback invoked with (text, done).
...Call options passed to do_stream().
A GenerateResult object.
do_generate()
Generate text (non-streaming). Abstract method.
LanguageModelV1$do_generate(params)
paramsA list of call options.
A GenerateResult object.
do_stream()
Generate text (streaming). Abstract method.
LanguageModelV1$do_stream(params, callback)
paramsA list of call options.
callbackCallback invoked with (text, done).
A GenerateResult object.
format_tool_result()
Format a tool execution result for the provider API.
LanguageModelV1$format_tool_result(tool_call_id, tool_name, result_content)
tool_call_idThe tool call identifier.
tool_nameThe tool name.
result_contentThe tool execution result.
A provider-specific tool result message.
get_history_format()
Get the message history format used by this model.
LanguageModelV1$get_history_format()
A character string such as "openai" or "anthropic".
clone()
The objects of this class are cloneable with this method.
LanguageModelV1$clone(deep = FALSE)
deepWhether to make a deep clone.
List configured capability model routes.
list_capability_models()list_capability_models()
A data frame with capability route names and model settings.
Builds compact handles for live session context without embedding full object payloads in the prompt.
list_context_handles(session, state = NULL, persist = TRUE)list_context_handles(session, state = NULL, persist = TRUE)
session |
A |
state |
Optional normalized context state. Defaults to the session state. |
persist |
Logical; whether to persist the handle list into the session context state. |
A list of compact context handle records.
Returns a data frame of models for the specified provider based on the static configuration. Includes enriched metadata when available (context window, pricing, capabilities).
list_models(provider = NULL)list_models(provider = NULL)
provider |
The name of the provider (e.g., "stepfun"). If NULL, all providers are listed. |
A data frame containing model details.
List live objects visible in the session environment.
list_r_objects( session = NULL, envir = NULL, pattern = NULL, include_hidden = FALSE, limit = 50L, scope = c("session", "workspace", "all") )list_r_objects( session = NULL, envir = NULL, pattern = NULL, include_hidden = FALSE, limit = 50L, scope = c("session", "workspace", "all") )
session |
Optional |
envir |
Optional environment. Ignored when |
pattern |
Optional regex pattern used to filter names. |
|
Logical; whether to include names starting with |
|
limit |
Maximum number of rows to return. |
scope |
One of |
A data frame with object metadata.
Load a previously saved ChatSession from a file.
load_chat_session(path, tools = NULL, hooks = NULL, registry = NULL)load_chat_session(path, tools = NULL, hooks = NULL, registry = NULL)
path |
File path to load from (.rds or .json). |
tools |
Optional list of Tool objects (tools are not saved, must be re-provided). |
hooks |
Optional HookHandler object. |
registry |
Optional ProviderRegistry. |
A ChatSession object with restored state.
if (interactive()) { # Load a saved session chat <- load_chat_session("my_session.rds", tools = my_tools) # Continue where you left off response <- chat$send("Let's continue our discussion") }if (interactive()) { # Load a saved session chat <- load_chat_session("my_session.rds", tools = my_tools) # Continue where you left off response <- chat$send("Let's continue our discussion") }
Defines a middleware that can intercept and modify model operations.
nameA descriptive name for this middleware.
transform_params()
Transform parameters before calling the model.
Middleware$transform_params(params, type, model)
paramsThe original call parameters.
typeEither "generate" or "stream".
modelThe model being called.
The transformed parameters.
wrap_generate()
Wrap the generate operation.
Middleware$wrap_generate(do_generate, params, model)
do_generateA function that calls the model's do_generate.
paramsThe (potentially transformed) parameters.
modelThe model being called.
The result of the generation.
wrap_stream()
Wrap the stream operation.
Middleware$wrap_stream(do_stream, params, model, callback)
do_streamA function that calls the model's do_stream.
paramsThe (potentially transformed) parameters.
modelThe model being called.
callbackThe streaming callback function.
clone()
The objects of this class are cloneable with this method.
Middleware$clone(deep = FALSE)
deepWhether to make a deep clone.
Provides migration guidance for legacy code patterns.
migrate_pattern(pattern)migrate_pattern(pattern)
pattern |
The legacy pattern to migrate from. |
A list with old_pattern, new_pattern, and example.
if (interactive()) { # Get migration guidance for ChatSession guidance <- migrate_pattern("ChatSession") cat(guidance$example) }if (interactive()) { # Get migration guidance for ChatSession guidance <- migrate_pattern("ChatSession") cat(guidance$example) }
Shortcut for default model configuration. Call with no arguments to read the
current default model, or pass a model to update it. This is equivalent to
calling get_model() and set_model() directly. Runtime options can be
supplied without new to update the current default model's options.
model(new, ...)model(new, ...)
new |
Optional model identifier string or |
... |
Runtime options forwarded to |
When new is missing, returns the current default model. Otherwise
invisibly returns the previous default model.
model() model("openai:gpt-4o-mini") model(NULL)model() model("openai:gpt-4o-mini") model(NULL)
Utilities for reading and updating the package-wide default language model.
High-level helpers that accept model = NULL, including generate_text(),
stream_text(), ChatSession$new(), create_chat_session(),
auto_fix(), and the knitr {ai} engine, use this default when no
explicit model is supplied.
Helper functions for constructing multimodal messages (text and images).
Inspect a live object through the existing semantic inspection adapters.
object_peek( session, name, detail = c("summary", "structure", "sample", "full") )object_peek( session, name, detail = c("summary", "structure", "sample", "full") )
session |
A |
name |
Object name in the session environment. |
detail |
One of |
A compact inspection string.
Object Strategy
Object Strategy
Strategy for generating structured objects based on a JSON Schema. This strategy instructs the LLM to produce valid JSON matching the schema, and handles parsing and validation of the output.
aisdk::OutputStrategy -> ObjectStrategy
schemaThe schema definition (from z_object, etc.).
schema_nameHuman-readable name for the schema.
new()
Initialize the ObjectStrategy.
ObjectStrategy$new(schema, schema_name = "json_schema")
schemaA schema object created by z_object, z_array, etc.
schema_nameAn optional name for the schema (default: "json_schema").
get_instruction()
Generate the instruction for the LLM to output valid JSON.
ObjectStrategy$get_instruction()
A character string with the prompt instruction.
validate()
Validate and parse the LLM output as JSON.
ObjectStrategy$validate(text, is_final = FALSE)
textThe raw text output from the LLM.
is_finalLogical, TRUE if this is the final output.
The parsed R object (list), or NULL if parsing fails.
clone()
The objects of this class are cloneable with this method.
ObjectStrategy$clone(deep = FALSE)
deepWhether to make a deep clone.
Give the model an OpenAI-hosted Python sandbox.
openai_code_interpreter_tool(container = list(type = "auto"))openai_code_interpreter_tool(container = list(type = "auto"))
container |
Container spec. Defaults to |
A plain list ready to drop into tools = list(...).
## Not run: generate_text( model, "Solve 3x + 11 = 14 step by step.", tools = list(openai_code_interpreter_tool()) ) ## End(Not run)## Not run: generate_text( model, "Solve 3x + 11 = 14 step by step.", tools = list(openai_code_interpreter_tool()) ) ## End(Not run)
Browser / desktop control. The model issues actions (click, type, scroll, screenshot) which the caller's harness executes against a virtual computer.
openai_computer_use_tool( display_width = NULL, display_height = NULL, environment = c("browser", "mac", "windows", "ubuntu") )openai_computer_use_tool( display_width = NULL, display_height = NULL, environment = c("browser", "mac", "windows", "ubuntu") )
display_width, display_height
|
Integer screen dimensions in pixels. Required by the API on most environments. |
environment |
One of |
A plain list ready to drop into tools = list(...).
Configure the Responses API's hosted RAG over one or more vector stores you've uploaded to OpenAI.
openai_file_search_tool( vector_store_ids, max_num_results = NULL, ranking_options = NULL )openai_file_search_tool( vector_store_ids, max_num_results = NULL, ranking_options = NULL )
vector_store_ids |
Character vector of vector-store IDs to search. Required, non-empty. |
max_num_results |
Optional integer cap on how many chunks the model sees per call. |
ranking_options |
Optional named list for advanced ranking config
(e.g. |
A plain list ready to drop into tools = list(...).
## Not run: generate_text( model, "What does the design doc say about caching?", tools = list(openai_file_search_tool(c("vs_abc123"))) ) ## End(Not run)## Not run: generate_text( model, "What does the design doc say about caching?", tools = list(openai_file_search_tool(c("vs_abc123"))) ) ## End(Not run)
Give the model access to a remote MCP server, executed
server-side by OpenAI. This is independent of aisdk's local MCP client
(R/mcp_client.R) — that one connects from R, this one tells OpenAI to
connect on the model's behalf.
openai_hosted_mcp_tool( server_label, server_url = NULL, connector_id = NULL, server_description = NULL, allowed_tools = NULL, require_approval = NULL, authorization = NULL, headers = NULL )openai_hosted_mcp_tool( server_label, server_url = NULL, connector_id = NULL, server_description = NULL, allowed_tools = NULL, require_approval = NULL, authorization = NULL, headers = NULL )
server_label |
Required label used to identify the server in tool calls. |
server_url |
URL of a custom MCP server. Exactly one of |
connector_id |
OpenAI-managed connector ID (e.g. |
server_description |
Optional human-readable description. |
allowed_tools |
Optional character vector of tool names to expose, or
a list filter (e.g. |
require_approval |
|
authorization |
Optional OAuth access token. |
headers |
Optional named list of HTTP headers sent to the MCP server. |
A plain list ready to drop into tools = list(...).
## Not run: generate_text( model, "Roll 2d4+1", tools = list(openai_hosted_mcp_tool( server_label = "dmcp", server_url = "https://dmcp-server.deno.dev/sse", allowed_tools = "roll", require_approval = "never" )) ) ## End(Not run)## Not run: generate_text( model, "Roll 2d4+1", tools = list(openai_hosted_mcp_tool( server_label = "dmcp", server_url = "https://dmcp-server.deno.dev/sse", allowed_tools = "roll", require_approval = "never" )) ) ## End(Not run)
Build the configuration for OpenAI's model-hosted web search, used via the Responses API. The model decides whether to search based on the prompt.
openai_web_search_tool( allowed_domains = NULL, user_location = NULL, search_context_size = NULL, type = c("web_search", "web_search_preview") )openai_web_search_tool( allowed_domains = NULL, user_location = NULL, search_context_size = NULL, type = c("web_search", "web_search_preview") )
allowed_domains |
Optional character vector of domains the search is
restricted to. Forwarded as |
user_location |
Optional named list with any of |
search_context_size |
Optional |
type |
The tool type identifier. Defaults to |
A plain list ready to drop into tools = list(...).
## Not run: model <- create_openai()$responses_model("gpt-5") generate_text( model, "Latest material AAPL news?", tools = list(openai_web_search_tool(search_context_size = "high")) ) ## End(Not run)## Not run: model <- create_openai()$responses_model("gpt-5") generate_text( model, "Latest material AAPL news?", tools = list(openai_web_search_tool(search_context_size = "high")) ) ## End(Not run)
Provider class for OpenAI. Can create language and embedding models.
specification_versionProvider spec version.
new()
Initialize the OpenAI provider.
OpenAIProvider$new(
api_key = NULL,
base_url = NULL,
organization = NULL,
project = NULL,
headers = NULL,
name = NULL,
timeout_seconds = NULL,
total_timeout_seconds = NULL,
first_byte_timeout_seconds = NULL,
connect_timeout_seconds = NULL,
idle_timeout_seconds = NULL,
disable_stream_options = FALSE,
api_format = c("auto", "chat", "responses")
)api_keyOpenAI API key. Defaults to OPENAI_API_KEY env var.
base_urlBase URL for API calls. Defaults to https://api.openai.com/v1.
organizationOptional OpenAI organization ID.
projectOptional OpenAI project ID.
headersOptional additional headers.
nameOptional provider name override (for compatible APIs).
timeout_secondsLegacy alias for total_timeout_seconds.
total_timeout_secondsOptional total request timeout in seconds for API calls.
first_byte_timeout_secondsOptional time-to-first-byte timeout in seconds for API calls.
connect_timeout_secondsOptional connection-establishment timeout in seconds for API calls.
idle_timeout_secondsOptional stall timeout in seconds for API calls.
disable_stream_optionsDisable stream_options parameter (for providers that don't support it).
api_formatDefault API surface for smart_model() / model():
"auto" (route reasoning models to Responses, others to Chat — the
canonical OpenAI behavior), "chat" (always Chat Completions — useful
for proxies that don't expose /responses, or that surface reasoning
models like gpt-5.x via /chat/completions), or "responses" (always
Responses API). The explicit language_model() and responses_model()
methods continue to ignore this setting.
language_model()
Create a language model (always Chat Completions API).
OpenAIProvider$language_model(model_id = Sys.getenv("OPENAI_MODEL", "gpt-4o"))model_idThe model ID (e.g., "gpt-4o", "gpt-4o-mini").
An OpenAILanguageModel object.
responses_model()
Create a language model using the Responses API.
OpenAIProvider$responses_model(model_id)
model_idThe model ID (e.g., "o1", "o3-mini", "gpt-4o").
The Responses API is designed for:
Models with built-in reasoning (o1, o3 series)
Stateful multi-turn conversations (server maintains history)
Advanced features like structured outputs
The model maintains conversation state internally via response IDs.
Call model$reset() to start a fresh conversation.
An OpenAIResponsesLanguageModel object.
model()
Default-route factory. Picks chat vs responses based on the
api_format set in create_openai(). Recommended entry point for
callers that don't care which surface is used.
OpenAIProvider$model(model_id = Sys.getenv("OPENAI_MODEL", "gpt-4o"))model_idThe model ID. Defaults to OPENAI_MODEL env var.
A LanguageModelV1 instance.
smart_model()
Smart model factory that selects the API surface.
OpenAIProvider$smart_model( model_id, api_format = private$config$api_format %||% "auto" )
model_idThe model ID.
api_formatAPI format: "auto" (default — reasoning → Responses,
others → Chat), "chat", or "responses". Defaults to the
api_format passed to create_openai().
When api_format = "auto", the method picks:
Responses API for reasoning models (o1, o3, gpt-5, ...)
Chat Completions API for everything else
Override per-call when the provider's default doesn't match the specific model you're about to use.
A language model object (either OpenAILanguageModel or OpenAIResponsesLanguageModel).
embedding_model()
Create an embedding model.
OpenAIProvider$embedding_model(model_id = "text-embedding-3-small")
model_idThe model ID (e.g., "text-embedding-3-small").
An OpenAIEmbeddingModel object.
image_model()
Create an image model.
OpenAIProvider$image_model(
model_id = Sys.getenv("OPENAI_IMAGE_MODEL", "gpt-image-2")
)model_idThe model ID (e.g., "gpt-image-2", "gpt-image-1.5").
An OpenAIImageModel object.
create_conversation()
Create a server-side conversation object via
POST /v1/conversations. Returns the parsed response, including the
conversation id you can pass as conversation = "conv_..." to
generate_text() / stream_text() so OpenAI manages the message
history server-side instead of you sending the full transcript each
turn.
OpenAIProvider$create_conversation(items = NULL, metadata = NULL)
itemsOptional list of initial conversation items, each shaped
like list(type = "message", role = "user", content = "Hello!").
metadataOptional named list (up to 16 keys, values stringified).
Parsed response list with at least id, object, created_at,
metadata.
get_conversation()
Retrieve a conversation object by id.
OpenAIProvider$get_conversation(conversation_id)
conversation_idConversation id returned from create_conversation().
Parsed response list.
delete_conversation()
Delete a conversation object by id. Server-side history is irrecoverable after this call.
OpenAIProvider$delete_conversation(conversation_id)
conversation_idConversation id returned from create_conversation().
Parsed response list (typically list(id, object, deleted)).
clone()
The objects of this class are cloneable with this method.
OpenAIProvider$clone(deep = FALSE)
deepWhether to make a deep clone.
Output Strategy Interface
Output Strategy Interface
Abstract R6 class defining the interface for output strategies.
Subclasses must implement get_instruction() and validate().
new()
Initialize the strategy.
OutputStrategy$new()
get_instruction()
Get the system prompt instruction for this strategy.
OutputStrategy$get_instruction()
A character string with instructions for the LLM.
validate()
Parse and validate the output text.
OutputStrategy$validate(text, is_final = FALSE)
textThe raw text output from the LLM.
is_finalLogical, TRUE if this is the final output (not streaming).
The parsed and validated object.
clone()
The objects of this class are cloneable with this method.
OutputStrategy$clone(deep = FALSE)
deepWhether to make a deep clone.
Print a comprehensive migration guide for upgrading to the new SDK version.
print_migration_guide(verbose = TRUE)print_migration_guide(verbose = TRUE)
verbose |
Include detailed examples. Default TRUE. |
Invisible NULL (prints to console).
Print GenerateObjectResult
## S3 method for class 'GenerateObjectResult' print(x, ...)## S3 method for class 'GenerateObjectResult' print(x, ...)
x |
A GenerateObjectResult object. |
... |
Additional arguments (ignored). |
Pretty print a z_schema object.
## S3 method for class 'z_schema' print(x, ...)## S3 method for class 'z_schema' print(x, ...)
x |
A z_schema object. |
... |
Additional arguments (ignored). |
Long-term memory storage for AI agents using SQLite. Stores successful code snippets, error fixes, and execution history for RAG (Retrieval Augmented Generation) and learning from past interactions.
Factory function to create or connect to a project memory database.
project_memory(project_root = tempdir(), db_name = "memory.sqlite")project_memory(project_root = tempdir(), db_name = "memory.sqlite")
project_root |
Project root directory. |
db_name |
Database filename. |
A ProjectMemory object.
if (interactive()) { # Create memory for current project memory <- project_memory() # Store a successful code snippet memory$store_snippet( code = "df %>% filter(x > 0) %>% summarize(mean = mean(y))", description = "Filter and summarize data", tags = c("dplyr", "summarize") ) # Store an error fix memory$store_fix( original_code = "mean(df$x)", error = "argument is not numeric or logical", fixed_code = "mean(as.numeric(df$x), na.rm = TRUE)", fix_description = "Convert to numeric and handle NAs" ) # Search for relevant snippets memory$search_snippets("summarize") }if (interactive()) { # Create memory for current project memory <- project_memory() # Store a successful code snippet memory$store_snippet( code = "df %>% filter(x > 0) %>% summarize(mean = mean(y))", description = "Filter and summarize data", tags = c("dplyr", "summarize") ) # Store an error fix memory$store_fix( original_code = "mean(df$x)", error = "argument is not numeric or logical", fixed_code = "mean(as.numeric(df$x), na.rm = TRUE)", fix_description = "Convert to numeric and handle NAs" ) # Search for relevant snippets memory$search_snippets("summarize") }
R6 class for managing persistent project memory using SQLite. Stores code snippets, error fixes, and execution graphs for resuming failed long-running jobs.
db_pathPath to the SQLite database file.
project_rootRoot directory of the project.
new()
Create or connect to a project memory database.
ProjectMemory$new(project_root = tempdir(), db_name = "memory.sqlite")
project_rootProject root directory. Defaults to tempdir().
db_nameDatabase filename. Defaults to "memory.sqlite".
A new ProjectMemory object.
store_snippet()
Store a successful code snippet for future reference.
ProjectMemory$store_snippet( code, description = NULL, tags = NULL, context = NULL )
codeThe R code that was executed successfully.
descriptionOptional description of what the code does.
tagsOptional character vector of tags for categorization.
contextOptional context about when/why this code was used.
The ID of the stored snippet.
store_fix()
Store an error fix for learning.
ProjectMemory$store_fix( original_code, error, fixed_code, fix_description = NULL )
original_codeThe code that produced the error.
errorThe error message.
fixed_codeThe corrected code.
fix_descriptionDescription of what was fixed.
The ID of the stored fix.
find_similar_fix()
Find a similar fix from memory.
ProjectMemory$find_similar_fix(error)
errorThe error message to match.
A list with the fix details, or NULL if not found.
search_snippets()
Search for relevant code snippets.
ProjectMemory$search_snippets(query, limit = 10)
querySearch query (matches description, tags, or code).
limitMaximum number of results.
A data frame of matching snippets.
store_workflow_node()
Store execution graph node for workflow persistence.
ProjectMemory$store_workflow_node( workflow_id, node_id, node_type, code, status = "pending", result = NULL, dependencies = NULL )
workflow_idUnique identifier for the workflow.
node_idUnique identifier for this node.
node_typeType of node (e.g., "transform", "model", "output").
codeThe code for this node.
statusNode status ("pending", "running", "completed", "failed").
resultOptional serialized result.
dependenciesCharacter vector of node IDs this depends on.
The database row ID.
update_node_status()
Update workflow node status.
ProjectMemory$update_node_status(workflow_id, node_id, status, result = NULL)
workflow_idWorkflow identifier.
node_idNode identifier.
statusNew status.
resultOptional result to store.
get_workflow()
Get workflow state for resuming.
ProjectMemory$get_workflow(workflow_id)
workflow_idWorkflow identifier.
A list with workflow nodes and their states.
get_resumable_nodes()
Resume a failed workflow from the last successful point.
ProjectMemory$get_resumable_nodes(workflow_id)
workflow_idWorkflow identifier.
List of node IDs that need to be re-executed.
store_conversation()
Store a conversation turn for context.
ProjectMemory$store_conversation(session_id, role, content, metadata = NULL)
session_idSession identifier.
roleMessage role ("user", "assistant", "system").
contentMessage content.
metadataOptional metadata list.
get_conversation()
Get conversation history for a session.
ProjectMemory$get_conversation(session_id, limit = 100)
session_idSession identifier.
limitMaximum number of messages.
A data frame of conversation messages.
store_review()
Store or update a human review for an AI-generated chunk.
ProjectMemory$store_review( chunk_id, file_path, chunk_label, prompt, response, status = "pending", ai_agent = NULL, uncertainty = NULL, session_id = NULL, review_mode = NULL, runtime_mode = NULL, artifact_json = NULL, execution_status = NULL, execution_output = NULL, final_code = NULL, error_message = NULL )
chunk_idUnique identifier for the chunk.
file_pathPath to the source file.
chunk_labelChunk label from knitr.
promptThe prompt sent to the AI.
responseThe AI's response.
statusReview status ("pending", "approved", "rejected").
ai_agentOptional agent name.
uncertaintyOptional uncertainty level.
session_idOptional session identifier for transcript/provenance.
review_modeOptional normalized review mode.
runtime_modeOptional normalized runtime mode.
artifact_jsonOptional JSON review artifact payload.
execution_statusOptional execution state.
execution_outputOptional execution output text.
final_codeOptional finalized executable code.
error_messageOptional execution or generation error.
The database row ID.
store_review_artifact()
Store structured review artifact metadata for a chunk.
ProjectMemory$store_review_artifact( chunk_id, artifact, session_id = NULL, review_mode = NULL, runtime_mode = NULL )
chunk_idChunk identifier.
artifactA serializable list representing the review artifact.
session_idOptional session identifier.
review_modeOptional normalized review mode.
runtime_modeOptional normalized runtime mode.
Invisible TRUE.
get_review()
Get a review by chunk ID.
ProjectMemory$get_review(chunk_id)
chunk_idChunk identifier.
A list with review details, or NULL if not found.
get_review_artifact()
Get a parsed review artifact by chunk ID.
ProjectMemory$get_review_artifact(chunk_id)
chunk_idChunk identifier.
A list artifact, or NULL if none is stored.
get_review_runtime_record()
Get a review together with its parsed artifact.
ProjectMemory$get_review_runtime_record(chunk_id)
chunk_idChunk identifier.
A list with review and artifact, or NULL if not found.
get_reviews_for_file()
Get all reviews for a given source file.
ProjectMemory$get_reviews_for_file(file_path)
file_pathSource document path.
A data frame of reviews ordered by updated time.
record_review_saveback()
Record a saveback lifecycle event for one or more chunk reviews.
ProjectMemory$record_review_saveback( chunk_ids, source_path, html_path = NULL, status = "requested", rerendered = FALSE, message = NULL )
chunk_idsCharacter vector of chunk identifiers.
source_pathSource document path.
html_pathOptional rendered HTML path.
statusSaveback status string.
rerenderedWhether a rerender occurred.
messageOptional message.
Invisible TRUE.
update_execution_result()
Update execution result fields for a chunk review.
ProjectMemory$update_execution_result( chunk_id, execution_status, execution_output = NULL, final_code = NULL, error_message = NULL )
chunk_idChunk identifier.
execution_statusExecution state string.
execution_outputOptional execution output text.
final_codeOptional finalized executable code.
error_messageOptional execution error.
Invisible TRUE.
append_review_event()
Append an audit event for a reviewed chunk.
ProjectMemory$append_review_event(chunk_id, event_type, payload = NULL)
chunk_idChunk identifier.
event_typeEvent type string.
payloadOptional serializable payload list.
The database row ID.
update_review_status()
Update review status.
ProjectMemory$update_review_status(chunk_id, status)
chunk_idChunk identifier.
statusNew status ("approved" or "rejected").
get_pending_reviews()
Get pending reviews, optionally filtered by file.
ProjectMemory$get_pending_reviews(file_path = NULL)
file_pathOptional file path filter.
A data frame of pending reviews.
stats()
Get memory statistics.
ProjectMemory$stats()
A list with counts and sizes.
clear()
Clear all memory (use with caution).
ProjectMemory$clear(confirm = FALSE)
confirmMust be TRUE to proceed.
print()
Print method for ProjectMemory.
ProjectMemory$print()
clone()
The objects of this class are cloneable with this method.
ProjectMemory$clone(deep = FALSE)
deepWhether to make a deep clone.
A dynamic factory for creating custom provider instances.
This allows users to instantiate a model provider at runtime by configuring
the endpoint (base_url), credentials (api_key), network protocol/routing (api_format),
and specific capabilities (use_max_completion_tokens), without writing a new Provider class.
Manages registered providers and allows accessing models by ID.
new()
Initialize the registry.
ProviderRegistry$new(separator = ":")
separatorThe separator between provider and model IDs (default: ":").
register()
Register a provider.
ProviderRegistry$register(id, provider)
idThe provider ID (e.g., "openai").
providerThe provider object (must have language_model method).
language_model()
Get a language model by ID.
ProviderRegistry$language_model(id)
idModel ID in the format "provider:model" (e.g., "openai:gpt-4o").
A LanguageModelV1 object.
embedding_model()
Get an embedding model by ID.
ProviderRegistry$embedding_model(id)
idModel ID in the format "provider:model".
An EmbeddingModelV1 object.
image_model()
Get an image model by ID.
ProviderRegistry$image_model(id)
idModel ID in the format "provider:model".
An ImageModelV1 object.
list_providers()
List all registered provider IDs.
ProviderRegistry$list_providers()
A character vector of provider IDs.
clone()
The objects of this class are cloneable with this method.
ProviderRegistry$clone(deep = FALSE)
deepWhether to make a deep clone.
Read-only helpers and built-in tools for inspecting live R session objects, functions, documentation, and source code.
General-purpose primitives that let a console Agent enrich diagnostic
context on its own when R's geterrmessage() / last.warning /
traceback() snapshots are incomplete.
These tools are intentionally broad (not problem-specific). Domain
tactics – e.g. where to look for an install log, how to interpret an
Rcpp compilation error – live in the r-debug skill (inst/skills/r-debug/).
The tools provide eyes and hands; the skill provides the playbook.
Provided tools:
r_eval: run R code in an isolated subprocess, capture stdout,
stderr (including from grandchild processes like compilers and
install.packages subprocesses), messages, warnings, value, error.
r_session_state: structured snapshot of the live R session
(.libPaths(), repos, search path, key env vars, options, sessionInfo).
Register an additional provider factory so it can be resolved through the
default registry's provider:model syntax. Intended for companion packages
(such as aisdk.providers) that ship OpenAI-compatible providers and
register them from their .onLoad hook, e.g.
aisdk::register_provider("deepseek", function() create_deepseek()).
Registration is load-order independent: the factory is replayed into the default registry whether it is registered before or after the registry is first built.
register_provider(id, factory)register_provider(id, factory)
id |
The provider ID (e.g. "deepseek"). |
factory |
A zero-argument function returning a provider object, or a
function of one argument ( |
Invisibly TRUE.
Forces R to re-read the .Renviron file without restarting the session. This is useful when you've modified .Renviron and don't want to restart R.
reload_env(path = ".Renviron")reload_env(path = ".Renviron")
path |
Path to .Renviron file (default: project root) |
Invisible TRUE if successful
if (interactive()) { # Reload environment after modifying .Renviron reload_env() # Now use the new keys Sys.getenv("OPENAI_API_KEY") }if (interactive()) { # Reload environment after modifying .Renviron reload_env() # Now use the new keys Sys.getenv("OPENAI_API_KEY") }
Render markdown-formatted text in the console with beautiful styling. This function uses the same rendering engine as the streaming output, supporting headers, lists, code blocks, and other markdown elements.
render_text(text)render_text(text)
text |
A character string containing markdown text, or a GenerateResult object. |
NULL (invisibly)
if (interactive()) { # Render simple text render_text("# Hello\n\nThis is **bold** text.") # Render with code block render_text("Here is some R code:\n\n```r\nx <- 1:10\nmean(x)\n```") }if (interactive()) { # Render simple text render_text("# Hello\n\nThis is **bold** text.") # Render with code block render_text("Here is some R code:\n\n```r\nx <- 1:10\nmean(x)\n```") }
Pauses execution and prompts the user for permission to execute a potentially
risky action. Supports console environments via readline.
request_authorization(action, risk_level = "YELLOW")request_authorization(action, risk_level = "YELLOW")
action |
Character string describing the action the Agent wants to perform. |
risk_level |
Character string. One of "GREEN", "YELLOW", "RED". |
Logical TRUE if user permits, otherwise throws an error with the rejection reason.
Resolve and validate the model selected for a capability route.
resolve_model_for_capability( capability, explicit_model = NULL, type = c("language", "embedding", "image"), required_model_capabilities = NULL, session = NULL, registry = NULL, fallback_model = NULL, default_model = NULL )resolve_model_for_capability( capability, explicit_model = NULL, type = c("language", "embedding", "image"), required_model_capabilities = NULL, session = NULL, registry = NULL, fallback_model = NULL, default_model = NULL )
capability |
Capability route name. |
explicit_model |
Optional explicit model override. |
type |
Expected model type: |
required_model_capabilities |
Optional required capability flags. |
session |
Optional |
registry |
Optional provider registry. |
fallback_model |
Optional model used when no route is configured. |
default_model |
Optional final fallback. If omitted for language models, the package default model is used. |
A resolved model object.
Resolve a symbol-like name against the live session environment, attached search path, and loaded namespaces.
resolve_r_binding( name, package = NULL, session = NULL, envir = NULL, scope = c("session", "workspace", "all"), prefer = c("auto", "object", "function") )resolve_r_binding( name, package = NULL, session = NULL, envir = NULL, scope = c("session", "workspace", "all"), prefer = c("auto", "object", "function") )
name |
Symbol-like name to resolve. |
package |
Optional package/namespace name to search first. |
session |
Optional |
envir |
Optional environment. Ignored when |
scope |
Where to resolve live objects before the search path:
|
prefer |
Preferred kind: |
A binding record list or NULL if not found.
Execute R code with a timeout to prevent infinite loops.
safe_eval(expr, timeout_seconds = 30, envir = parent.frame())safe_eval(expr, timeout_seconds = 30, envir = parent.frame())
expr |
Expression to evaluate. |
timeout_seconds |
Maximum execution time in seconds. |
envir |
Environment for evaluation. |
The result or an error.
Parses a JSON string, attempting to repair it using fix_json if
the initial parse fails.
safe_parse_json(text)safe_parse_json(text)
text |
A JSON string. |
A parsed R object (list, vector, etc.) or NULL if parsing fails even after repair.
safe_parse_json('{"a": 1}') safe_parse_json('{"a": 1,')safe_parse_json('{"a": 1}') safe_parse_json('{"a": 1,')
Standardized internal helper for JSON serialization with common defaults.
Object types registered via register_json_coercion() (for example ggplot
objects, via aisdk.datatools) are coerced before serialization.
safe_to_json(x, auto_unbox = TRUE, ...)safe_to_json(x, auto_unbox = TRUE, ...)
x |
Object to serialize. |
auto_unbox |
Whether to automatically unbox single-element vectors. Default TRUE. |
... |
Additional arguments to jsonlite::toJSON. |
A JSON string.
SandboxManager R6 class and utilities for building an R-native programmatic tool sandbox. Inspired by Anthropic's Programmatic Tool Calling, this module enables LLMs to write R code that batch-invokes registered tools and processes data locally (using dplyr/purrr), returning only concise results to the context.
The core idea: instead of the LLM making N separate tool calls (each requiring
a round-trip), it writes a single R script that loops over inputs, calls tools
as ordinary R functions, filters/aggregates the results with dplyr, and
print()s only the key findings. This dramatically reduces token usage,
latency, and context window pressure.
User tools -> SandboxManager -> isolated R environment - tool_a() - tool_b() - dplyr::* - purrr::* create_r_code_tool() -> single "execute_r_code" tool (registered with the LLM)
R6 class that manages an isolated R environment for executing LLM-generated R code. Tools are bound as callable functions within this environment, enabling the LLM to batch-invoke and process data locally.
new()
Initialize a new SandboxManager.
SandboxManager$new(
tools = list(),
preload_packages = c("dplyr", "purrr"),
max_output_chars = 8000,
parent_env = NULL
)toolsOptional list of Tool objects to bind into the sandbox.
preload_packagesCharacter vector of package names to preload into the sandbox (their exports become available). Default: c("dplyr", "purrr").
max_output_charsMaximum characters to capture from code output.
Prevents runaway print() from flooding the context. Default: 8000.
parent_envOptional parent environment for the sandbox.
When a ChatSession is available, pass session$get_envir() here
to enable cross-step variable persistence.
bind_tools()
Bind Tool objects into the sandbox as callable R functions.
SandboxManager$bind_tools(tools)
toolsA list of Tool objects to bind.
Invisible self (for chaining).
execute()
Execute R code in the sandbox environment.
SandboxManager$execute(code_str)
code_strA character string containing R code to execute.
A character string with captured stdout, or an error message.
get_tool_signatures()
Get human-readable signatures for all bound tools.
SandboxManager$get_tool_signatures()
A character string with Markdown-formatted tool documentation.
get_env()
Get the sandbox environment.
SandboxManager$get_env()
The R environment used by the sandbox.
list_tools()
Get list of bound tool names.
SandboxManager$list_tools()
Character vector of tool names available in the sandbox.
reset()
Reset the sandbox environment (clear all user variables). Tool bindings and preloaded packages are preserved.
SandboxManager$reset()
print()
Print method for SandboxManager.
SandboxManager$print()
clone()
The objects of this class are cloneable with this method.
SandboxManager$clone(deep = FALSE)
deepWhether to make a deep clone.
Convenience function to scan a directory and return a SkillRegistry. Alias for create_skill_registry().
scan_skills(path, recursive = FALSE)scan_skills(path, recursive = FALSE)
path |
Path to scan for skills. |
recursive |
Whether to scan subdirectories. Default FALSE. |
A populated SkillRegistry object.
A lightweight DSL (Domain Specific Language) for defining JSON Schema structures in R, inspired by Zod from TypeScript. Used for defining tool parameters.
Utilities to automatically generate z_schema objects from R function signatures.
Convert a z_schema object to a JSON string suitable for API calls. Handles the R-specific auto_unbox issues properly.
schema_to_json(schema, pretty = FALSE)schema_to_json(schema, pretty = FALSE)
schema |
A z_schema object created by z_* functions. |
pretty |
If TRUE, format JSON with indentation. |
A JSON string.
schema <- z_object( name = z_string(description = "User name") ) cat(schema_to_json(schema, pretty = TRUE))schema <- z_object( name = z_string(description = "User name") ) cat(schema_to_json(schema, pretty = TRUE))
Clears all protected variables.
sdk_clear_protected_vars()sdk_clear_protected_vars()
Get the current value of a feature flag.
sdk_feature(flag, default = NULL)sdk_feature(flag, default = NULL)
flag |
Name of the feature flag. |
default |
Default value if flag not set. |
The flag value.
if (interactive()) { # Check if shared session is enabled if (sdk_feature("use_shared_session")) { session <- create_shared_session(model = "openai:gpt-4o") } } else { session <- create_chat_session(model = "openai:gpt-4o") }if (interactive()) { # Check if shared session is enabled if (sdk_feature("use_shared_session")) { session <- create_shared_session(model = "openai:gpt-4o") } } else { session <- create_chat_session(model = "openai:gpt-4o") }
Get Metadata for a Protected Variable
sdk_get_var_metadata(name)sdk_get_var_metadata(name)
name |
Character string. The name of the variable. |
A list with metadata (locked, cost, etc.), or NULL if not protected.
Check if a Variable is Locked
sdk_is_var_locked(name)sdk_is_var_locked(name)
name |
Character string. The name of the variable. |
TRUE if the variable is protected and locked, FALSE otherwise.
List all available feature flags and their current values.
sdk_list_features()sdk_list_features()
A named list of feature flags.
if (interactive()) { # See all feature flags print(sdk_list_features()) }if (interactive()) { # See all feature flags print(sdk_list_features()) }
Marks a variable as protected so that the Agent cannot accidentally overwrite, shadow, or deeply copy it during sandbox execution.
sdk_protect_var(name, locked = TRUE, cost = "High")sdk_protect_var(name, locked = TRUE, cost = "High")
name |
Character string. The name of the variable to protect. |
locked |
Logical. If TRUE, the variable cannot be assigned to by the Agent. |
cost |
Character string. An indicator of the variable's computation/memory cost (e.g., "High", "Medium", "Low"). |
Invisible TRUE.
Reset all feature flags to their default values.
sdk_reset_features()sdk_reset_features()
Invisible NULL.
Set a feature flag value. Use this to enable/disable SDK features.
sdk_set_feature(flag, value)sdk_set_feature(flag, value)
flag |
Name of the feature flag. |
value |
Value to set. |
Invisible previous value.
if (interactive()) { # Disable shared session for legacy compatibility sdk_set_feature("use_shared_session", FALSE) # Enable legacy tool format sdk_set_feature("legacy_tool_format", TRUE) }if (interactive()) { # Disable shared session for legacy compatibility sdk_set_feature("use_shared_session", FALSE) # Enable legacy tool format sdk_set_feature("legacy_tool_format", TRUE) }
Removes protection from a previously protected variable.
sdk_unprotect_var(name)sdk_unprotect_var(name)
name |
Character string. The name of the variable to unprotect. |
Invisible TRUE.
Internal semantic adapter protocol and registry for object-aware context construction and inspection.
ChatSession R6 class for managing stateful conversations with LLMs. Provides automatic history management, persistence, and model switching.
Set the model used for a named capability. For example, the default chat
model can remain a low-cost text model while vision.inspect uses a
vision-capable language model and image.generate uses an image model.
set_capability_model( capability, model, type = "auto", required_model_capabilities = NULL )set_capability_model( capability, model, type = "auto", required_model_capabilities = NULL )
capability |
Capability route name, such as |
model |
Model ID string or model object. Passing |
type |
Model type for this route: |
required_model_capabilities |
Optional model capability flags required
by this route, such as |
Invisibly returns the previous model for the route, or the previous route list for batch updates.
old <- set_capability_model("vision.inspect", "openai:gpt-4o") get_capability_model("vision.inspect") set_capability_model("vision.inspect", old)old <- set_capability_model("vision.inspect", "openai:gpt-4o") get_capability_model("vision.inspect") set_capability_model("vision.inspect", old)
Apply adaptive context-management settings to a session.
set_context_management_config( session, config = NULL, mode = NULL, llm_synthesis = NULL, synthesis_model = NULL, llm_synthesis_policy = NULL, context_window_override = NULL, max_output_tokens_override = NULL, project_memory_root = NULL, retrieval_providers = NULL, retrieval_provider_order = NULL, retrieval_provider_limits = NULL, retrieval_min_hits = NULL, retrieval_scoring_policy = NULL, retrieval_reranking = NULL, retrieval_reranking_model = NULL, retrieval_reranking_policy = NULL )set_context_management_config( session, config = NULL, mode = NULL, llm_synthesis = NULL, synthesis_model = NULL, llm_synthesis_policy = NULL, context_window_override = NULL, max_output_tokens_override = NULL, project_memory_root = NULL, retrieval_providers = NULL, retrieval_provider_order = NULL, retrieval_provider_limits = NULL, retrieval_min_hits = NULL, retrieval_scoring_policy = NULL, retrieval_reranking = NULL, retrieval_reranking_model = NULL, retrieval_reranking_policy = NULL )
session |
A |
config |
Optional config list created by |
mode |
Optional override for config mode. |
llm_synthesis |
Optional override for config LLM synthesis flag. |
synthesis_model |
Optional override for config synthesis model. |
llm_synthesis_policy |
Optional override for config LLM synthesis policy. |
context_window_override |
Optional override for context window. |
max_output_tokens_override |
Optional override for max output tokens. |
project_memory_root |
Optional override for project memory root. |
retrieval_providers |
Optional override for retrieval-provider selection. |
retrieval_provider_order |
Optional override for provider ranking/order. |
retrieval_provider_limits |
Optional override for per-provider limits. |
retrieval_min_hits |
Optional override for per-provider matching thresholds. |
retrieval_scoring_policy |
Optional override for cross-provider scoring policy. |
retrieval_reranking |
Optional override for learned reranking enablement. |
retrieval_reranking_model |
Optional override for the reranker model. |
retrieval_reranking_policy |
Optional override for reranking policy. |
Invisible session.
Sets the package-wide default language model. Pass NULL to restore the
built-in default ("openai:gpt-4o" unless overridden with
options(aisdk.default_model = ...)). If new is omitted and runtime
options are supplied, only the runtime options are updated.
set_model( new = NULL, context_window = NULL, max_output_tokens = NULL, max_tokens = NULL, thinking = NULL, thinking_budget = NULL, reasoning_effort = NULL, reset_options = FALSE )set_model( new = NULL, context_window = NULL, max_output_tokens = NULL, max_tokens = NULL, thinking = NULL, thinking_budget = NULL, reasoning_effort = NULL, reset_options = FALSE )
new |
A model identifier string, a |
context_window |
Optional context-window override used by sessions created from this default model. |
max_output_tokens |
Optional maximum output-token metadata override. |
max_tokens |
Optional default generation token limit. |
thinking |
Optional default thinking-mode value passed to providers that support it. Logical values are normalized by each provider. |
thinking_budget |
Optional default thinking budget. |
reasoning_effort |
Optional default reasoning effort ( |
reset_options |
Logical. If |
Invisibly returns the previous default model.
old <- set_model("deepseek:deepseek-chat") current <- get_model() set_model(old) set_model(NULL)old <- set_model("deepseek:deepseek-chat") current <- get_model() set_model(old) set_model(NULL)
R6 class representing a skill with progressive loading capabilities. A Skill consists of:
Level 1: YAML frontmatter (name, description) - always loaded
Level 2: SKILL.md body (detailed instructions) - on demand
Level 3: R scripts (executable code) - executed by agent
nameThe unique name of the skill (from YAML frontmatter).
descriptionA brief description of the skill (from YAML frontmatter).
aliasesOptional aliases that should also trigger this skill.
when_to_useOptional triggering guidance for this skill.
pathsOptional file glob patterns that make this skill relevant.
pathThe directory path containing the skill files.
manifestRaw YAML frontmatter parsed from SKILL.md.
new()
Create a new Skill object by parsing a SKILL.md file.
Skill$new(path)
pathPath to the skill directory (containing SKILL.md).
A new Skill object.
load()
Load the full SKILL.md body content (Level 2).
Skill$load()
Character string containing the skill instructions.
get_manifest()
Return the raw SKILL.md frontmatter as a list.
Skill$get_manifest()
Named list of metadata fields.
to_store_record()
Export the skill to a structured record suitable for a skill store.
Skill$to_store_record( include_body = TRUE, include_files = TRUE, include_assets = FALSE )
include_bodyInclude the full SKILL.md body in the record.
include_filesInclude textual source files from the skill folder.
include_assetsInclude a list of asset file names.
A named list ready for JSON serialization.
metadata_text()
Return concise metadata text used for routing and listing.
Skill$metadata_text()
Character scalar.
matches_paths()
Check whether the skill's paths patterns match any provided file paths.
Skill$matches_paths(file_paths = character(0), cwd = NULL)
file_pathsCharacter vector of file paths.
cwdOptional working directory used to relativize absolute paths.
Logical scalar.
execute_script()
Execute an R script from the skill's scripts directory (Level 3). Uses callr for safe, isolated execution.
Skill$execute_script(script_name, args = list())
script_nameName of the script file (e.g., "normalize.R").
argsNamed list of arguments to pass to the script.
The result from the script execution.
list_scripts()
List available scripts in the skill's scripts directory.
Skill$list_scripts()
Character vector of script file names.
list_resources()
List available reference files in the skill's references directory.
Skill$list_resources()
Character vector of reference file names.
read_resource()
Read content of a reference file from the references directory.
Skill$read_resource(resource_name)
resource_nameName of the reference file.
Character string containing the resource content.
get_asset_path()
Get the absolute path to an asset in the assets directory.
Skill$get_asset_path(asset_name)
asset_nameName of the asset file or directory.
Absolute path string.
print()
Print a summary of the skill.
Skill$print()
clone()
The objects of this class are cloneable with this method.
Skill$clone(deep = FALSE)
deepWhether to make a deep clone.
SkillRegistry class for discovering, caching, and retrieving skills. Scans directories for SKILL.md files and provides access to skill metadata.
R6 class that manages a collection of skills. Provides methods to:
Scan directories for SKILL.md files
Cache skill metadata (Level 1)
Retrieve skills by name
Generate prompt sections for LLM context
new()
Create a new SkillRegistry, optionally scanning a directory.
SkillRegistry$new(path = NULL, recursive = FALSE)
pathOptional path to scan for skills on creation.
recursiveWhether to scan subdirectories when path is provided.
A new SkillRegistry object.
scan_skills()
Scan a directory for skill folders containing SKILL.md files.
SkillRegistry$scan_skills(path, recursive = FALSE, remember = TRUE)
pathPath to the directory to scan.
recursiveWhether to scan subdirectories. Default FALSE.
rememberWhether this root should be remembered for refresh().
The registry object (invisibly), for chaining.
refresh()
Re-scan remembered skill roots so updates on disk become visible.
SkillRegistry$refresh(clear = TRUE)
clearIf TRUE, clears currently loaded skills before re-scanning.
The registry object (invisibly).
list_roots()
List skill roots remembered by this registry.
SkillRegistry$list_roots()
A data frame with root path and recursive flag.
get_skill()
Get a skill by name.
SkillRegistry$get_skill(name)
nameThe name of the skill to retrieve.
The Skill object, or NULL if not found.
resolve_skill_name()
Resolve a skill name or alias to its canonical name.
SkillRegistry$resolve_skill_name(name)
nameSkill name or alias.
Canonical skill name or NULL.
find_closest_skill_name()
Find the closest matching canonical skill name for fuzzy recovery.
SkillRegistry$find_closest_skill_name(name)
nameSkill name or alias candidate.
Canonical skill name or NULL.
has_skill()
Check if a skill exists in the registry.
SkillRegistry$has_skill(name)
nameThe name of the skill to check.
TRUE if the skill exists, FALSE otherwise.
list_skills()
List all registered skills with their names and descriptions.
SkillRegistry$list_skills()
A data.frame with columns: name, description.
count()
Get the number of registered skills.
SkillRegistry$count()
Integer count of skills.
find_relevant_skills()
Find relevant skills for a user query and optional file paths.
SkillRegistry$find_relevant_skills( query = NULL, file_paths = character(0), cwd = NULL, limit = 3L )
queryOptional user query text.
file_pathsOptional character vector of file paths.
cwdOptional working directory for path matching.
limitMaximum number of results to return.
Data frame of matching skills sorted by score.
generate_prompt_section()
Generate a prompt section listing available skills. This can be injected into the system prompt.
SkillRegistry$generate_prompt_section()
Character string with formatted skill list.
print()
Print a summary of the registry.
SkillRegistry$print()
clone()
The objects of this class are cloneable with this method.
SkillRegistry$clone(deep = FALSE)
deepWhether to make a deep clone.
Factory functions for creating standard library agents with scoped tools and safety guardrails. These agents form the foundation of the multi-agent orchestration system.
Implements the Strategy pattern for handling different structured output formats from LLMs. This allows the SDK to be extended with new output types (e.g., objects, enums, dataframes) without modifying core logic.
Stream image generation with partial-image previews, useful for showing
the user progressive renders before the final image arrives. Currently
implemented for OpenAI's Responses API (partial_images 0–3); other
providers raise an informative error directing callers back to
generate_image().
stream_image( model, prompt, callback, output_dir = tempdir(), partial_images = 2, registry = NULL, ... )stream_image( model, prompt, callback, output_dir = tempdir(), partial_images = 2, registry = NULL, ... )
model |
An |
prompt |
Prompt describing the desired image. |
callback |
A function called for each partial/final event. The event
is a named list with |
output_dir |
Directory where the final image is written. Defaults to
|
partial_images |
Integer 0–3 — how many preview frames to request.
Defaults to |
registry |
Optional provider registry. |
... |
Additional arguments passed to the model implementation
(e.g. |
A GenerateImageResult with the final image.
## Not run: provider <- create_openai() model <- provider$image_model("gpt-image-1.5") stream_image(model, "a glowing nebula", callback = function(event) { if (event$type == "partial") { message(sprintf("Preview #%d (%d bytes)", event$index, length(event$bytes))) } else { message("Final image arrived: ", length(event$bytes), " bytes") } }) ## End(Not run)## Not run: provider <- create_openai() model <- provider$image_model("gpt-image-1.5") stream_image(model, "a glowing nebula", callback = function(event) { if (event$type == "partial") { message(sprintf("Preview #%d (%d bytes)", event$index, length(event$bytes))) } else { message("Final image arrived: ", length(event$bytes), " bytes") } }) ## End(Not run)
Generate text using a language model with streaming output. This function provides a real-time stream of tokens through a callback.
stream_text( model = NULL, prompt, callback = NULL, system = NULL, temperature = 0.7, max_tokens = NULL, tools = NULL, max_steps = 1, max_tool_result_errors = 2, require_post_tool_protocol = FALSE, sandbox = FALSE, skills = NULL, session = NULL, hooks = NULL, registry = NULL, renderer = NULL, .stream_event_callback = NULL, ... )stream_text( model = NULL, prompt, callback = NULL, system = NULL, temperature = 0.7, max_tokens = NULL, tools = NULL, max_steps = 1, max_tool_result_errors = 2, require_post_tool_protocol = FALSE, sandbox = FALSE, skills = NULL, session = NULL, hooks = NULL, registry = NULL, renderer = NULL, .stream_event_callback = NULL, ... )
model |
Either a LanguageModelV1 object, or a string ID like "openai:gpt-4o". |
prompt |
A character string prompt, or a list of messages. |
callback |
A function called for each text chunk: |
system |
Optional system prompt. |
temperature |
Sampling temperature (0-2). Default 0.7. |
max_tokens |
Maximum tokens to generate. |
tools |
Optional list of Tool objects for function calling. |
max_steps |
Number of model/tool steps in one execution window. Default 1. The runtime treats this as a budget checkpoint, not as a hard task stop. |
max_tool_result_errors |
Historical compatibility option. Tool result errors are recorded as task observations; runtime policy decides whether to continue, finalize, ask the user, or block. |
require_post_tool_protocol |
Logical. If TRUE, after any tool results
are returned the model must either make another tool call or wrap its final
answer in a |
sandbox |
Logical. If TRUE, enables R-native programmatic sandbox mode.
See |
skills |
Optional path to skills directory, or a SkillRegistry object. |
session |
Optional ChatSession object for shared state. |
hooks |
Optional HookHandler object. |
registry |
Optional ProviderRegistry to use. |
renderer |
Optional Renderer for agent output. Defaults to the cli
terminal backend ( |
.stream_event_callback |
Internal callback for typed stream events. |
... |
Additional arguments passed to the model. |
A GenerateResult object (accumulated from the stream).
if (interactive()) { model <- create_openai()$language_model("gpt-4o") stream_text(model, "Tell me a story", callback = function(text, done) { if (!done) cat(text) }) }if (interactive()) { model <- create_openai()$language_model("gpt-4o") stream_text(model, "Tell me a story", callback = function(text, done) { if (!done) cat(text) }) }
Creates a scoped child ChatSession for a focused task. The child uses an
environment whose parent is the parent session environment, so writes stay in
the child scope. Only a compact result summary and trace are written back to
the parent context state.
sub_session_query( session, task, context_handles = NULL, max_turns = 3L, budget = NULL, timeout = NULL )sub_session_query( session, task, context_handles = NULL, max_turns = 3L, budget = NULL, timeout = NULL )
session |
Parent |
task |
Focused child task. |
context_handles |
Optional context handle IDs to summarize for the child. |
max_turns |
Maximum child generation/tool turns. |
budget |
Optional budget metadata recorded in the result. |
timeout |
Optional timeout in seconds. Currently recorded as metadata. |
A compact sub-session result list.
R6 class for logging events in a structured format (JSON).
trace_idCurrent trace ID for the session.
eventsCollected telemetry events for in-memory inspection.
emitLogical; when TRUE, events are printed as JSON lines.
pricing_tablePricing for common models (USD per 1M tokens).
new()
Initialize Telemetry
Telemetry$new(trace_id = NULL, emit = TRUE)
trace_idOptional trace ID. If NULL, generates a random one.
emitLogical; when TRUE, events are printed as JSON lines.
log_event()
Log an event
Telemetry$log_event(type, ...)
typeEvent type (e.g., "generation_start", "tool_call").
...Additional fields to log.
get_events()
Return collected telemetry events.
Telemetry$get_events()
A list of event payloads.
clear_events()
Clear collected telemetry events.
Telemetry$clear_events()
Invisibly returns self.
as_hooks()
Create hooks for telemetry
Telemetry$as_hooks()
A HookHandler object pre-configured with telemetry logs.
calculate_cost()
Calculate estimated cost for a generation result
Telemetry$calculate_cost(result, model_id = NULL)
resultThe GenerateResult object.
model_idOptional model ID string. if NULL, tries to guess from context (not reliable yet, passing in log_event might be better).
Estimated cost in USD, or NULL if unknown.
clone()
The objects of this class are cloneable with this method.
Telemetry$clone(deep = FALSE)
deepWhether to make a deep clone.
Factory function to create a Tool object. This is the recommended way to define tools for LLM function calling.
tool( name, description, parameters = NULL, execute = NULL, layer = "llm", meta = NULL )tool( name, description, parameters = NULL, execute = NULL, layer = "llm", meta = NULL )
name |
Unique tool name (used by LLM to call the tool). |
description |
Description of the tool's purpose. Be descriptive to help the LLM understand when to use this tool. |
parameters |
A z_schema object (z_object/z_any/etc), a named list, a character vector, or NULL. When NULL, the schema is inferred from the execute function signature (if possible) and defaults to flexible types. |
execute |
An R function that implements the tool logic. It can accept a single list argument (args), or standard named parameters. List-style functions receive a single list argument containing parameters. |
layer |
Tool layer: "llm" (loaded into context) or "computer" (executed via bash/filesystem). Default is "llm". Computer layer tools are not loaded into context but executed via bash. |
meta |
Optional metadata associated with the tool (e.g., |
A Tool object.
if (interactive()) { # Define a weather tool get_weather <- tool( name = "get_weather", description = "Get the current weather for a location", parameters = z_object( location = z_string(description = "The city name, e.g., 'Beijing'"), unit = z_enum(c("celsius", "fahrenheit"), description = "Temperature unit") ), execute = function(args) { # In real usage, call a weather API here paste("Weather in", args$location, "is 22 degrees", args$unit) } ) # Use with generate_text result <- generate_text( model = "openai:gpt-4o", prompt = "What's the weather in Tokyo?", tools = list(get_weather) ) }if (interactive()) { # Define a weather tool get_weather <- tool( name = "get_weather", description = "Get the current weather for a location", parameters = z_object( location = z_string(description = "The city name, e.g., 'Beijing'"), unit = z_enum(c("celsius", "fahrenheit"), description = "Temperature unit") ), execute = function(args) { # In real usage, call a weather API here paste("Weather in", args$location, "is 22 degrees", args$unit) } ) # Use with generate_text result <- generate_text( model = "openai:gpt-4o", prompt = "What's the weather in Tokyo?", tools = list(get_weather) ) }
R6 class representing a callable tool for LLM function calling. A Tool connects an LLM's tool call request to an R function.
nameThe unique name of the tool.
descriptionA description of what the tool does.
parametersA z_object schema defining the tool's parameters.
layerTool layer: "llm" (loaded into context) or "computer" (executed via bash/filesystem).
metaOptional metadata for the tool (e.g., caching configuration).
new()
Initialize a Tool.
Tool$new(name, description, parameters, execute, layer = "llm", meta = NULL)
nameUnique tool name (used by LLM to call the tool).
descriptionDescription of the tool's purpose.
parametersA z_object schema defining expected parameters.
executeAn R function that implements the tool logic.
layerTool layer: "llm" or "computer" (default: "llm").
metaOptional metadata list (e.g., cache_control).
to_api_format()
Convert tool to API format.
Tool$to_api_format(provider = "openai")
providerProvider name ("openai" or "anthropic"). Default "openai".
A list in the format expected by the API.
run()
Execute the tool with given arguments.
Tool$run(args, envir = NULL)
argsA list or named list of arguments.
envirOptional environment in which to evaluate the tool function.
When provided, the environment is passed as .envir in the args list,
allowing the execute function to access and modify session variables.
The result of executing the tool function.
print()
Print method for Tool.
Tool$print()
clone()
The objects of this class are cloneable with this method.
Tool$clone(deep = FALSE)
deepWhether to make a deep clone.
Updates or appends environment variables to the .Renviron file.
update_renviron(updates, path = ".Renviron")update_renviron(updates, path = ".Renviron")
updates |
A named list of key-value pairs to update. |
path |
Path to .Renviron file (default: project root) |
Invisible TRUE if successful
Internal helpers to capture printed output, messages, and warnings from evaluated R expressions so tool execution can be rendered cleanly in the console UI.
Provides standardized HTTP request handling with exponential backoff retry.
Implements multi-layer defense strategy for handling API responses:
Empty response body handling (returns instead of parse error)
JSON parsing with repair fallback
SSE stream error recovery
Graceful degradation on malformed data
Provides robust utilities for parsing potentially truncated or malformed JSON strings, commonly encountered in streaming LLM outputs.
A robust utility that uses a finite state machine to close open brackets, braces, and quotes to make a truncated JSON string valid for parsing.
fix_json(json_str)fix_json(json_str)
json_str |
A potentially truncated JSON string. |
A repaired JSON string.
fix_json('{"name": "Gene...') fix_json('[1, 2, {"a":')fix_json('{"name": "Gene...') fix_json('[1, 2, {"a":')
Provides middleware functionality to wrap and enhance language models. Middleware can transform parameters and wrap generate/stream operations.
A registry for managing AI model providers.
Supports the provider:model syntax for accessing models.
Provides a mechanism to protect specific variables from being accidentally modified or duplicated by the Agent within the sandbox environment.
Recursively traverse an R expression and apply a visitor function to each node.
walk_ast(expr, visitor)walk_ast(expr, visitor)
expr |
An R expression, call, or primitive type. |
visitor |
A function taking a node as argument. |
Wraps a LanguageModelV1 with one or more middleware instances. Middleware is applied in order: first middleware transforms first, last middleware wraps closest to the model.
wrap_language_model(model, middleware, model_id = NULL, provider_id = NULL)wrap_language_model(model, middleware, model_id = NULL, provider_id = NULL)
model |
A LanguageModelV1 object. |
middleware |
A single Middleware object or a list of Middleware objects. |
model_id |
Optional custom model ID. |
provider_id |
Optional custom provider ID. |
A new LanguageModelV1 object with middleware applied.
Create a JSON Schema that accepts any JSON value.
z_any(description = NULL, nullable = TRUE, default = NULL)z_any(description = NULL, nullable = TRUE, default = NULL)
description |
Optional description of the field. |
nullable |
If TRUE, allows null values. |
default |
Optional default value. |
A list representing JSON Schema for any value.
z_any(description = "Flexible input")z_any(description = "Flexible input")
Create a JSON Schema for array type.
z_array( items, description = NULL, nullable = FALSE, default = NULL, min_items = NULL, max_items = NULL )z_array( items, description = NULL, nullable = FALSE, default = NULL, min_items = NULL, max_items = NULL )
items |
Schema for array items (created by z_* functions). |
description |
Optional description of the field. |
nullable |
If TRUE, allows null values. |
default |
Optional default value. |
min_items |
Optional minimum number of items. |
max_items |
Optional maximum number of items. |
A list representing JSON Schema for array.
z_array(z_string(), description = "List of names")z_array(z_string(), description = "List of names")
Create a JSON Schema for boolean type.
z_boolean(description = NULL, nullable = FALSE, default = NULL)z_boolean(description = NULL, nullable = FALSE, default = NULL)
description |
Optional description of the field. |
nullable |
If TRUE, allows null values. |
default |
Optional default value. |
A list representing JSON Schema for boolean.
z_boolean(description = "Whether to include details")z_boolean(description = "Whether to include details")
Create a schema that represents a dataframe (or list of row objects).
This is an R-specific convenience function that generates a JSON Schema
for an array of objects. The LLM will be instructed to output data in a
format that can be easily converted to an R dataframe using
dplyr::bind_rows() or do.call(rbind, lapply(..., as.data.frame)).
Create a schema that represents a dataframe (or list of row objects). This is an R-specific convenience function that generates a JSON Schema for an array of objects.
z_dataframe( ..., .description = NULL, .nullable = FALSE, .default = NULL, .min_rows = NULL, .max_rows = NULL )z_dataframe( ..., .description = NULL, .nullable = FALSE, .default = NULL, .min_rows = NULL, .max_rows = NULL )
... |
Named arguments where names are column names and values are z_schema objects representing the column types. |
.description |
Optional description of the dataframe. |
.nullable |
If TRUE, allows null values. |
.default |
Optional default value. |
.min_rows |
Optional minimum number of rows. |
.max_rows |
Optional maximum number of rows. |
A z_schema object representing an array of objects.
A z_schema object representing an array of objects.
# Define a schema for a dataframe of genes gene_schema <- z_dataframe( gene_name = z_string(description = "Name of the gene"), expression = z_number(description = "Expression level"), significant = z_boolean(description = "Is statistically significant") ) # Use with generate_object # result <- generate_object(model, "Extract gene data...", gene_schema) # df <- dplyr::bind_rows(result$object)# Define a schema for a dataframe of genes gene_schema <- z_dataframe( gene_name = z_string(description = "Name of the gene"), expression = z_number(description = "Expression level"), significant = z_boolean(description = "Is statistically significant") ) # Use with generate_object # result <- generate_object(model, "Extract gene data...", gene_schema) # df <- dplyr::bind_rows(result$object)
Add a description to a z_schema object (pipe-friendly).
z_describe(schema, description)z_describe(schema, description)
schema |
A z_schema object. |
description |
The description string. |
The modified z_schema object.
Create a JSON Schema for an empty object {}.
z_empty_object(description = NULL)z_empty_object(description = NULL)
description |
Optional description. |
A z_schema object.
Create a JSON Schema for string enum type.
z_enum(values, description = NULL, nullable = FALSE, default = NULL)z_enum(values, description = NULL, nullable = FALSE, default = NULL)
values |
Character vector of allowed values. |
description |
Optional description of the field. |
nullable |
If TRUE, allows null values. |
default |
Optional default value. |
A list representing JSON Schema for enum.
z_enum(c("celsius", "fahrenheit"), description = "Temperature unit")z_enum(c("celsius", "fahrenheit"), description = "Temperature unit")
Create a JSON Schema for integer type.
z_integer( description = NULL, nullable = FALSE, default = NULL, minimum = NULL, maximum = NULL )z_integer( description = NULL, nullable = FALSE, default = NULL, minimum = NULL, maximum = NULL )
description |
Optional description of the field. |
nullable |
If TRUE, allows null values. |
default |
Optional default value. |
minimum |
Optional minimum value. |
maximum |
Optional maximum value. |
A list representing JSON Schema for integer.
z_integer(description = "Number of items", minimum = 0)z_integer(description = "Number of items", minimum = 0)
Create a JSON Schema for number (floating point) type.
z_number( description = NULL, nullable = FALSE, default = NULL, minimum = NULL, maximum = NULL )z_number( description = NULL, nullable = FALSE, default = NULL, minimum = NULL, maximum = NULL )
description |
Optional description of the field. |
nullable |
If TRUE, allows null values. |
default |
Optional default value. |
minimum |
Optional minimum value. |
maximum |
Optional maximum value. |
A list representing JSON Schema for number.
z_number(description = "Temperature value", minimum = -100, maximum = 100)z_number(description = "Temperature value", minimum = -100, maximum = 100)
Create a JSON Schema for object type. This is the primary schema builder for defining tool parameters.
z_object( ..., .description = NULL, .required = NULL, .additional_properties = FALSE )z_object( ..., .description = NULL, .required = NULL, .additional_properties = FALSE )
... |
Named arguments where names are property names and values are z_schema objects created by z_* functions. |
.description |
Optional description of the object. |
.required |
Character vector of required field names. If NULL (default), all fields are considered required. |
.additional_properties |
Whether to allow additional properties. Default FALSE. |
A list representing JSON Schema for object.
z_object( location = z_string(description = "City name, e.g., Beijing"), unit = z_enum(c("celsius", "fahrenheit"), description = "Temperature unit") )z_object( location = z_string(description = "City name, e.g., Beijing"), unit = z_enum(c("celsius", "fahrenheit"), description = "Temperature unit") )
Create a JSON Schema for string type.
z_string( description = NULL, nullable = FALSE, default = NULL, min_length = NULL, max_length = NULL )z_string( description = NULL, nullable = FALSE, default = NULL, min_length = NULL, max_length = NULL )
description |
Optional description of the field. |
nullable |
If TRUE, allows null values. |
default |
Optional default value. |
min_length |
Optional minimum string length. |
max_length |
Optional maximum string length. |
A list representing JSON Schema for string.
z_string(description = "The city name")z_string(description = "The city name")